text
stringlengths
1
1.05M
dnl AMD K6-2 mpn_rshift -- mpn right shift. dnl Copyright 1999, 2000, 2002 Free Software Foundation, Inc. dnl dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 2.1 of the dnl License, or (at your option) any later version. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public dnl License along with the GNU MP Library; see the file COPYING.LIB. If dnl not, write to the Free Software Foundation, Inc., 51 Franklin Street, dnl Fifth Floor, Boston, MA 02110-1301, USA. include(`../config.m4') C K6-2: 1.75 cycles/limb C mp_limb_t mpn_rshift (mp_ptr dst, mp_srcptr src, mp_size_t size, C unsigned shift); C defframe(PARAM_SHIFT,16) defframe(PARAM_SIZE, 12) defframe(PARAM_SRC, 8) defframe(PARAM_DST, 4) deflit(`FRAME',0) dnl Minimum 9, because the unrolled loop can't handle less. dnl deflit(UNROLL_THRESHOLD, 9) TEXT ALIGN(32) PROLOGUE(mpn_rshift) deflit(`FRAME',0) C The 1 limb case can be done without the push %ebx, but it's then C still the same speed. The push is left as a free helping hand for C the two_or_more code. movl PARAM_SIZE, %eax pushl %ebx FRAME_pushl() movl PARAM_SRC, %ebx decl %eax movl PARAM_SHIFT, %ecx jnz L(two_or_more) movl (%ebx), %edx C src limb movl PARAM_DST, %ebx shrdl( %cl, %edx, %eax) C return value shrl %cl, %edx movl %edx, (%ebx) C dst limb popl %ebx ret C ----------------------------------------------------------------------------- ALIGN(16) C avoid offset 0x1f L(two_or_more): C eax size-1 C ebx src C ecx shift C edx movl (%ebx), %edx C src low limb negl %ecx addl $32, %ecx movd PARAM_SHIFT, %mm6 shll %cl, %edx cmpl $UNROLL_THRESHOLD-1, %eax jae L(unroll) C eax size-1 C ebx src C ecx 32-shift C edx retval C C mm6 shift movl PARAM_DST, %ecx leal (%ebx,%eax,4), %ebx leal -4(%ecx,%eax,4), %ecx negl %eax C This loop runs at about 3 cycles/limb, which is the amount of C decoding, and this is despite every second access being unaligned. L(simple): C eax counter, -(size-1) to -1 C ebx &src[size-1] C ecx &dst[size-1] C edx retval C C mm0 scratch C mm6 shift Zdisp( movq, 0,(%ebx,%eax,4), %mm0) incl %eax psrlq %mm6, %mm0 Zdisp( movd, %mm0, 0,(%ecx,%eax,4)) jnz L(simple) movq %mm0, (%ecx) movl %edx, %eax popl %ebx femms ret C ----------------------------------------------------------------------------- ALIGN(16) L(unroll): C eax size-1 C ebx src C ecx 32-shift C edx retval C C mm6 shift addl $32, %ecx subl $7, %eax C size-8 movd %ecx, %mm7 movl PARAM_DST, %ecx movq (%ebx), %mm2 C src low qword leal (%ebx,%eax,4), %ebx C src end - 32 testb $4, %cl leal (%ecx,%eax,4), %ecx C dst end - 32 notl %eax C -(size-7) jz L(dst_aligned) psrlq %mm6, %mm2 incl %eax Zdisp( movd, %mm2, 0,(%ecx,%eax,4)) C dst low limb movq 4(%ebx,%eax,4), %mm2 C new src low qword L(dst_aligned): movq 12(%ebx,%eax,4), %mm0 C src second lowest qword nop C avoid bad cache line crossing C This loop is the important bit, the rest is just support for it. C Four src limbs are held at the start, and four more will be read. C Four dst limbs will be written. This schedule seems necessary for C full speed. C C The use of -(size-7) lets the loop stop when %eax becomes >= 0 and C and leaves 0 to 3 which can be tested with test $1 and $2. L(top): C eax counter, -(size-7) step by +4 until >=0 C ebx src end - 32 C ecx dst end - 32 C edx retval C C mm0 src next qword C mm1 scratch C mm2 src prev qword C mm6 shift C mm7 64-shift psrlq %mm6, %mm2 addl $4, %eax movq %mm0, %mm1 psllq %mm7, %mm0 por %mm0, %mm2 movq 4(%ebx,%eax,4), %mm0 psrlq %mm6, %mm1 movq %mm2, -12(%ecx,%eax,4) movq %mm0, %mm2 psllq %mm7, %mm0 por %mm0, %mm1 movq 12(%ebx,%eax,4), %mm0 movq %mm1, -4(%ecx,%eax,4) ja L(top) C jump if no carry and not zero C Now have the four limbs in mm2 (low) and mm0 (high), and %eax is 0 C to 3 representing respectively 3 to 0 further limbs. testl $2, %eax C testl to avoid bad cache line crossings jnz L(finish_nottwo) C Two or three extra limbs: rshift mm2, OR it with lshifted mm0, mm0 C becomes new mm2 and a new mm0 is loaded. psrlq %mm6, %mm2 movq %mm0, %mm1 psllq %mm7, %mm0 addl $2, %eax por %mm0, %mm2 movq 12(%ebx,%eax,4), %mm0 movq %mm2, -4(%ecx,%eax,4) movq %mm1, %mm2 L(finish_nottwo): testb $1, %al psrlq %mm6, %mm2 movq %mm0, %mm1 psllq %mm7, %mm0 por %mm0, %mm2 psrlq %mm6, %mm1 movq %mm2, 4(%ecx,%eax,4) jnz L(finish_even) C one further extra limb to process movd 32-4(%ebx), %mm0 C src[size-1], most significant limb popl %ebx movq %mm0, %mm2 psllq %mm7, %mm0 por %mm0, %mm1 psrlq %mm6, %mm2 movq %mm1, 32-12(%ecx) C dst[size-3,size-2] movd %mm2, 32-4(%ecx) C dst[size-1] movl %edx, %eax C retval femms ret nop C avoid bad cache line crossing L(finish_even): C no further extra limbs movq %mm1, 32-8(%ecx) C dst[size-2,size-1] movl %edx, %eax C retval popl %ebx femms ret EPILOGUE()
; A253476: Indices of centered triangular numbers (A005448) which are also centered heptagonal numbers (A069099). ; Submitted by Jamie Morken(s1) ; 1,15,70,1596,7645,175491,840826,19302360,92483161,2123084055,10172306830,233519943636,1118861268085,25685070715851,123064567182466,2825124258799920,13535983528803121,310737983397275295,1488835123601160790,34178353049441482476,163758327612598883725,3759308097455165797011,18011927202262276048906,413489712367018796188680,1981148233921237766495881,45480109052274612414957735,217908293804133892038497950,5002398506037840346849162116,23967931170220806886468278565,550218355555110163540992874971 mul $0,3 add $0,1 mov $1,2 mov $2,3 lpb $0 sub $0,2 add $1,$2 add $2,$1 add $2,$1 add $2,$1 lpe mov $0,$2 div $0,6 add $0,1
; A127067: Define an array by d(m, 0) = 1, d(m, 1) = m; d(m, k) = (m - k + 1) d(m+1, k-1) - (k-1) (m+1) d(m+2, k-2). Sequence gives d(2,n). ; Submitted by Jon Maiga ; 1,2,0,-24,-60,720,5040,-40320,-589680,3628800,99792000,-479001600,-23740516800,87178291200,7682586912000,-20922789888000,-3281772285792000,6402373705728000,1801868049805824000,-2432902008176640000,-1241948957556827520000,1124000727777607680000,1052459837705700103680000,-620448401733239439360000,-1076711251064462709696000000,403291461126605635584000000,1308833601011027790386688000000,-304888344611713860501504000000,-1864597223028428269655129856000000,265252859812191058636308480000000 lpb $0 add $2,$3 add $3,1 mov $1,$3 mul $1,$0 sub $0,1 add $1,$3 add $2,$1 sub $4,1 mul $1,$4 mul $3,$4 add $3,$2 mov $2,$1 lpe mov $0,$3 add $0,1
; ------------------------------------------------------------------ ; MikeOS Text Editor ; ------------------------------------------------------------------ BITS 16 %INCLUDE "mikedev.inc" ORG 32768 start: call setup_screen cmp si, 0 ; Were we passed a filename? je .no_param_passed call os_string_tokenize ; If so, get it from params mov di, filename ; Save file for later usage call os_string_copy mov ax, si mov cx, 36864 call os_load_file ; Load the file 4K after the program start point jnc file_load_success mov ax, file_load_fail_msg ; If fail, show message and exit mov bx, 0 mov cx, 0 mov dx, 0 call os_dialog_box call os_clear_screen ret ; Back to the OS .no_param_passed: call os_file_selector ; Get filename to load jnc near file_chosen call os_clear_screen ; Quit if Esc pressed in file selector ret file_chosen: mov si, ax ; Save it for later usage mov di, filename call os_string_copy ; Now we need to make sure that the file extension is TXT or BAS... mov di, ax call os_string_length add di, ax dec di ; Make DI point to last char in filename dec di dec di mov si, txt_extension ; Check for .TXT extension mov cx, 3 rep cmpsb je valid_extension dec di mov si, bas_extension ; Check for .BAS extension mov cx, 3 rep cmpsb je valid_extension mov dx, 0 mov ax, wrong_ext_msg mov bx, 0 mov cx, 0 call os_dialog_box mov si, 0 jmp start valid_extension: mov ax, filename mov cx, 36864 ; Load the file 4K after the program start point call os_load_file file_load_success: mov word [filesize], bx ; Now BX contains the number of bytes in the file, so let's add ; the load offset to get the last byte of the file in RAM add bx, 36864 cmp bx, 36864 jne .not_empty mov byte [bx], 10 ; If the file is empty, insert a newline char to start with inc bx inc word [filesize] .not_empty: mov word [last_byte], bx ; Store position of final data byte mov cx, 0 ; Lines to skip when rendering (scroll marker) mov word [skiplines], 0 mov byte [cursor_x], 0 ; Initial cursor position will be start of text mov byte [cursor_y], 2 ; The file starts being displayed on line 2 of the screen ; Now we need to display the text on the screen; the following loop is called ; whenever the screen scrolls, but not just when the cursor is moved render_text: call setup_screen mov dh, 2 ; Move cursor to near top mov dl, 0 call os_move_cursor mov si, 36864 ; Point to start of text data mov ah, 0Eh ; BIOS char printing routine mov word cx, [skiplines] ; We're now going to skip lines depending on scroll level redraw: cmp cx, 0 ; Do we have any lines to skip? je display_loop ; If not, start the displaying dec cx ; Otherwise work through the lines .skip_loop: lodsb ; Read bytes until newline, to skip a line cmp al, 10 jne .skip_loop ; Move on to next line jmp redraw display_loop: ; Now we're ready to display the text lodsb ; Get character from file data cmp al, 10 ; Go to start of line if it's a carriage return character jne skip_return call os_get_cursor_pos mov dl, 0 ; Set DL = 0 (column = 0) call os_move_cursor skip_return: call os_get_cursor_pos ; Don't wrap lines on screen cmp dl, 79 je .no_print int 10h ; Print the character via the BIOS .no_print: mov word bx, [last_byte] cmp si, bx ; Have we printed all characters in the file? je near get_input call os_get_cursor_pos ; Are we at the bottom of the display area? cmp dh, 23 je get_input ; Wait for keypress if so jmp display_loop ; If not, keep rendering the characters ; When we get here, now we've displayed the text on the screen, and it's time ; to put the cursor at the position set by the user (not where it has been ; positioned after the text rendering), and get input get_input: ; call showbytepos ; USE FOR DEBUGGING (SHOWS CURSOR INFO AT TOP-RIGHT) mov byte dl, [cursor_x] ; Move cursor to user-set position mov byte dh, [cursor_y] call os_move_cursor call os_wait_for_key ; Get input cmp ah, KEY_UP ; Cursor key pressed? je near go_up cmp ah, KEY_DOWN je near go_down cmp ah, KEY_LEFT je near go_left cmp ah, KEY_RIGHT je near go_right cmp al, KEY_ESC ; Quit if Esc pressed je near close jmp text_entry ; Otherwise it was probably a text entry char ; ------------------------------------------------------------------ ; Move cursor left on the screen, and backward in data bytes go_left: cmp byte [cursor_x], 0 ; Are we at the start of a line? je .cant_move_left dec byte [cursor_x] ; If not, move cursor and data position dec word [cursor_byte] .cant_move_left: jmp get_input ; ------------------------------------------------------------------ ; Move cursor right on the screen, and forward in data bytes go_right: pusha cmp byte [cursor_x], 79 ; Far right of display? je .nothing_to_do ; Don't do anything if so mov word ax, [cursor_byte] mov si, 36864 add si, ax ; Now SI points to the char under the cursor inc si cmp word si, [last_byte] ; Can't move right if we're at the last byte of data je .nothing_to_do dec si cmp byte [si], 0Ah ; Can't move right if we are on a newline character je .nothing_to_do inc word [cursor_byte] ; Move data byte position and cursor location forwards inc byte [cursor_x] .nothing_to_do: popa jmp get_input ; ------------------------------------------------------------------ ; Move cursor down on the screen, and forward in data bytes go_down: ; First up, let's work out which character in the RAM file data ; the cursor will point to when we try to move down pusha mov word cx, [cursor_byte] mov si, 36864 add si, cx ; Now SI points to the char under the cursor .loop: inc si cmp word si, [last_byte] ; Is it pointing to the last byte in the data? je .do_nothing ; Quit out if so dec si lodsb ; Otherwise grab a character from the data inc cx ; Move our position along cmp al, 0Ah ; Look for newline char jne .loop ; Keep trying until we find a newline char mov word [cursor_byte], cx .nowhere_to_go: popa cmp byte [cursor_y], 22 ; If down pressed and cursor at bottom, scroll view down je .scroll_file_down inc byte [cursor_y] ; If down pressed elsewhere, just move the cursor mov byte [cursor_x], 0 ; And go to first column in next line jmp render_text .scroll_file_down: inc word [skiplines] ; Increment the lines we need to skip mov byte [cursor_x], 0 ; And go to first column in next line jmp render_text ; Redraw the whole lot .do_nothing: popa jmp render_text ; ------------------------------------------------------------------ ; Move cursor up on the screen, and backward in data bytes go_up: pusha mov word cx, [cursor_byte] mov si, 36864 add si, cx ; Now SI points to the char under the cursor cmp si, 36864 ; Do nothing if we're already at the start of the file je .start_of_file mov byte al, [si] ; Is the cursor already on a newline character? cmp al, 0Ah je .starting_on_newline jmp .full_monty ; If not, go back two newline chars .starting_on_newline: cmp si, 36865 je .start_of_file cmp byte [si-1], 0Ah ; Is the char before this one a newline char? je .another_newline_before dec si dec cx jmp .full_monty .another_newline_before: ; And the one before that a newline char? cmp byte [si-2], 0Ah jne .go_to_start_of_line ; If so, it means that the user pressed up on a newline char with another newline ; char above, so we just want to move back to that one, and do nothing else dec word [cursor_byte] jmp .display_move .go_to_start_of_line: dec si dec cx cmp si, 36864 je .start_of_file dec si dec cx cmp si, 36864 ; Do nothing if we're already at the start of the file je .start_of_file jmp .loop2 .full_monty: cmp si, 36864 je .start_of_file mov byte al, [si] cmp al, 0Ah ; Look for newline char je .found_newline dec cx dec si jmp .full_monty .found_newline: dec si dec cx .loop2: cmp si, 36864 je .start_of_file mov byte al, [si] cmp al, 0Ah ; Look for newline char je .found_done dec cx dec si jmp .loop2 .found_done: inc cx mov word [cursor_byte], cx jmp .display_move .start_of_file: mov word [cursor_byte], 0 mov byte [cursor_x], 0 .display_move: popa cmp byte [cursor_y], 2 ; If up pressed and cursor at top, scroll view up je .scroll_file_up dec byte [cursor_y] ; If up pressed elsewhere, just move the cursor mov byte [cursor_x], 0 ; And go to first column in previous line jmp get_input .scroll_file_up: cmp word [skiplines], 0 ; Don't scroll view up if we're at the top jle get_input dec word [skiplines] ; Otherwise decrement the lines we need to skip jmp render_text ; ------------------------------------------------------------------ ; When an key (other than cursor keys or Esc) is pressed... text_entry: pusha cmp ax, 3B00h ; F1 pressed? je near .f1_pressed cmp ax, 3C00h ; F2 pressed? je near save_file cmp ax, 3D00h ; F3 pressed? je near new_file cmp ax, 3F00h ; F5 pressed? je near .f5_pressed cmp ax, 4200h ; F8 pressed? je near .f8_pressed cmp ah, 53h ; Delete? je near .delete_pressed cmp al, 8 je near .backspace_pressed cmp al, KEY_ENTER je near .enter_pressed cmp al, 32 ; Only deal with displayable chars jl near .nothing_to_do cmp al, 126 je near .nothing_to_do call os_get_cursor_pos cmp dl, 78 jg near .nothing_to_do push ax call move_all_chars_forward mov word cx, [cursor_byte] mov si, 36864 add si, cx ; Now SI points to the char under the cursor pop ax mov byte [si], al inc word [cursor_byte] inc byte [cursor_x] .nothing_to_do: popa jmp render_text .delete_pressed: mov si, 36865 add si, word [cursor_byte] cmp si, word [last_byte] je .end_of_file cmp byte [si], 0Ah jl .at_final_char_in_line call move_all_chars_backward popa jmp render_text .at_final_char_in_line: call move_all_chars_backward ; Char and newline character too call move_all_chars_backward ; Char and newline character too popa jmp render_text .backspace_pressed: cmp word [cursor_byte], 0 je .do_nothing cmp byte [cursor_x], 0 je .do_nothing dec word [cursor_byte] dec byte [cursor_x] mov si, 36864 add si, word [cursor_byte] cmp si, word [last_byte] je .end_of_file cmp byte [si], 0Ah jl .at_final_char_in_line2 call move_all_chars_backward popa jmp render_text .at_final_char_in_line2: call move_all_chars_backward ; Char and newline character too call move_all_chars_backward ; Char and newline character too popa jmp render_text .do_nothing: popa jmp render_text .end_of_file: popa jmp render_text .enter_pressed: call move_all_chars_forward mov word cx, [cursor_byte] mov di, 36864 add di, cx ; Now SI points to the char under the cursor mov byte [di], 0Ah ; Add newline char popa jmp go_down .f1_pressed: ; Show some help info mov dx, 0 ; One-button dialog box mov ax, .msg_1 mov bx, .msg_2 mov cx, .msg_3 call os_dialog_box popa jmp render_text .msg_1 db 'Use Backspace to remove characters,', 0 .msg_2 db 'and Delete to remove newline chars.', 0 .msg_3 db 'Unix-formatted text files only!', 0 .f5_pressed: ; Cut line cmp byte [cursor_x], 0 je .done_going_left dec byte [cursor_x] dec word [cursor_byte] jmp .f5_pressed .done_going_left: mov si, 36864 add si, word [cursor_byte] inc si cmp si, word [last_byte] je .do_nothing_here dec si cmp byte [si], 10 je .final_char call move_all_chars_backward jmp .done_going_left .final_char: call move_all_chars_backward .do_nothing_here: popa jmp render_text .f8_pressed: ; Run BASIC mov word ax, [filesize] cmp ax, 4 jl .not_big_enough call os_clear_screen mov ax, 36864 mov si, 0 mov word bx, [filesize] call os_run_basic call os_print_newline mov si, .basic_finished_msg call os_print_string call os_wait_for_key call os_show_cursor popa jmp render_text .not_big_enough: mov ax, .fail1_msg mov bx, .fail2_msg mov cx, 0 mov dx, 0 call os_dialog_box popa jmp render_text .basic_finished_msg db ">>> BASIC finished - hit a key to return to the editor", 0 .fail1_msg db 'Not enough BASIC code to execute!', 0 .fail2_msg db 'You need at least an END command.', 0 ; ------------------------------------------------------------------ ; Move data from current cursor one character ahead move_all_chars_forward: pusha mov si, 36864 add si, word [filesize] ; SI = final byte in file mov di, 36864 add di, word [cursor_byte] .loop: mov byte al, [si] mov byte [si+1], al dec si cmp si, di jl .finished jmp .loop .finished: inc word [filesize] inc word [last_byte] popa ret ; ------------------------------------------------------------------ ; Move data from current cursor + 1 to end of file back one char move_all_chars_backward: pusha mov si, 36864 add si, word [cursor_byte] .loop: mov byte al, [si+1] mov byte [si], al inc si cmp word si, [last_byte] jne .loop .finished: dec word [filesize] dec word [last_byte] popa ret ; ------------------------------------------------------------------ ; SAVE FILE save_file: mov ax, filename ; Delete the file if it already exists call os_remove_file mov ax, filename mov word cx, [filesize] mov bx, 36864 call os_write_file jc .failure ; If we couldn't save file... mov ax, file_save_succeed_msg mov bx, 0 mov cx, 0 mov dx, 0 call os_dialog_box popa jmp render_text .failure: mov ax, file_save_fail_msg1 mov bx, file_save_fail_msg2 mov cx, 0 mov dx, 0 call os_dialog_box popa jmp render_text ; ------------------------------------------------------------------ ; NEW FILE new_file: mov ax, confirm_msg mov bx, 0 mov cx, 0 mov dx, 1 call os_dialog_box cmp ax, 1 je .do_nothing mov di, 36864 ; Clear the entire text buffer mov al, 0 mov cx, 28672 rep stosb mov word [filesize], 1 mov bx, 36864 ; Store just a single newline char mov byte [bx], 10 inc bx mov word [last_byte], bx mov cx, 0 ; Reset other values mov word [skiplines], 0 mov byte [cursor_x], 0 mov byte [cursor_y], 2 mov word [cursor_byte], 0 .retry_filename: mov ax, filename mov bx, new_file_msg call os_input_dialog mov ax, filename ; Delete the file if it already exists call os_remove_file mov ax, filename mov word cx, [filesize] mov bx, 36864 call os_write_file jc .failure ; If we couldn't save file... .do_nothing: popa jmp render_text .failure: mov ax, file_save_fail_msg1 mov bx, file_save_fail_msg2 mov cx, 0 mov dx, 0 call os_dialog_box jmp .retry_filename ; ------------------------------------------------------------------ ; Quit close: call os_clear_screen ret ; ------------------------------------------------------------------ ; Setup screen with colours, titles and horizontal lines setup_screen: pusha mov ax, txt_title_msg ; Set up the screen with info at top and bottom mov bx, txt_footer_msg mov cx, BLACK_ON_WHITE call os_draw_background mov dh, 1 ; Draw lines at top and bottom mov dl, 0 ; (Differentiate it from the text file viewer) call os_move_cursor mov ax, 0 ; Use single line character call os_print_horiz_line mov dh, 23 mov dl, 0 call os_move_cursor call os_print_horiz_line popa ret ; ------------------------------------------------------------------ ; DEBUGGING -- SHOW POSITION OF BYTE IN FILE AND CHAR UNDERNEATH CURSOR ; ENABLE THIS IN THE get_input SECTION ABOVE IF YOU NEED IT showbytepos: pusha mov word ax, [cursor_byte] call os_int_to_string mov si, ax mov dh, 0 mov dl, 60 call os_move_cursor call os_print_string call os_print_space mov si, 36864 add si, word [cursor_byte] lodsb call os_print_2hex call os_print_space mov ah, 0Eh int 10h call os_print_space popa ret ; ------------------------------------------------------------------ ; Data section txt_title_msg db 'MikeOS Text Editor', 0 txt_footer_msg db '[Esc] Quit [F1] Help [F2] Save [F3] New [F5] Delete line [F8] Run BASIC', 0 txt_extension db 'TXT', 0 bas_extension db 'BAS', 0 wrong_ext_msg db 'You can only load .TXT or .BAS files!', 0 confirm_msg db 'Are you sure? Unsaved data will be lost!', 0 file_load_fail_msg db 'Could not load file! Does it exist?', 0 new_file_msg db 'Enter a new filename:', 0 file_save_fail_msg1 db 'Could not save file!', 0 file_save_fail_msg2 db '(Write-only media or bad filename?)', 0 file_save_succeed_msg db 'File saved.', 0 skiplines dw 0 cursor_x db 0 ; User-set cursor position cursor_y db 0 cursor_byte dw 0 ; Byte in file data where cursor is last_byte dw 0 ; Location in RAM of final byte in file filename times 32 db 0 ; 12 would do, but the user ; might enter something daft filesize dw 0 ; ------------------------------------------------------------------
; A293476: a(n) = ((n + 1)/2)*(n + 2)*Pochhammer(n, 5) / 4!. ; Submitted by Jamie Morken(s1.) ; 0,15,180,1050,4200,13230,35280,83160,178200,353925,660660,1171170,1987440,3248700,5140800,7907040,11860560,17398395,25017300,35331450,49092120,67209450,90776400,121095000,159705000,208415025,269336340,344919330,437992800,551806200,690074880,857028480,1057462560,1296793575,1581117300,1917270810,2312898120,2776519590,3317605200,3946651800,4675264440,5516241885,6483666420,7592998050,8861173200,10306708020,11949806400,13812472800,15918630000,18294241875,20967441300,23968663290,27330783480 mov $1,3 mov $2,$0 add $2,4 sub $1,$2 bin $1,2 mul $1,$0 bin $2,$0 mul $1,$2 mov $0,$1
/* Copyright 2015-2018 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "DiligentCore/Graphics/GraphicsEngine/interface/Buffer.h"
; A285270: a(n) = H_n(n), where H_n is the physicist's n-th Hermite polynomial. ; Submitted by Christian Krause ; 1,2,14,180,3340,80600,2389704,83965616,3409634960,157077960480,8093278209760,461113571640128,28784033772836544,1953535902100115840,143219579014652040320,11279408109860685024000,949705205977314865582336,85131076752851318807814656,8094279370190580822082014720 lpb $0 sub $0,1 add $3,1 mov $1,$3 mul $1,2 mul $1,$0 sub $2,$3 add $2,$1 mul $3,2 add $4,1 mul $3,$4 add $3,$2 lpe mov $0,$3 add $0,1
;; ;; Copyright (c) 2012-2022, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation nor the names of its contributors ;; may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; %include "include/os.asm" %include "include/imb_job.asm" %include "include/mb_mgr_datastruct.asm" %include "include/reg_sizes.asm" %include "include/memcpy.asm" %include "include/const.inc" extern sha_256_mult_sse mksection .rodata default rel align 16 byteswap: ;ddq 0x0c0d0e0f08090a0b0405060700010203 dq 0x0405060700010203, 0x0c0d0e0f08090a0b mksection .text %ifndef FUNC %define FUNC submit_job_hmac_sha_256_sse %endif %if 1 %ifdef LINUX %define arg1 rdi %define arg2 rsi %define reg3 rcx %define reg4 rdx %else %define arg1 rcx %define arg2 rdx %define reg3 rdi %define reg4 rsi %endif %define state arg1 %define job arg2 %define len2 arg2 ; idx needs to be in rbx, rbp, r13-r15 %define last_len rbp %define idx rbp %define p r11 %define start_offset r11 %define unused_lanes rbx %define tmp4 rbx %define job_rax rax %define len rax %define size_offset reg3 %define tmp2 reg3 %define lane reg4 %define tmp3 reg4 %define extra_blocks r8 %define tmp r9 %define p2 r9 %define lane_data r10 %endif ; This routine clobbers rbx, rbp, rsi, rdi; called routine also clobbers r12 struc STACK _gpr_save: resq 5 _rsp_save: resq 1 endstruc ; JOB* FUNC(MB_MGR_HMAC_SHA_256_OOO *state, IMB_JOB *job) ; arg 1 : rcx : state ; arg 2 : rdx : job MKGLOBAL(FUNC,function,internal) FUNC: mov rax, rsp sub rsp, STACK_size and rsp, -16 mov [rsp + _gpr_save + 8*0], rbx mov [rsp + _gpr_save + 8*1], rbp mov [rsp + _gpr_save + 8*2], r12 %ifndef LINUX mov [rsp + _gpr_save + 8*3], rsi mov [rsp + _gpr_save + 8*4], rdi %endif mov [rsp + _rsp_save], rax ; original SP mov unused_lanes, [state + _unused_lanes_sha256] movzx lane, BYTE(unused_lanes) shr unused_lanes, 8 imul lane_data, lane, _HMAC_SHA1_LANE_DATA_size lea lane_data, [state + _ldata_sha256 + lane_data] mov [state + _unused_lanes_sha256], unused_lanes mov len, [job + _msg_len_to_hash_in_bytes] mov tmp, len shr tmp, 6 ; divide by 64, len in terms of blocks mov [lane_data + _job_in_lane], job mov dword [lane_data + _outer_done], 0 movdqa xmm0, [state + _lens_sha256] XPINSRW xmm0, xmm1, p, lane, tmp, scale_x16 movdqa [state + _lens_sha256], xmm0 mov last_len, len and last_len, 63 lea extra_blocks, [last_len + 9 + 63] shr extra_blocks, 6 mov [lane_data + _extra_blocks], DWORD(extra_blocks) mov p, [job + _src] add p, [job + _hash_start_src_offset_in_bytes] mov [state + _args_data_ptr_sha256 + 8*lane], p cmp len, 64 jb copy_lt64 fast_copy: add p, len movdqu xmm0, [p - 64 + 0*16] movdqu xmm1, [p - 64 + 1*16] movdqu xmm2, [p - 64 + 2*16] movdqu xmm3, [p - 64 + 3*16] movdqa [lane_data + _extra_block + 0*16], xmm0 movdqa [lane_data + _extra_block + 1*16], xmm1 movdqa [lane_data + _extra_block + 2*16], xmm2 movdqa [lane_data + _extra_block + 3*16], xmm3 end_fast_copy: mov size_offset, extra_blocks shl size_offset, 6 sub size_offset, last_len add size_offset, 64-8 mov [lane_data + _size_offset], DWORD(size_offset) mov start_offset, 64 sub start_offset, last_len mov [lane_data + _start_offset], DWORD(start_offset) lea tmp, [8*64 + 8*len] bswap tmp mov [lane_data + _extra_block + size_offset], tmp mov tmp, [job + _auth_key_xor_ipad] movdqu xmm0, [tmp] movdqu xmm1, [tmp + 4*4] movd [state + _args_digest_sha256 + 4*lane + 0*SHA256_DIGEST_ROW_SIZE], xmm0 pextrd [state + _args_digest_sha256 + 4*lane + 1*SHA256_DIGEST_ROW_SIZE], xmm0, 1 pextrd [state + _args_digest_sha256 + 4*lane + 2*SHA256_DIGEST_ROW_SIZE], xmm0, 2 pextrd [state + _args_digest_sha256 + 4*lane + 3*SHA256_DIGEST_ROW_SIZE], xmm0, 3 movd [state + _args_digest_sha256 + 4*lane + 4*SHA256_DIGEST_ROW_SIZE], xmm1 pextrd [state + _args_digest_sha256 + 4*lane + 5*SHA256_DIGEST_ROW_SIZE], xmm1, 1 pextrd [state + _args_digest_sha256 + 4*lane + 6*SHA256_DIGEST_ROW_SIZE], xmm1, 2 pextrd [state + _args_digest_sha256 + 4*lane + 7*SHA256_DIGEST_ROW_SIZE], xmm1, 3 test len, ~63 jnz ge64_bytes lt64_bytes: movdqa xmm0, [state + _lens_sha256] XPINSRW xmm0, xmm1, tmp, lane, extra_blocks, scale_x16 movdqa [state + _lens_sha256], xmm0 lea tmp, [lane_data + _extra_block + start_offset] mov [state + _args_data_ptr_sha256 + 8*lane], tmp mov dword [lane_data + _extra_blocks], 0 ge64_bytes: cmp unused_lanes, 0xff jne return_null jmp start_loop align 16 start_loop: ; Find min length movdqa xmm0, [state + _lens_sha256] phminposuw xmm1, xmm0 pextrw len2, xmm1, 0 ; min value pextrw idx, xmm1, 1 ; min index (0...3) cmp len2, 0 je len_is_0 pshuflw xmm1, xmm1, 0 psubw xmm0, xmm1 movdqa [state + _lens_sha256], xmm0 ; "state" and "args" are the same address, arg1 ; len is arg2 call sha_256_mult_sse ; state and idx are intact len_is_0: ; process completed job "idx" imul lane_data, idx, _HMAC_SHA1_LANE_DATA_size lea lane_data, [state + _ldata_sha256 + lane_data] mov DWORD(extra_blocks), [lane_data + _extra_blocks] cmp extra_blocks, 0 jne proc_extra_blocks cmp dword [lane_data + _outer_done], 0 jne end_loop proc_outer: mov dword [lane_data + _outer_done], 1 mov DWORD(size_offset), [lane_data + _size_offset] mov qword [lane_data + _extra_block + size_offset], 0 movdqa xmm0, [state + _lens_sha256] XPINSRW xmm0, xmm1, tmp, idx, 1, scale_x16 movdqa [state + _lens_sha256], xmm0 lea tmp, [lane_data + _outer_block] mov job, [lane_data + _job_in_lane] mov [state + _args_data_ptr_sha256 + 8*idx], tmp movd xmm0, [state + _args_digest_sha256 + 4*idx + 0*SHA256_DIGEST_ROW_SIZE] pinsrd xmm0, [state + _args_digest_sha256 + 4*idx + 1*SHA256_DIGEST_ROW_SIZE], 1 pinsrd xmm0, [state + _args_digest_sha256 + 4*idx + 2*SHA256_DIGEST_ROW_SIZE], 2 pinsrd xmm0, [state + _args_digest_sha256 + 4*idx + 3*SHA256_DIGEST_ROW_SIZE], 3 pshufb xmm0, [rel byteswap] movd xmm1, [state + _args_digest_sha256 + 4*idx + 4*SHA256_DIGEST_ROW_SIZE] pinsrd xmm1, [state + _args_digest_sha256 + 4*idx + 5*SHA256_DIGEST_ROW_SIZE], 1 pinsrd xmm1, [state + _args_digest_sha256 + 4*idx + 6*SHA256_DIGEST_ROW_SIZE], 2 %ifndef SHA224 pinsrd xmm1, [state + _args_digest_sha256 + 4*idx + 7*SHA256_DIGEST_ROW_SIZE], 3 %endif pshufb xmm1, [rel byteswap] movdqa [lane_data + _outer_block], xmm0 movdqa [lane_data + _outer_block + 4*4], xmm1 %ifdef SHA224 mov dword [lane_data + _outer_block + 7*4], 0x80 %endif mov tmp, [job + _auth_key_xor_opad] movdqu xmm0, [tmp] movdqu xmm1, [tmp + 4*4] movd [state + _args_digest_sha256 + 4*idx + 0*SHA256_DIGEST_ROW_SIZE], xmm0 pextrd [state + _args_digest_sha256 + 4*idx + 1*SHA256_DIGEST_ROW_SIZE], xmm0, 1 pextrd [state + _args_digest_sha256 + 4*idx + 2*SHA256_DIGEST_ROW_SIZE], xmm0, 2 pextrd [state + _args_digest_sha256 + 4*idx + 3*SHA256_DIGEST_ROW_SIZE], xmm0, 3 movd [state + _args_digest_sha256 + 4*idx + 4*SHA256_DIGEST_ROW_SIZE], xmm1 pextrd [state + _args_digest_sha256 + 4*idx + 5*SHA256_DIGEST_ROW_SIZE], xmm1, 1 pextrd [state + _args_digest_sha256 + 4*idx + 6*SHA256_DIGEST_ROW_SIZE], xmm1, 2 pextrd [state + _args_digest_sha256 + 4*idx + 7*SHA256_DIGEST_ROW_SIZE], xmm1, 3 jmp start_loop align 16 proc_extra_blocks: mov DWORD(start_offset), [lane_data + _start_offset] movdqa xmm0, [state + _lens_sha256] XPINSRW xmm0, xmm1, tmp, idx, extra_blocks, scale_x16 movdqa [state + _lens_sha256], xmm0 lea tmp, [lane_data + _extra_block + start_offset] mov [state + _args_data_ptr_sha256 + 8*idx], tmp mov dword [lane_data + _extra_blocks], 0 jmp start_loop align 16 copy_lt64: ;; less than one message block of data ;; beginning of source block ;; destination extrablock but backwards by len from where 0x80 pre-populated ;; p2 clobbers unused_lanes, undo before exit lea p2, [lane_data + _extra_block + 64] sub p2, len memcpy_sse_64_1 p2, p, len, tmp4, tmp2, xmm0, xmm1, xmm2, xmm3 mov unused_lanes, [state + _unused_lanes_sha256] jmp end_fast_copy return_null: xor job_rax, job_rax jmp return align 16 end_loop: mov job_rax, [lane_data + _job_in_lane] mov unused_lanes, [state + _unused_lanes_sha256] mov qword [lane_data + _job_in_lane], 0 or dword [job_rax + _status], IMB_STATUS_COMPLETED_AUTH shl unused_lanes, 8 or unused_lanes, idx mov [state + _unused_lanes_sha256], unused_lanes mov p, [job_rax + _auth_tag_output] %ifdef SHA224 cmp qword [job_rax + _auth_tag_output_len_in_bytes], 14 jne copy_full_digest %else cmp qword [job_rax + _auth_tag_output_len_in_bytes], 16 jne copy_full_digest %endif ;; copy 14 bytes for SHA224 / 16 bytes for SHA256 mov DWORD(tmp), [state + _args_digest_sha256 + 4*idx + 0*SHA256_DIGEST_ROW_SIZE] mov DWORD(tmp2), [state + _args_digest_sha256 + 4*idx + 1*SHA256_DIGEST_ROW_SIZE] mov DWORD(tmp3), [state + _args_digest_sha256 + 4*idx + 2*SHA256_DIGEST_ROW_SIZE] mov DWORD(tmp4), [state + _args_digest_sha256 + 4*idx + 3*SHA256_DIGEST_ROW_SIZE] bswap DWORD(tmp) bswap DWORD(tmp2) bswap DWORD(tmp3) bswap DWORD(tmp4) mov [p + 0*4], DWORD(tmp) mov [p + 1*4], DWORD(tmp2) mov [p + 2*4], DWORD(tmp3) %ifdef SHA224 mov [p + 3*4], WORD(tmp4) %else mov [p + 3*4], DWORD(tmp4) %endif jmp clear_ret copy_full_digest: ;; copy 28 bytes for SHA224 / 32 bytes for SHA256 mov DWORD(tmp), [state + _args_digest_sha256 + 4*idx + 0*SHA256_DIGEST_ROW_SIZE] mov DWORD(tmp2), [state + _args_digest_sha256 + 4*idx + 1*SHA256_DIGEST_ROW_SIZE] mov DWORD(tmp3), [state + _args_digest_sha256 + 4*idx + 2*SHA256_DIGEST_ROW_SIZE] mov DWORD(tmp4), [state + _args_digest_sha256 + 4*idx + 3*SHA256_DIGEST_ROW_SIZE] bswap DWORD(tmp) bswap DWORD(tmp2) bswap DWORD(tmp3) bswap DWORD(tmp4) mov [p + 0*4], DWORD(tmp) mov [p + 1*4], DWORD(tmp2) mov [p + 2*4], DWORD(tmp3) mov [p + 3*4], DWORD(tmp4) mov DWORD(tmp), [state + _args_digest_sha256 + 4*idx + 4*SHA256_DIGEST_ROW_SIZE] mov DWORD(tmp2), [state + _args_digest_sha256 + 4*idx + 5*SHA256_DIGEST_ROW_SIZE] mov DWORD(tmp3), [state + _args_digest_sha256 + 4*idx + 6*SHA256_DIGEST_ROW_SIZE] %ifndef SHA224 mov DWORD(tmp4), [state + _args_digest_sha256 + 4*idx + 7*SHA256_DIGEST_ROW_SIZE] %endif bswap DWORD(tmp) bswap DWORD(tmp2) bswap DWORD(tmp3) %ifndef SHA224 bswap DWORD(tmp4) %endif mov [p + 4*4], DWORD(tmp) mov [p + 5*4], DWORD(tmp2) mov [p + 6*4], DWORD(tmp3) %ifndef SHA224 mov [p + 7*4], DWORD(tmp4) %endif clear_ret: %ifdef SAFE_DATA ;; Clear digest (28B/32B), outer_block (28B/32B) and extra_block (64B) of returned job %assign J 0 %rep 7 mov dword [state + _args_digest_sha256 + SHA256_DIGEST_WORD_SIZE*idx + J*SHA256_DIGEST_ROW_SIZE], 0 %assign J (J+1) %endrep %ifndef SHA224 mov dword [state + _args_digest_sha256 + SHA256_DIGEST_WORD_SIZE*idx + 7*SHA256_DIGEST_ROW_SIZE], 0 %endif pxor xmm0, xmm0 imul lane_data, idx, _HMAC_SHA1_LANE_DATA_size lea lane_data, [state + _ldata_sha256 + lane_data] ;; Clear first 64 bytes of extra_block %assign offset 0 %rep 4 movdqa [lane_data + _extra_block + offset], xmm0 %assign offset (offset + 16) %endrep ;; Clear first 28 bytes (SHA-224) or 32 bytes (SHA-256) of outer_block movdqa [lane_data + _outer_block], xmm0 %ifdef SHA224 mov qword [lane_data + _outer_block + 16], 0 mov dword [lane_data + _outer_block + 24], 0 %else movdqa [lane_data + _outer_block + 16], xmm0 %endif %endif ;; SAFE_DATA return: mov rbx, [rsp + _gpr_save + 8*0] mov rbp, [rsp + _gpr_save + 8*1] mov r12, [rsp + _gpr_save + 8*2] %ifndef LINUX mov rsi, [rsp + _gpr_save + 8*3] mov rdi, [rsp + _gpr_save + 8*4] %endif mov rsp, [rsp + _rsp_save] ; original SP ret mksection stack-noexec
{ let r := 0 for { let i := 0 } lt(i, 1048576) { i := add(i, 1) } { 0xfdedc7f10142ff97 0xfbdfda0e2ce356173d1993d5f70a2b11 0xfdedc7f10142ff97 dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div pop dup2 dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div pop dup2 dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div pop dup2 dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div pop dup2 dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div pop dup2 dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div pop dup2 dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div pop dup2 dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div dup2 div =: r pop pop } switch r case 0xfdedc7f10142ff97 { stop } default { 0 0 revert } }
; int bv_priority_queue_push(bv_priority_queue_t *q, int c) SECTION code_clib SECTION code_adt_bv_priority_queue PUBLIC bv_priority_queue_push EXTERN asm_bv_priority_queue_push bv_priority_queue_push: pop hl pop bc ex (sp),hl jp asm_bv_priority_queue_push
#abs.asb .text main : li $v0, 5 syscall move $a0, $v0 bgtz $a0, affichage neg $a0, $a0 j affichage affichage:li $v0, 1 syscall li $v0, 10 syscall
org 0h org 03h setb p1.5 reti org 13h clr p1.5 reti inicio: mov tcon,#0ah mov ie,#85h main: sjmp main
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013,2014 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #if defined(STM32PLUS_F4_HAS_MAC) || defined(STM32PLUS_F1_CL_E) #include "config/net.h" namespace stm32plus { namespace net { /** * Constructor when creating a connection from an incoming connection to a TcpServer. This is IRQ code. * @param networkUtilityObjects utility objects * @param tcpEvents TCP events * @param segmentEvent The event that triggered the server * @param segmentSizeLimit The MSS limit for this server * @param additionalHeaderSize Number of bytes required for lower layer headers */ bool TcpConnection::initialise(NetworkUtilityObjects& networkUtilityObjects, TcpEvents& tcpEvents, TcpSegmentEvent& segmentEvent, uint16_t segmentSizeLimit, uint16_t additionalHeaderSize) { const TcpOptionMaximumSegmentSize *mss; // remember parameters _networkUtilityObjects=&networkUtilityObjects; _tcpEvents=&tcpEvents; _segmentSizeLimit=segmentSizeLimit; _additionalHeaderSize=additionalHeaderSize; _lastZeroWindowPollTime=0; // create the receive buffer _receiveBuffer=new TcpReceiveBuffer(_params.tcp_receiveBufferSize); // set up the class initialise(segmentEvent.ipPacket.header->ip_sourceAddress, segmentEvent.sourcePort, segmentEvent.destinationPort); // pull out the state variables from the remote side _state.rxWindow.receiveNext=NetUtil::ntohl(segmentEvent.tcpHeader.tcp_sequenceNumber); _state.txWindow.sendWindow=NetUtil::ntohs(segmentEvent.tcpHeader.tcp_windowSize); // find the MSS option if((mss=segmentEvent.tcpHeader.findOption<TcpOptionMaximumSegmentSize>())==nullptr) _remoteMss=536; // default from the RFC else _remoteMss=NetUtil::ntohs(mss->tcp_optionMss); // this is an incoming client connection to our server. we need to send a SYN-ACK _state.localPortIsEphemeral=false; _state.changeState(*_networkUtilityObjects,TcpState::SYN_RCVD); return sendSynAck(); } /** * Constructor when creating a client for an outgoing connection to a server. * @param networkUtilityObjects utility objects * @param tcpEvents TCP events * @param segmentSizeLimit The MSS limit for this server * @param additionalHeaderSize Number of bytes required for lower layer headers */ bool TcpConnection::initialise(NetworkUtilityObjects& networkUtilityObjects, TcpEvents& tcpEvents, const IpAddress& remoteAddress, uint16_t localPort, uint16_t remotePort, uint16_t segmentSizeLimit, uint16_t additionalHeaderSize) { // remember parameters _networkUtilityObjects=&networkUtilityObjects; _tcpEvents=&tcpEvents; _segmentSizeLimit=segmentSizeLimit; _additionalHeaderSize=additionalHeaderSize; _lastZeroWindowPollTime=0; // create the receive buffer _receiveBuffer=new TcpReceiveBuffer(_params.tcp_receiveBufferSize); // set up the class initialise(remoteAddress,remotePort,localPort); // no state variables from the remote side yet _state.rxWindow.receiveNext=0; _state.txWindow.sendWindow=0; // this is an incoming client connection to our server. we need to send a SYN-ACK _state.localPortIsEphemeral=true; _state.changeState(*_networkUtilityObjects,TcpState::SYN_SENT); return sendSyn(); } /** * Destructor */ TcpConnection::~TcpConnection() { // unsubscribe from notification events _networkUtilityObjects->NetworkNotificationEventSender.removeSubscriber(NetworkNotificationEventSourceSlot::bind(this,&TcpConnection::onNotification)); // unsubscribe from receive events _tcpEvents->TcpReceiveEventSender.removeSubscriber(TcpReceiveEventSourceSlot::bind(this,&TcpConnection::onReceive)); // notify that we've been released. depending on our state, the connection may be moved into the // closing handler _networkUtilityObjects->NetworkNotificationEventSender.raiseEvent(TcpConnectionReleasedEvent(*this)); // delete the receive buffer delete _receiveBuffer; } /** * Initialise the class members and subscriptions * @param remoteAddress IP address of the remote end * @param remotePort The remote port * @param localPort The local port */ void TcpConnection::initialise(const IpAddress& remoteAddress,uint16_t remotePort,uint16_t localPort) { _state.changeState(*_networkUtilityObjects,TcpState::CLOSED); _state.additionalHeaderSize=_additionalHeaderSize; _state.localPort=localPort; _state.remotePort=remotePort; _state.remoteAddress=remoteAddress; // the receive window is not currently closed _receiveWindowIsClosed=false; // set the last active time to now _lastActiveTime=MillisecondTimer::millis(); // generate a random initial sequence number. Yes this is wrong according to the host requirements RFC but we're // not in a position to maintain a continuously incrementing 4us timer. OK to cast off the volatile here. _networkUtilityObjects->nextRandom(const_cast<uint32_t&>(_state.txWindow.sendNext)); _state.txWindow.sendNext&=0x7FFFFFFF; _state.txWindow.sendUnacknowledged=_state.txWindow.sendNext; _state.rxWindow.receiveWindow=_receiveBuffer->availableToWrite(); // subscribe to notification events _networkUtilityObjects->NetworkNotificationEventSender.insertSubscriber(NetworkNotificationEventSourceSlot::bind(this,&TcpConnection::onNotification)); // subscribe to segment receive events _tcpEvents->TcpReceiveEventSender.insertSubscriber(TcpReceiveEventSourceSlot::bind(this,&TcpConnection::onReceive)); } /** * Callback from our subscription to notification events * @param ned The event descriptor */ void TcpConnection::onNotification(NetEventDescriptor& ned) { if(ned.eventType==NetEventDescriptor::NetEventType::TCP_FIND_CONNECTION) handleFindConnectionEvent(static_cast<TcpFindConnectionNotificationEvent&>(ned)); } /** * Segment received event. This is IRQ code. * @param event The event */ void TcpConnection::onReceive(TcpSegmentEvent& event) { // must be for this connection if(event.ipPacket.header->ip_sourceAddress!=_state.remoteAddress || _state.localPort!=event.destinationPort || _state.remotePort!=event.sourcePort) return; // it's for us, so it's considered handled even if we drop it event.handled=true; // see what we've been sent if(event.tcpHeader.hasRst()) handleIncomingRst(); else { // check for SYN-ACK if(event.tcpHeader.hasSyn() && event.tcpHeader.hasAck()) handleIncomingSynAck(event.tcpHeader); else { if(event.tcpHeader.hasAck()) handleIncomingAck(event.tcpHeader,event.payloadLength!=0); if(event.payloadLength>0) handleIncomingData(event); if(event.tcpHeader.hasFin()) handleIncomingFin(event); } // store the latest sender window size - it can change on any incoming segment _state.txWindow.sendWindow=NetUtil::ntohs(event.tcpHeader.tcp_windowSize); } } /** * Handle a FIN (remote close) coming from the other side. * Change the state to CLOSE_WAIT and send a notification. * * This is IRQ code */ void TcpConnection::handleIncomingFin(TcpSegmentEvent& event) { uint32_t rxnext; // the sequence number must be in order. if the segments have got out of order on // the network then there could be data to come before this FIN rxnext=NetUtil::ntohl(event.tcpHeader.tcp_sequenceNumber); if(rxnext!=_state.rxWindow.receiveNext) return; // change our state _state.changeState(*_networkUtilityObjects,TcpState::CLOSE_WAIT); // ACK the FIN so the connection is now half-closed _state.rxWindow.receiveNext++; _state.sendAck(*_networkUtilityObjects,sillyWindowAvoidance()); // notify TcpConnectionClosedEventSender.raiseEvent(TcpConnectionClosedEvent(*this)); } /** * Handle some incoming data from the remote end. This is IRQ code. * @param event The segment event */ void TcpConnection::handleIncomingData(const TcpSegmentEvent& event) { uint32_t rxnext; // we've become active _lastActiveTime=MillisecondTimer::millis(); // we can only handle sequential data. if the sequence number on the incoming packet is // not what we expect then we drop the segment because an earlier segment has either got // lost or been overtaken on the network. the sender will have to resend. rxnext=NetUtil::ntohl(event.tcpHeader.tcp_sequenceNumber); if(rxnext==_state.rxWindow.receiveNext) { // the data size cannot be greater than the write space available in the buffer. If it // is then the sender is most likely probing a zero window that we have advertised. if(event.payloadLength<=_receiveBuffer->availableToWrite()) { // write the data into the buffer _receiveBuffer->write(event.payload,event.payloadLength); // update our variables _state.rxWindow.receiveNext+=event.payloadLength; _state.rxWindow.receiveWindow=_receiveBuffer->availableToWrite(); } } // ack the current state _state.sendAck(*_networkUtilityObjects,sillyWindowAvoidance()); // notify if there is some data to read if(_receiveBuffer->availableToRead()>0) TcpConnectionDataReadyEventSender.raiseEvent(TcpConnectionDataReadyEvent(*this)); } /** * Handle an incoming ACK. We can handle any ACK that moves sendUnacknowledged forward. We are trusting * the remote not to ACK data that it hasn't received. * This is IRQ code. * @param header The TCP header * @param true if this segment contains data */ void TcpConnection::handleIncomingAck(const TcpHeader& header,bool hasData) { uint32_t newSuna; // if the current state is SYN_RCVD then we can move to established if(_state.state==TcpState::SYN_RCVD) _state.changeState(*_networkUtilityObjects,TcpState::ESTABLISHED); // the gotcha here is to cater for 32-bit overflow while checking that the new s.una // is greater than the old which is necessary to avoid winding back the window by // accident when segments arrive out of order. We arbitrarily decide that a distance // of 2^31 between the pointers is sufficient to indicate a wrap. newSuna=NetUtil::ntohl(header.tcp_ackNumber); if((newSuna>_state.txWindow.sendUnacknowledged || _state.txWindow.sendUnacknowledged-newSuna>0x80000000)) _state.txWindow.sendUnacknowledged=newSuna; else { // if the ACK has no data and did not move the window then re-ack our current state // possibly opening our window if(!hasData) _state.sendAck(*_networkUtilityObjects,sillyWindowAvoidance()); } } /** * Handle an incoming SYN-ACK. * This is IRQ code. * @param header The TCP header */ void TcpConnection::handleIncomingSynAck(const TcpHeader& header) { const TcpOptionMaximumSegmentSize *mss; // the only legal state is SYN_SENT if(_state.state!=TcpState::SYN_SENT) return; // that SYN cost us a sequence number _state.txWindow.sendNext++; // pull out the state variables from the remote side _state.rxWindow.receiveNext=NetUtil::ntohl(header.tcp_sequenceNumber)+1; _state.txWindow.sendWindow=NetUtil::ntohs(header.tcp_windowSize); // find the MSS option if((mss=header.findOption<TcpOptionMaximumSegmentSize>())==nullptr) _remoteMss=536; // default from the RFC else _remoteMss=NetUtil::ntohs(mss->tcp_optionMss); // we're established, as far as we know _state.changeState(*_networkUtilityObjects,TcpState::ESTABLISHED); // ACK their SYN-ACK _state.sendAck(*_networkUtilityObjects,sillyWindowAvoidance()); } /** * Send a SYN segment to the server. This segment has no data. It contains the SYN flag plus our receive buffer * size and the MSS option. * @return true if it was sent */ bool TcpConnection::sendSyn() { // create a NetBuffer to hold the SYN segment NetBuffer *nb=new NetBuffer(_additionalHeaderSize+TcpHeader::getNoOptionsHeaderSize(),4); // set up MSS (maximum segment size) option TcpOptionMaximumSegmentSize *mssOption=reinterpret_cast<TcpOptionMaximumSegmentSize *>(nb->moveWritePointerBack(4)); mssOption->initialise(_segmentSizeLimit); // construct the header TcpHeader *header=reinterpret_cast<TcpHeader *>(nb->moveWritePointerBack(TcpHeader::getNoOptionsHeaderSize())); // we're acking the SYN, which costs the sender 1 sequence number header->initialise(_state.localPort, // ports _state.remotePort, _state.txWindow.sendNext, // initial sequence number 0, // nothing to ACK getReceiveBufferSpaceAvailable(), // data space available TcpHeaderFlags::SYN); // this header is larger than the minimum header->setSize(TcpHeader::getNoOptionsHeaderSize()+TcpOptionMaximumSegmentSize::getSize()); // ask the IP layer to send the packet IpTransmitRequestEvent iptre( nb, _state.remoteAddress, IpProtocol::TCP); _networkUtilityObjects->NetworkSendEventSender.raiseEvent(iptre); return iptre.succeeded; } /** * Send a SYN-ACK segment back to our client. This segment has no data. It contains the SYN * and ACK flags plus our receive buffer size and the MSS option. * @return true if it worked */ bool TcpConnection::sendSynAck() { // create a NetBuffer to hold the SYN-ACK segment. we're dealing with an incoming // SYN segment from an IRQ NetBuffer *nb=new NetBuffer(_additionalHeaderSize+TcpHeader::getNoOptionsHeaderSize(),4); // set up MSS (maximum segment size) option TcpOptionMaximumSegmentSize *mssOption=reinterpret_cast<TcpOptionMaximumSegmentSize *>(nb->moveWritePointerBack(4)); mssOption->initialise(_segmentSizeLimit); // construct the header TcpHeader *header=reinterpret_cast<TcpHeader *>(nb->moveWritePointerBack(TcpHeader::getNoOptionsHeaderSize())); // we're acking the SYN, which costs the sender 1 sequence number _state.rxWindow.receiveNext++; header->initialise(_state.localPort, // ports _state.remotePort, _state.txWindow.sendNext, // initial sequence number _state.rxWindow.receiveNext, // ack the SYN (the SYN consumes a sequence number) getReceiveBufferSpaceAvailable(), // data space available TcpHeaderFlags::SYN | TcpHeaderFlags::ACK); // this header is larger than the minimum header->setSize(TcpHeader::getNoOptionsHeaderSize()+TcpOptionMaximumSegmentSize::getSize()); // increment our sequence number _state.txWindow.sendNext++; // ask the IP layer to send the packet IpTransmitRequestEvent iptre( nb, _state.remoteAddress, IpProtocol::TCP); _networkUtilityObjects->NetworkSendEventSender.raiseEvent(iptre); return iptre.succeeded; } /** * Send a batch of data to the remote client with an optional timeout. If the timeout is zero * then this is effectively a blocking call that will not return until success or a network * error occurs. * * Data is sent in segments to the other side. The size of each segment is bounded by the lower * of our MTU and the last known receive window of the recipient. actuallySent is updated to * hold the amount of data acknowledged by the other end when this function returns. * * If tcp_nagleAvoidance is true (the default) then this method tries to send at least two * packets per call to force the remote to ACK immediately. If only one packet were to go out * per call then we may have to wait up to 200ms for the remote end's Nagle algorithm timer * to expire and send us our ACK. * * The timeout, if non zero, is applied in full to each segment that we send. It means * that we will wait for that many milliseconds after we send a segment to receiving an ACK * before we give up. There will be an interplay between this timeout and the tcp_sendRetry* * configuration parameters. * * @param data The buffer of data to transmit * @param datasize How many bytes of data to transmit * @param[out] actuallySent How many bytes we sent and have been acknowledged, updated on success or failure. * @param[in] timeoutMillis How long to wait for any blocking state to release, or zero (the default) to wait forever. * @return true if all the data was sent, false if there was an error. Even if there is an error it is still possible for data to have been sent. Always check actuallySent to see how much data was sent. */ bool TcpConnection::send(const void *data,uint32_t datasize,uint32_t& actuallySent,uint32_t timeoutMillis) { uint32_t bufpos,expectsuna,batchpos,batchbufpos,now,resendtimeout,startwait; uint16_t batchwin,batchsendcap; TcpHeaderFlags headerFlags; actuallySent=0; now=MillisecondTimer::millis(); // we've become active _lastActiveTime=now; // if the state is SYNC_RCVD then we wait for it to move on if(_state.state==TcpState::SYN_RCVD) if(!waitForStateChange(TcpState::SYN_RCVD,timeoutMillis)) return false; // the new state must be ESTABLISHED if(_state.state!=TcpState::ESTABLISHED) return _networkUtilityObjects->setError(ErrorProvider::ERROR_PROVIDER_NET_TCP_CONNECTION,E_INVALID_STATE); // we need to handle the zero window case. don't try to send if the window is at zero // for a defined interval. if(_state.txWindow.sendWindow==0) { if(_lastZeroWindowPollTime==0) { _lastZeroWindowPollTime=now; // we can try now, this is the first time we know it to be zero _zeroWindowPollDelay=_params.tcp_initialResendDelay; } else { if(MillisecondTimer::hasTimedOut(_lastZeroWindowPollTime,_zeroWindowPollDelay)) return true; // this is not an error, zero bytes were sent because the window is closed else { _lastZeroWindowPollTime=now; // we can try again now _zeroWindowPollDelay=std::min(_params.tcp_maxResendDelay,_zeroWindowPollDelay*2); } } } else _lastZeroWindowPollTime=0; // non-zero window, cancel the poll time // bufpos is the index into the user's data of the current batch being sent // batchwin is current sender receive window bufpos=0; batchwin=_state.txWindow.sendWindow; resendtimeout=_params.tcp_initialResendDelay; // if the data would be sent in one go and nagle avoidance is enabled then force the send // to be 2 packets so that the recipient will generate an ACK immediately. if(datasize<=batchwin && _params.tcp_nagleAvoidance && datasize>1) batchsendcap=(datasize/2)+1; else batchsendcap=UINT16_MAX; // set up the header flags headerFlags=TcpHeaderFlags::ACK; if(_params.tcp_push) headerFlags=headerFlags | TcpHeaderFlags::PSH; // keep going while there is data and the connection is open while(datasize>0 && !isLocalEndClosed()) { uint16_t batchsize,batchremaining; bool resend; // a batch is how much we push out without waiting for ACKs. We always try to send 1 byte even when the sender // window is closed, this effectively polls the sender for window updates if they've been advertising // a zero window to us. batchsize=std::max(1UL,std::min(datasize,static_cast<uint32_t>(batchwin))); batchremaining=batchsize; batchpos=_state.txWindow.sendNext; batchbufpos=bufpos; // expectsuna is the ACK number that we'll be expecting when this batch is done expectsuna=_state.txWindow.sendNext+batchsize; // keep transmitting segments for this batch or until the local end is closed while(batchremaining>0 && !isLocalEndClosed()) { uint16_t tosend; // send up to the remote MSS in one segment tosend=std::min(std::min(batchsendcap,batchremaining),_remoteMss); // send this segment if it's not been ACK'd already (can happen if this is a resend) if(batchpos+tosend>=_state.txWindow.sendUnacknowledged) { // create a netbuffer for the user data - only the header space is alloc'd. the user data // is transmitted in-place. NetBuffer *nb=new NetBuffer(_additionalHeaderSize+TcpHeader::getNoOptionsHeaderSize(), 0, reinterpret_cast<const uint8_t *>(data)+batchbufpos, tosend); // create the header TcpHeader *header=reinterpret_cast<TcpHeader *>(nb->moveWritePointerBack(TcpHeader::getNoOptionsHeaderSize())); header->initialise(_state.localPort, _state.remotePort, batchpos, // where we are sending from _state.rxWindow.receiveNext, // ack up to receiveNext _state.rxWindow.receiveWindow, // current window size headerFlags); // always ACK // ask the IP layer to send the packet IpTransmitRequestEvent iptre( nb, _state.remoteAddress, IpProtocol::TCP); _networkUtilityObjects->NetworkSendEventSender.raiseEvent(iptre); if(!iptre.succeeded) return false; } // update the sequence number (batchpos) and the user buffer position (batchbufpos) batchpos+=tosend; batchbufpos+=tosend; batchremaining-=tosend; } // reset the resend flag resend=false; startwait=MillisecondTimer::millis(); // wait for the ACKs on that last batch to come back while(expectsuna!=_state.txWindow.sendUnacknowledged && !isLocalEndClosed()) { // check for user timeout, measured from the beginning of the call if(timeoutMillis && MillisecondTimer::hasTimedOut(now,timeoutMillis)) return _networkUtilityObjects->setError(ErrorProvider::ERROR_PROVIDER_NET_TCP_CONNECTION,E_TIMED_OUT); // check for resend timeout for this batch if(MillisecondTimer::hasTimedOut(startwait,resendtimeout)) { resend=true; resendtimeout=std::min(_params.tcp_maxResendDelay,resendtimeout*2); break; } } // if we're not about to go into a resend of this batch then update the batch position // for the next run if(!resend) { resendtimeout=_params.tcp_initialResendDelay; bufpos=batchbufpos; _state.txWindow.sendNext=batchpos; // it's very important that sendNext and actuallySent move in sync actuallySent+=batchsize; datasize-=batchsize; batchwin=_state.txWindow.sendWindow; } } // if we bailed because the state was changed then indicate that to the caller if(isLocalEndClosed()) return _networkUtilityObjects->setError(ErrorProvider::ERROR_PROVIDER_NET_TCP_CONNECTION,E_CONNECTION_RESET); return true; } /** * Receive some data from the remote client. If the timeout is zero then this is a blocking call that will * not return until success, the other end closes, or a network error occurs. actuallyReceived will be filled * in with the actual amount of data received. * * If the other end closes then 'true' is returned and actuallyReceived may be less than you asked for. Call * isRemoteEndClosed() to test if the other end has closed. * * This is not IRQ safe. * * @param data Where to receive the data * @param dataSize The amount of data to receive * @param actuallyReceived The amount of data actually received * @param timeoutMillis The total time limit to wait for all blocking calls to complete, or zero to always block. * @return true if there was no error. */ bool TcpConnection::receive(void *data,uint32_t dataSize,uint32_t& actuallyReceived,uint32_t timeoutMillis) { uint32_t now,received; uint8_t *ptr; actuallyReceived=0; // get current time if(timeoutMillis) now=MillisecondTimer::millis(); else now=0; // keep the compiler quiet // continue until finished ptr=reinterpret_cast<uint8_t *>(data); while(dataSize>0) { if(_receiveBuffer->availableToRead()) { // copy in as much as we can received=std::min(dataSize,_receiveBuffer->availableToRead()); _receiveBuffer->read(ptr,received); // update counters dataSize-=received; actuallyReceived+=received; ptr+=received; _state.rxWindow.receiveWindow=_receiveBuffer->availableToWrite(); // reset timeout base if(timeoutMillis) now=MillisecondTimer::millis(); } else { // there is nothing to read. has the remote end closed the connection? if so then nothing // more is ever going to arrive. this is not an error condition. if(isRemoteEndClosed()) break; else { // no data arrived and the remote end is still open. check for timeout. if(timeoutMillis && MillisecondTimer::hasTimedOut(now,timeoutMillis)) { // if some data was received then this is not an error if(actuallyReceived) break; // no data arrived and we timed out. this is an error return _networkUtilityObjects->setError(ErrorProvider::ERROR_PROVIDER_NET_TCP_CONNECTION,E_TIMED_OUT); } } } } // if we've got some data then we can check if a currently-closed receive window can be opened if(actuallyReceived) { // this must be done with IRQs suspended IrqSuspend suspender; // if the receive window is closed and we can now open it then do so if(_receiveWindowIsClosed && receiveWindowCanBeOpened()) { _receiveWindowIsClosed=false; _state.sendAck(*_networkUtilityObjects,sillyWindowAvoidance()); } } // finished return true; } } } #endif
Name: ys_w64.asm Type: file Size: 22163 Last-Modified: '2016-05-13T04:50:38Z' SHA-1: 5A3A00130CC3446808BF436D1E56424BC1E91049 Description: null
; void *obstack_int_grow_callee(struct obstack *ob, int data) SECTION code_clib SECTION code_alloc_obstack PUBLIC _obstack_int_grow_callee EXTERN asm_obstack_int_grow _obstack_int_grow_callee: pop af pop hl pop bc push af jp asm_obstack_int_grow
#include <nano/lib/config.hpp> #include <nano/lib/tomlconfig.hpp> #include <nano/node/cli.hpp> #include <nano/node/common.hpp> #include <nano/node/daemonconfig.hpp> #include <nano/node/node.hpp> namespace { void reset_confirmation_heights (nano::block_store & store); bool is_using_rocksdb (boost::filesystem::path const & data_path, std::error_code & ec); } std::string nano::error_cli_messages::message (int ev) const { switch (static_cast<nano::error_cli> (ev)) { case nano::error_cli::generic: return "Unknown error"; case nano::error_cli::parse_error: return "Coud not parse command line"; case nano::error_cli::invalid_arguments: return "Invalid arguments"; case nano::error_cli::unknown_command: return "Unknown command"; case nano::error_cli::database_write_error: return "Database write error"; case nano::error_cli::reading_config: return "Config file read error"; case nano::error_cli::disable_all_network: return "Flags --disable_tcp_realtime and --disable_udp cannot be used together"; } return "Invalid error code"; } void nano::add_node_options (boost::program_options::options_description & description_a) { // clang-format off description_a.add_options () ("account_create", "Insert next deterministic key in to <wallet>") ("account_get", "Get account number for the <key>") ("account_key", "Get the public key for <account>") ("vacuum", "Compact database. If data_path is missing, the database in data directory is compacted.") ("snapshot", "Compact database and create snapshot, functions similar to vacuum but does not replace the existing database") ("data_path", boost::program_options::value<std::string> (), "Use the supplied path as the data directory") ("network", boost::program_options::value<std::string> (), "Use the supplied network (live, beta or test)") ("clear_send_ids", "Remove all send IDs from the database (dangerous: not intended for production use)") ("online_weight_clear", "Clear online weight history records") ("peer_clear", "Clear online peers database dump") ("unchecked_clear", "Clear unchecked blocks") ("confirmation_height_clear", "Clear confirmation height") ("diagnostics", "Run internal diagnostics") ("generate_config", boost::program_options::value<std::string> (), "Write configuration to stdout, populated with defaults suitable for this system. Pass the configuration type node or rpc. See also use_defaults.") ("key_create", "Generates a adhoc random keypair and prints it to stdout") ("key_expand", "Derive public key and account number from <key>") ("wallet_add_adhoc", "Insert <key> in to <wallet>") ("wallet_create", "Creates a new wallet and prints the ID") ("wallet_change_seed", "Changes seed for <wallet> to <key>") ("wallet_decrypt_unsafe", "Decrypts <wallet> using <password>, !!THIS WILL PRINT YOUR PRIVATE KEY TO STDOUT!!") ("wallet_destroy", "Destroys <wallet> and all keys it contains") ("wallet_import", "Imports keys in <file> using <password> in to <wallet>") ("wallet_list", "Dumps wallet IDs and public keys") ("wallet_remove", "Remove <account> from <wallet>") ("wallet_representative_get", "Prints default representative for <wallet>") ("wallet_representative_set", "Set <account> as default representative for <wallet>") ("vote_dump", "Dump most recent votes from representatives") ("account", boost::program_options::value<std::string> (), "Defines <account> for other commands") ("file", boost::program_options::value<std::string> (), "Defines <file> for other commands") ("key", boost::program_options::value<std::string> (), "Defines the <key> for other commands, hex") ("seed", boost::program_options::value<std::string> (), "Defines the <seed> for other commands, hex") ("password", boost::program_options::value<std::string> (), "Defines <password> for other commands") ("wallet", boost::program_options::value<std::string> (), "Defines <wallet> for other commands") ("force", boost::program_options::value<bool>(), "Bool to force command if allowed") ("use_defaults", "If present, the generate_config command will generate uncommented entries"); // clang-format on } void nano::add_node_flag_options (boost::program_options::options_description & description_a) { // clang-format off description_a.add_options() ("disable_backup", "Disable wallet automatic backups") ("disable_lazy_bootstrap", "Disables lazy bootstrap") ("disable_legacy_bootstrap", "Disables legacy bootstrap") ("disable_wallet_bootstrap", "Disables wallet lazy bootstrap") ("disable_bootstrap_listener", "Disables bootstrap processing for TCP listener (not including realtime network TCP connections)") ("disable_tcp_realtime", "Disables TCP realtime network") ("disable_udp", "Disables UDP realtime network") ("disable_unchecked_cleanup", "Disables periodic cleanup of old records from unchecked table") ("disable_unchecked_drop", "Disables drop of unchecked table at startup") ("fast_bootstrap", "Increase bootstrap speed for high end nodes with higher limits") ("batch_size", boost::program_options::value<std::size_t>(), "Increase sideband batch size, default 512") ("block_processor_batch_size", boost::program_options::value<std::size_t>(), "Increase block processor transaction batch write size, default 0 (limited by config block_processor_batch_max_time), 256k for fast_bootstrap") ("block_processor_full_size", boost::program_options::value<std::size_t>(), "Increase block processor allowed blocks queue size before dropping live network packets and holding bootstrap download, default 65536, 1 million for fast_bootstrap") ("block_processor_verification_size", boost::program_options::value<std::size_t>(), "Increase batch signature verification size in block processor, default 0 (limited by config signature_checker_threads), unlimited for fast_bootstrap"); // clang-format on } std::error_code nano::update_flags (nano::node_flags & flags_a, boost::program_options::variables_map const & vm) { std::error_code ec; auto batch_size_it = vm.find ("batch_size"); if (batch_size_it != vm.end ()) { flags_a.sideband_batch_size = batch_size_it->second.as<size_t> (); } flags_a.disable_backup = (vm.count ("disable_backup") > 0); flags_a.disable_lazy_bootstrap = (vm.count ("disable_lazy_bootstrap") > 0); flags_a.disable_legacy_bootstrap = (vm.count ("disable_legacy_bootstrap") > 0); flags_a.disable_wallet_bootstrap = (vm.count ("disable_wallet_bootstrap") > 0); flags_a.disable_bootstrap_listener = (vm.count ("disable_bootstrap_listener") > 0); flags_a.disable_tcp_realtime = (vm.count ("disable_tcp_realtime") > 0); flags_a.disable_udp = (vm.count ("disable_udp") > 0); if (flags_a.disable_tcp_realtime && flags_a.disable_udp) { ec = nano::error_cli::disable_all_network; } flags_a.disable_unchecked_cleanup = (vm.count ("disable_unchecked_cleanup") > 0); flags_a.disable_unchecked_drop = (vm.count ("disable_unchecked_drop") > 0); flags_a.fast_bootstrap = (vm.count ("fast_bootstrap") > 0); if (flags_a.fast_bootstrap) { flags_a.block_processor_batch_size = 256 * 1024; flags_a.block_processor_full_size = 1024 * 1024; flags_a.block_processor_verification_size = std::numeric_limits<size_t>::max (); } auto block_processor_batch_size_it = vm.find ("block_processor_batch_size"); if (block_processor_batch_size_it != vm.end ()) { flags_a.block_processor_batch_size = block_processor_batch_size_it->second.as<size_t> (); } auto block_processor_full_size_it = vm.find ("block_processor_full_size"); if (block_processor_full_size_it != vm.end ()) { flags_a.block_processor_full_size = block_processor_full_size_it->second.as<size_t> (); } auto block_processor_verification_size_it = vm.find ("block_processor_verification_size"); if (block_processor_verification_size_it != vm.end ()) { flags_a.block_processor_verification_size = block_processor_verification_size_it->second.as<size_t> (); } return ec; } namespace { void database_write_lock_error (std::error_code & ec) { std::cerr << "Write database error, this cannot be run while the node is already running\n"; ec = nano::error_cli::database_write_error; } bool copy_database (boost::filesystem::path const & data_path, boost::program_options::variables_map & vm, boost::filesystem::path const & output_path, std::error_code & ec) { bool success = false; bool needs_to_write = vm.count ("unchecked_clear") || vm.count ("clear_send_ids") || vm.count ("online_weight_clear") || vm.count ("peer_clear") || vm.count ("confirmation_height_clear"); auto node_flags = nano::inactive_node_flag_defaults (); node_flags.read_only = !needs_to_write; nano::inactive_node node (data_path, 24000, node_flags); if (!node.node->init_error ()) { if (vm.count ("unchecked_clear")) { auto transaction (node.node->store.tx_begin_write ()); node.node->store.unchecked_clear (transaction); } if (vm.count ("clear_send_ids")) { auto transaction (node.node->wallets.tx_begin_write ()); node.node->wallets.clear_send_ids (transaction); } if (vm.count ("online_weight_clear")) { auto transaction (node.node->store.tx_begin_write ()); node.node->store.online_weight_clear (transaction); } if (vm.count ("peer_clear")) { auto transaction (node.node->store.tx_begin_write ()); node.node->store.peer_clear (transaction); } if (vm.count ("confirmation_height_clear")) { reset_confirmation_heights (node.node->store); } success = node.node->copy_with_compaction (output_path); } else { database_write_lock_error (ec); } return success; } } std::error_code nano::handle_node_options (boost::program_options::variables_map & vm) { std::error_code ec; boost::filesystem::path data_path = vm.count ("data_path") ? boost::filesystem::path (vm["data_path"].as<std::string> ()) : nano::working_path (); if (vm.count ("account_create")) { if (vm.count ("wallet") == 1) { nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { std::string password; if (vm.count ("password") > 0) { password = vm["password"].as<std::string> (); } inactive_node node (data_path); auto wallet (node.node->wallets.open (wallet_id)); if (wallet != nullptr) { auto transaction (wallet->wallets.tx_begin_write ()); if (!wallet->enter_password (transaction, password)) { auto pub (wallet->store.deterministic_insert (transaction)); std::cout << boost::str (boost::format ("Account: %1%\n") % pub.to_account ()); } else { std::cerr << "Invalid password\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Wallet doesn't exist\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_add command requires one <wallet> option and one <key> option and optionally one <password> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("account_get") > 0) { if (vm.count ("key") == 1) { nano::account pub; pub.decode_hex (vm["key"].as<std::string> ()); std::cout << "Account: " << pub.to_account () << std::endl; } else { std::cerr << "account comand requires one <key> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("account_key") > 0) { if (vm.count ("account") == 1) { nano::account account; account.decode_account (vm["account"].as<std::string> ()); std::cout << "Hex: " << account.to_string () << std::endl; } else { std::cerr << "account_key command requires one <account> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("vacuum") > 0) { try { auto using_rocksdb = is_using_rocksdb (data_path, ec); if (!ec) { std::cout << "Vacuuming database copy in "; boost::filesystem::path source_path; boost::filesystem::path backup_path; boost::filesystem::path vacuum_path; if (using_rocksdb) { source_path = data_path / "rocksdb"; backup_path = source_path / "backup"; vacuum_path = backup_path / "vacuumed"; if (!boost::filesystem::exists (vacuum_path)) { boost::filesystem::create_directories (vacuum_path); } std::cout << source_path << "\n"; } else { source_path = data_path / "data.ldb"; backup_path = data_path / "backup.vacuum.ldb"; vacuum_path = data_path / "vacuumed.ldb"; std::cout << data_path << "\n"; } std::cout << "This may take a while..." << std::endl; bool success = copy_database (data_path, vm, vacuum_path, ec); if (success) { // Note that these throw on failure std::cout << "Finalizing" << std::endl; if (using_rocksdb) { nano::remove_all_files_in_dir (backup_path); nano::move_all_files_to_dir (source_path, backup_path); nano::move_all_files_to_dir (vacuum_path, source_path); boost::filesystem::remove_all (vacuum_path); } else { boost::filesystem::remove (backup_path); boost::filesystem::rename (source_path, backup_path); boost::filesystem::rename (vacuum_path, source_path); } std::cout << "Vacuum completed" << std::endl; } else { std::cerr << "Vacuum failed (copying returned false)" << std::endl; } } else { std::cerr << "Vacuum failed. RocksDB is enabled but the node has not been built with RocksDB support" << std::endl; } } catch (const boost::filesystem::filesystem_error & ex) { std::cerr << "Vacuum failed during a file operation: " << ex.what () << std::endl; } catch (...) { std::cerr << "Vacuum failed (unknown reason)" << std::endl; } } else if (vm.count ("snapshot")) { try { auto using_rocksdb = is_using_rocksdb (data_path, ec); if (!ec) { boost::filesystem::path source_path; boost::filesystem::path snapshot_path; if (using_rocksdb) { source_path = data_path / "rocksdb"; snapshot_path = source_path / "backup"; } else { source_path = data_path / "data.ldb"; snapshot_path = data_path / "snapshot.ldb"; } std::cout << "Database snapshot of " << source_path << " to " << snapshot_path << " in progress" << std::endl; std::cout << "This may take a while..." << std::endl; bool success = copy_database (data_path, vm, snapshot_path, ec); if (success) { std::cout << "Snapshot completed, This can be found at " << snapshot_path << std::endl; } else { std::cerr << "Snapshot failed (copying returned false)" << std::endl; } } else { std::cerr << "Snapshot failed. RocksDB is enabled but the node has not been built with RocksDB support" << std::endl; } } catch (const boost::filesystem::filesystem_error & ex) { std::cerr << "Snapshot failed during a file operation: " << ex.what () << std::endl; } catch (...) { std::cerr << "Snapshot failed (unknown reason)" << std::endl; } } else if (vm.count ("unchecked_clear")) { boost::filesystem::path data_path = vm.count ("data_path") ? boost::filesystem::path (vm["data_path"].as<std::string> ()) : nano::working_path (); auto node_flags = nano::inactive_node_flag_defaults (); node_flags.read_only = false; nano::inactive_node node (data_path, 24000, node_flags); if (!node.node->init_error ()) { auto transaction (node.node->store.tx_begin_write ()); node.node->store.unchecked_clear (transaction); std::cout << "Unchecked blocks deleted" << std::endl; } else { database_write_lock_error (ec); } } else if (vm.count ("clear_send_ids")) { boost::filesystem::path data_path = vm.count ("data_path") ? boost::filesystem::path (vm["data_path"].as<std::string> ()) : nano::working_path (); auto node_flags = nano::inactive_node_flag_defaults (); node_flags.read_only = false; nano::inactive_node node (data_path, 24000, node_flags); if (!node.node->init_error ()) { auto transaction (node.node->wallets.tx_begin_write ()); node.node->wallets.clear_send_ids (transaction); std::cout << "Send IDs deleted" << std::endl; } else { database_write_lock_error (ec); } } else if (vm.count ("online_weight_clear")) { boost::filesystem::path data_path = vm.count ("data_path") ? boost::filesystem::path (vm["data_path"].as<std::string> ()) : nano::working_path (); auto node_flags = nano::inactive_node_flag_defaults (); node_flags.read_only = false; nano::inactive_node node (data_path, 24000, node_flags); if (!node.node->init_error ()) { auto transaction (node.node->store.tx_begin_write ()); node.node->store.online_weight_clear (transaction); std::cout << "Onine weight records are removed" << std::endl; } else { database_write_lock_error (ec); } } else if (vm.count ("peer_clear")) { boost::filesystem::path data_path = vm.count ("data_path") ? boost::filesystem::path (vm["data_path"].as<std::string> ()) : nano::working_path (); auto node_flags = nano::inactive_node_flag_defaults (); node_flags.read_only = false; nano::inactive_node node (data_path, 24000, node_flags); if (!node.node->init_error ()) { auto transaction (node.node->store.tx_begin_write ()); node.node->store.peer_clear (transaction); std::cout << "Database peers are removed" << std::endl; } else { database_write_lock_error (ec); } } else if (vm.count ("confirmation_height_clear")) { boost::filesystem::path data_path = vm.count ("data_path") ? boost::filesystem::path (vm["data_path"].as<std::string> ()) : nano::working_path (); auto node_flags = nano::inactive_node_flag_defaults (); node_flags.read_only = false; nano::inactive_node node (data_path, 24000, node_flags); if (!node.node->init_error ()) { auto account_it = vm.find ("account"); if (account_it != vm.cend ()) { auto account_str = account_it->second.as<std::string> (); nano::account account; if (!account.decode_account (account_str)) { uint64_t confirmation_height; auto transaction (node.node->store.tx_begin_read ()); if (!node.node->store.confirmation_height_get (transaction, account, confirmation_height)) { auto transaction (node.node->store.tx_begin_write ()); auto conf_height_reset_num = 0; if (account == node.node->network_params.ledger.genesis_account) { conf_height_reset_num = 1; node.node->store.confirmation_height_put (transaction, account, confirmation_height); } else { node.node->store.confirmation_height_clear (transaction, account, confirmation_height); } std::cout << "Confirmation height of account " << account_str << " is set to " << conf_height_reset_num << std::endl; } else { std::cerr << "Could not find account" << std::endl; ec = nano::error_cli::generic; } } else { std::cerr << "Invalid account id\n"; ec = nano::error_cli::invalid_arguments; } } else { reset_confirmation_heights (node.node->store); std::cout << "Confirmation heights of all accounts (except genesis which is set to 1) are set to 0" << std::endl; } } else { database_write_lock_error (ec); } } else if (vm.count ("generate_config")) { auto type = vm["generate_config"].as<std::string> (); nano::tomlconfig toml; bool valid_type = false; if (type == "node") { valid_type = true; nano::daemon_config config (data_path); config.serialize_toml (toml); } else if (type == "rpc") { valid_type = true; nano::rpc_config config (false); config.serialize_toml (toml); } else { std::cerr << "Invalid configuration type " << type << ". Must be node or rpc." << std::endl; } if (valid_type) { std::cout << "# This is an example configuration file for Nano. Visit https://docs.nano.org/running-a-node/configuration/ for more information.\n#\n" << "# Fields may need to be defined in the context of a [category] above them.\n" << "# The desired configuration changes should be placed in config-" << type << ".toml in the node data path.\n" << "# To change a value from its default, uncomment (erasing #) the corresponding field.\n" << "# It is not recommended to uncomment every field, as the default value for important fields may change in the future. Only change what you need.\n" << "# Additional information for notable configuration options is available in https://docs.nano.org/running-a-node/configuration/#notable-configuration-options\n"; if (vm.count ("use_defaults")) { std::cout << toml.to_string () << std::endl; } else { std::cout << toml.to_string_commented_entries () << std::endl; } } } else if (vm.count ("diagnostics")) { inactive_node node (data_path); std::cout << "Testing hash function" << std::endl; nano::raw_key key; key.data.clear (); nano::send_block send (0, 0, 0, key, 0, 0); std::cout << "Testing key derivation function" << std::endl; nano::raw_key junk1; junk1.data.clear (); nano::uint256_union junk2 (0); nano::kdf kdf; kdf.phs (junk1, "", junk2); std::cout << "Dumping OpenCL information" << std::endl; bool error (false); nano::opencl_environment environment (error); if (!error) { environment.dump (std::cout); std::stringstream stream; environment.dump (stream); node.node->logger.always_log (stream.str ()); } else { std::cerr << "Error initializing OpenCL" << std::endl; ec = nano::error_cli::generic; } } else if (vm.count ("key_create")) { nano::keypair pair; std::cout << "Private: " << pair.prv.data.to_string () << std::endl << "Public: " << pair.pub.to_string () << std::endl << "Account: " << pair.pub.to_account () << std::endl; } else if (vm.count ("key_expand")) { if (vm.count ("key") == 1) { nano::private_key prv; prv.decode_hex (vm["key"].as<std::string> ()); nano::public_key pub (nano::pub_key (prv)); std::cout << "Private: " << prv.to_string () << std::endl << "Public: " << pub.to_string () << std::endl << "Account: " << pub.to_account () << std::endl; } else { std::cerr << "key_expand command requires one <key> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("wallet_add_adhoc")) { if (vm.count ("wallet") == 1 && vm.count ("key") == 1) { nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { std::string password; if (vm.count ("password") > 0) { password = vm["password"].as<std::string> (); } inactive_node node (data_path); auto wallet (node.node->wallets.open (wallet_id)); if (wallet != nullptr) { auto transaction (wallet->wallets.tx_begin_write ()); if (!wallet->enter_password (transaction, password)) { nano::raw_key key; if (!key.data.decode_hex (vm["key"].as<std::string> ())) { wallet->store.insert_adhoc (transaction, key); } else { std::cerr << "Invalid key\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid password\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Wallet doesn't exist\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_add command requires one <wallet> option and one <key> option and optionally one <password> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("wallet_change_seed")) { if (vm.count ("wallet") == 1 && (vm.count ("seed") == 1 || vm.count ("key") == 1)) { nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { std::string password; if (vm.count ("password") > 0) { password = vm["password"].as<std::string> (); } inactive_node node (data_path); auto wallet (node.node->wallets.open (wallet_id)); if (wallet != nullptr) { auto transaction (wallet->wallets.tx_begin_write ()); if (!wallet->enter_password (transaction, password)) { nano::raw_key seed; if (vm.count ("seed")) { if (seed.data.decode_hex (vm["seed"].as<std::string> ())) { std::cerr << "Invalid seed\n"; ec = nano::error_cli::invalid_arguments; } } else if (seed.data.decode_hex (vm["key"].as<std::string> ())) { std::cerr << "Invalid key seed\n"; ec = nano::error_cli::invalid_arguments; } if (!ec) { std::cout << "Changing seed and caching work. Please wait..." << std::endl; wallet->change_seed (transaction, seed); } } else { std::cerr << "Invalid password\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Wallet doesn't exist\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_change_seed command requires one <wallet> option and one <seed> option and optionally one <password> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("wallet_create")) { nano::raw_key seed_key; if (vm.count ("seed") == 1) { if (seed_key.data.decode_hex (vm["seed"].as<std::string> ())) { std::cerr << "Invalid seed\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("seed") > 1) { std::cerr << "wallet_create command allows one optional <seed> parameter\n"; ec = nano::error_cli::invalid_arguments; } else if (vm.count ("key") == 1) { if (seed_key.data.decode_hex (vm["key"].as<std::string> ())) { std::cerr << "Invalid seed key\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("key") > 1) { std::cerr << "wallet_create command allows one optional <key> seed parameter\n"; ec = nano::error_cli::invalid_arguments; } if (!ec) { inactive_node node (data_path); auto wallet_key = nano::random_wallet_id (); auto wallet (node.node->wallets.create (wallet_key)); if (wallet != nullptr) { if (vm.count ("password") > 0) { std::string password (vm["password"].as<std::string> ()); auto transaction (wallet->wallets.tx_begin_write ()); auto error (wallet->store.rekey (transaction, password)); if (error) { std::cerr << "Password change error\n"; ec = nano::error_cli::invalid_arguments; } } if (vm.count ("seed") || vm.count ("key")) { auto transaction (wallet->wallets.tx_begin_write ()); wallet->change_seed (transaction, seed_key); } std::cout << wallet_key.to_string () << std::endl; } else { std::cerr << "Wallet creation error\n"; ec = nano::error_cli::invalid_arguments; } } } else if (vm.count ("wallet_decrypt_unsafe")) { if (vm.count ("wallet") == 1) { std::string password; if (vm.count ("password") == 1) { password = vm["password"].as<std::string> (); } nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { inactive_node node (data_path); auto existing (node.node->wallets.items.find (wallet_id)); if (existing != node.node->wallets.items.end ()) { auto transaction (existing->second->wallets.tx_begin_write ()); if (!existing->second->enter_password (transaction, password)) { nano::raw_key seed; existing->second->store.seed (seed, transaction); std::cout << boost::str (boost::format ("Seed: %1%\n") % seed.data.to_string ()); for (auto i (existing->second->store.begin (transaction)), m (existing->second->store.end ()); i != m; ++i) { nano::account const & account (i->first); nano::raw_key key; auto error (existing->second->store.fetch (transaction, account, key)); (void)error; assert (!error); std::cout << boost::str (boost::format ("Pub: %1% Prv: %2%\n") % account.to_account () % key.data.to_string ()); if (nano::pub_key (key.as_private_key ()) != account) { std::cerr << boost::str (boost::format ("Invalid private key %1%\n") % key.data.to_string ()); } } } else { std::cerr << "Invalid password\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Wallet doesn't exist\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_decrypt_unsafe requires one <wallet> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("wallet_destroy")) { if (vm.count ("wallet") == 1) { nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { inactive_node node (data_path); if (node.node->wallets.items.find (wallet_id) != node.node->wallets.items.end ()) { node.node->wallets.destroy (wallet_id); } else { std::cerr << "Wallet doesn't exist\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_destroy requires one <wallet> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("wallet_import")) { if (vm.count ("file") == 1) { std::string filename (vm["file"].as<std::string> ()); std::ifstream stream; stream.open (filename.c_str ()); if (!stream.fail ()) { std::stringstream contents; contents << stream.rdbuf (); std::string password; if (vm.count ("password") == 1) { password = vm["password"].as<std::string> (); } bool forced (false); if (vm.count ("force") == 1) { forced = vm["force"].as<bool> (); } if (vm.count ("wallet") == 1) { nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { inactive_node node (data_path); auto existing (node.node->wallets.items.find (wallet_id)); if (existing != node.node->wallets.items.end ()) { bool valid (false); { auto transaction (node.node->wallets.tx_begin_write ()); valid = existing->second->store.valid_password (transaction); if (!valid) { valid = !existing->second->enter_password (transaction, password); } } if (valid) { if (existing->second->import (contents.str (), password)) { std::cerr << "Unable to import wallet\n"; ec = nano::error_cli::invalid_arguments; } else { std::cout << "Import completed\n"; } } else { std::cerr << boost::str (boost::format ("Invalid password for wallet %1%\nNew wallet should have empty (default) password or passwords for new wallet & json file should match\n") % wallet_id.to_string ()); ec = nano::error_cli::invalid_arguments; } } else { if (!forced) { std::cerr << "Wallet doesn't exist\n"; ec = nano::error_cli::invalid_arguments; } else { bool error (true); { nano::lock_guard<std::mutex> lock (node.node->wallets.mutex); auto transaction (node.node->wallets.tx_begin_write ()); nano::wallet wallet (error, transaction, node.node->wallets, wallet_id.to_string (), contents.str ()); } if (error) { std::cerr << "Unable to import wallet\n"; ec = nano::error_cli::invalid_arguments; } else { node.node->wallets.reload (); nano::lock_guard<std::mutex> lock (node.node->wallets.mutex); release_assert (node.node->wallets.items.find (wallet_id) != node.node->wallets.items.end ()); std::cout << "Import completed\n"; } } } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_import requires one <wallet> option\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Unable to open <file>\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_import requires one <file> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("wallet_list")) { inactive_node node (data_path); for (auto i (node.node->wallets.items.begin ()), n (node.node->wallets.items.end ()); i != n; ++i) { std::cout << boost::str (boost::format ("Wallet ID: %1%\n") % i->first.to_string ()); auto transaction (i->second->wallets.tx_begin_read ()); for (auto j (i->second->store.begin (transaction)), m (i->second->store.end ()); j != m; ++j) { std::cout << nano::account (j->first).to_account () << '\n'; } } } else if (vm.count ("wallet_remove")) { if (vm.count ("wallet") == 1 && vm.count ("account") == 1) { inactive_node node (data_path); nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { auto wallet (node.node->wallets.items.find (wallet_id)); if (wallet != node.node->wallets.items.end ()) { nano::account account_id; if (!account_id.decode_account (vm["account"].as<std::string> ())) { auto transaction (wallet->second->wallets.tx_begin_write ()); auto account (wallet->second->store.find (transaction, account_id)); if (account != wallet->second->store.end ()) { wallet->second->store.erase (transaction, account_id); } else { std::cerr << "Account not found in wallet\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid account id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Wallet not found\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_remove command requires one <wallet> and one <account> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("wallet_representative_get")) { if (vm.count ("wallet") == 1) { nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { inactive_node node (data_path); auto wallet (node.node->wallets.items.find (wallet_id)); if (wallet != node.node->wallets.items.end ()) { auto transaction (wallet->second->wallets.tx_begin_read ()); auto representative (wallet->second->store.representative (transaction)); std::cout << boost::str (boost::format ("Representative: %1%\n") % representative.to_account ()); } else { std::cerr << "Wallet not found\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_representative_get requires one <wallet> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("wallet_representative_set")) { if (vm.count ("wallet") == 1) { if (vm.count ("account") == 1) { nano::wallet_id wallet_id; if (!wallet_id.decode_hex (vm["wallet"].as<std::string> ())) { nano::account account; if (!account.decode_account (vm["account"].as<std::string> ())) { inactive_node node (data_path); auto wallet (node.node->wallets.items.find (wallet_id)); if (wallet != node.node->wallets.items.end ()) { auto transaction (wallet->second->wallets.tx_begin_write ()); wallet->second->store.representative_set (transaction, account); } else { std::cerr << "Wallet not found\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid account\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "Invalid wallet id\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_representative_set requires one <account> option\n"; ec = nano::error_cli::invalid_arguments; } } else { std::cerr << "wallet_representative_set requires one <wallet> option\n"; ec = nano::error_cli::invalid_arguments; } } else if (vm.count ("vote_dump") == 1) { inactive_node node (data_path); auto transaction (node.node->store.tx_begin_read ()); for (auto i (node.node->store.vote_begin (transaction)), n (node.node->store.vote_end ()); i != n; ++i) { auto const & vote (i->second); std::cerr << boost::str (boost::format ("%1%\n") % vote->to_json ()); } } else { ec = nano::error_cli::unknown_command; } return ec; } namespace { void reset_confirmation_heights (nano::block_store & store) { // First do a clean sweep auto transaction (store.tx_begin_write ()); store.confirmation_height_clear (transaction); // Then make sure the confirmation height of the genesis account open block is 1 nano::network_params network_params; store.confirmation_height_put (transaction, network_params.ledger.genesis_account, 1); } bool is_using_rocksdb (boost::filesystem::path const & data_path, std::error_code & ec) { nano::daemon_config config (data_path); auto error = nano::read_node_config_toml (data_path, config); if (!error) { bool use_rocksdb = config.node.rocksdb_config.enable; if (use_rocksdb) { #if !NANO_ROCKSDB ec = nano::error_cli::database_write_error; #endif return (NANO_ROCKSDB == 1); } } else { ec = nano::error_cli::reading_config; } return false; } }
; A254729: Number of numbers j + k*sqrt(2) of length n, where the length is the least number of steps to reach 0, the allowable steps being x -> x + 1 and x -> x*sqrt(2). ; 1,1,2,3,4,7,11,18,29,47,76,123,199,322,521,843,1364,2207,3571,5778,9349,15127,24476,39603,64079,103682,167761,271443,439204,710647,1149851,1860498,3010349,4870847,7881196,12752043,20633239,33385282,54018521,87403803,141422324,228826127,370248451,599074578,969323029,1568397607,2537720636,4106118243,6643838879,10749957122,17393796001,28143753123,45537549124,73681302247,119218851371,192900153618,312119004989,505019158607,817138163596,1322157322203,2139295485799,3461452808002,5600748293801,9062201101803,14662949395604,23725150497407,38388099893011,62113250390418,100501350283429,162614600673847,263115950957276,425730551631123,688846502588399,1114577054219522,1803423556807921,2918000611027443,4721424167835364,7639424778862807,12360848946698171,20000273725560978,32361122672259149,52361396397820127,84722519070079276,137083915467899403,221806434537978679,358890350005878082,580696784543856761,939587134549734843,1520283919093591604,2459871053643326447,3980154972736918051,6440026026380244498,10420180999117162549,16860207025497407047,27280388024614569596,44140595050111976643,71420983074726546239,115561578124838522882,186982561199565069121,302544139324403592003 trn $0,1 seq $0,324015 ; Number of nonempty subsets of {1, ..., n} containing no two cyclically successive elements. add $0,1
CeladonPrizeRoom_h: db LOBBY ; tileset db CELADON_PRIZE_ROOM_HEIGHT, CELADON_PRIZE_ROOM_WIDTH ; dimensions (y, x) dw CeladonPrizeRoomBlocks, CeladonPrizeRoomTextPointers, CeladonPrizeRoomScript ; blocks, texts, scripts db $00 ; connections dw CeladonPrizeRoomObject ; objects
; --------------------------------------------------------------------------- ; Sprite mappings - walls of the special stage ; --------------------------------------------------------------------------- Map_SSWalls_internal: dc.w byte_2C584-Map_SSWalls_internal dc.w byte_2C58A-Map_SSWalls_internal dc.w byte_2C590-Map_SSWalls_internal dc.w byte_2C596-Map_SSWalls_internal dc.w byte_2C59C-Map_SSWalls_internal dc.w byte_2C5A2-Map_SSWalls_internal dc.w byte_2C5A8-Map_SSWalls_internal dc.w byte_2C5AE-Map_SSWalls_internal dc.w byte_2C5B4-Map_SSWalls_internal dc.w byte_2C5BA-Map_SSWalls_internal dc.w byte_2C5C0-Map_SSWalls_internal dc.w byte_2C5C6-Map_SSWalls_internal dc.w byte_2C5CC-Map_SSWalls_internal dc.w byte_2C5D2-Map_SSWalls_internal dc.w byte_2C5D8-Map_SSWalls_internal dc.w byte_2C5DE-Map_SSWalls_internal byte_2C584: dc.b 1 dc.b $F4, $A, 0, 0, $F4 byte_2C58A: dc.b 1 dc.b $F0, $F, 0, 9, $F0 byte_2C590: dc.b 1 dc.b $F0, $F, 0, $19, $F0 byte_2C596: dc.b 1 dc.b $F0, $F, 0, $29, $F0 byte_2C59C: dc.b 1 dc.b $F0, $F, 0, $39, $F0 byte_2C5A2: dc.b 1 dc.b $F0, $F, 0, $49, $F0 byte_2C5A8: dc.b 1 dc.b $F0, $F, 0, $59, $F0 byte_2C5AE: dc.b 1 dc.b $F0, $F, 0, $69, $F0 byte_2C5B4: dc.b 1 dc.b $F0, $F, 0, $79, $F0 byte_2C5BA: dc.b 1 dc.b $F0, $F, 0, $89, $F0 byte_2C5C0: dc.b 1 dc.b $F0, $F, 0, $99, $F0 byte_2C5C6: dc.b 1 dc.b $F0, $F, 0, $A9, $F0 byte_2C5CC: dc.b 1 dc.b $F0, $F, 0, $B9, $F0 byte_2C5D2: dc.b 1 dc.b $F0, $F, 0, $C9, $F0 byte_2C5D8: dc.b 1 dc.b $F0, $F, 0, $D9, $F0 byte_2C5DE: dc.b 1 dc.b $F0, $F, 0, $E9, $F0 even
; A188708: Number of 4 X n binary arrays without the pattern 0 0 diagonally or vertically. ; Submitted by Christian Krause ; 8,49,304,1876,11556,71152,438048,2696784,16602304,102209216,629233216,3873764352,23848153088,146816985344,903853103104,5564413613056,34256339608576,210893165924352,1298326906544128,7992922619695104,49207030742728704,302934482131664896,1864963178619355136,11481319766345777152,70682737915860615168,435145918845213016064,2678899774836759855104,16492178124214965108736,101531211371059454672896,625059152577243095498752,3848067396662091168350208,23689954187854050019508224,145843061353196278517858304 add $0,1 mul $0,2 mov $3,1 lpb $0 sub $0,1 add $2,$3 mov $3,$1 mov $1,$2 mul $1,2 add $1,1 add $4,1 add $4,$2 mov $2,$4 lpe mov $0,$1 div $3,2 add $0,$3 add $0,2
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r14 push %r15 push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x1026b, %rsi lea addresses_D_ht+0x15989, %rdi nop nop nop dec %r10 mov $41, %rcx rep movsw nop nop nop xor %r11, %r11 lea addresses_A_ht+0xc26b, %rsi lea addresses_WT_ht+0x1d06b, %rdi nop sub $28830, %r11 mov $69, %rcx rep movsb sub %rcx, %rcx lea addresses_UC_ht+0x1726b, %r15 nop nop nop nop dec %rbx mov (%r15), %ecx nop nop and $39960, %r11 lea addresses_WC_ht+0x2809, %r15 nop nop cmp %rdi, %rdi movw $0x6162, (%r15) nop nop inc %r11 lea addresses_UC_ht+0x10b2b, %r11 clflush (%r11) nop cmp $55816, %rdi mov (%r11), %bx nop nop nop nop nop add $18858, %r11 lea addresses_WC_ht+0x19207, %r10 clflush (%r10) nop nop nop nop dec %rcx movb $0x61, (%r10) nop and $11182, %rdi lea addresses_WC_ht+0x1186b, %r15 dec %r11 mov $0x6162636465666768, %rcx movq %rcx, %xmm0 movups %xmm0, (%r15) nop xor %rsi, %rsi lea addresses_WT_ht+0x1b29b, %r10 nop nop nop nop and $29316, %r11 movb (%r10), %r15b nop and $61527, %r10 lea addresses_D_ht+0xe61b, %rsi lea addresses_WT_ht+0x14eb, %rdi nop nop nop nop xor %r14, %r14 mov $82, %rcx rep movsl nop nop nop add %r11, %r11 pop %rsi pop %rdi pop %rcx pop %rbx pop %r15 pop %r14 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r8 push %r9 push %rbp push %rbx push %rdi // Load lea addresses_A+0xa74b, %r14 nop nop nop nop nop xor %r10, %r10 mov (%r14), %r8d xor %rbp, %rbp // Load lea addresses_US+0x316b, %r14 clflush (%r14) nop nop nop inc %r9 mov (%r14), %r10d nop nop xor $63511, %rbx // Store lea addresses_A+0x166b, %rbp nop dec %r8 movb $0x51, (%rbp) nop nop sub %rdi, %rdi // Load lea addresses_D+0x6b, %rdi nop nop nop cmp $56958, %rbp vmovntdqa (%rdi), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $1, %xmm4, %r9 nop nop nop add %rbp, %rbp // Faulty Load lea addresses_D+0x6b, %rbx clflush (%rbx) nop cmp $23004, %r10 vmovups (%rbx), %ymm1 vextracti128 $0, %ymm1, %xmm1 vpextrq $0, %xmm1, %r8 lea oracles, %r9 and $0xff, %r8 shlq $12, %r8 mov (%r9,%r8,1), %r8 pop %rdi pop %rbx pop %rbp pop %r9 pop %r8 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_A', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_US', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_A', 'AVXalign': False, 'size': 1}} {'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_D_ht'}} {'src': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2}} {'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16}} {'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 3, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
/* * Copyright (c), Microsoft Open Technologies, Inc. * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 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 <Windows.h> #include <errno.h> #include <stdio.h> #include <wchar.h> #include <Psapi.h> #define QFORK_MAIN_IMPL #include "Win32_QFork.h" #include "Win32_QFork_impl.h" #include "Win32_dlmalloc.h" #include "Win32_SmartHandle.h" #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <stdint.h> using namespace std; extern "C" { // forward def from util.h. long long memtoll(const char *p, int *err); } //#define DEBUG_WITH_PROCMON #ifdef DEBUG_WITH_PROCMON #define FILE_DEVICE_PROCMON_LOG 0x00009535 #define IOCTL_EXTERNAL_LOG_DEBUGOUT (ULONG) CTL_CODE( FILE_DEVICE_PROCMON_LOG, 0x81, METHOD_BUFFERED, FILE_WRITE_ACCESS ) HANDLE hProcMonDevice = INVALID_HANDLE_VALUE; BOOL WriteToProcmon (wstring message) { if (hProcMonDevice != INVALID_HANDLE_VALUE) { DWORD nb = 0; return DeviceIoControl( hProcMonDevice, IOCTL_EXTERNAL_LOG_DEBUGOUT, (LPVOID)(message.c_str()), (DWORD)(message.length() * sizeof(wchar_t)), NULL, 0, &nb, NULL); } else { return FALSE; } } #endif /* Redis is an in memory DB. We need to share the redis database with a quasi-forked process so that we can do the RDB and AOF saves without halting the main redis process, or crashing due to code that was never designed to be thread safe. Essentially we need to replicate the COW behavior of fork() on Windows, but we don't actually need a complete fork() implementation. A complete fork() implementation would require subsystem level support to make happen. The following is required to make this quasi-fork scheme work: DLMalloc (http://g.oswego.edu/dl/html/malloc.html): - replaces malloc/realloc/free, either by manual patching of the zmalloc code in Redis or by patching the CRT routines at link time - partitions space into segments that it allocates from (currently configured as 64MB chunks) - we map/unmap these chunks as requested into a memory map (unmapping allows the system to decide how to reduce the physical memory pressure on system) DLMallocMemoryMap: - An uncomitted memory map whose size is the total physical memory on the system less some memory for the rest of the system so that we avoid excessive swapping. - This is reserved high in VM space so that it can be mapped at a specific address in the child qforked process (ASLR must be disabled for these processes) - This must be mapped in exactly the same virtual memory space in both forker and forkee. QForkConrolMemoryMap: - contains a map of the allocated segments in the DLMallocMemoryMap - contains handles for inter-process synchronization - contains pointers to some of the global data in the parent process if mapped into DLMallocMemoryMap, and a copy of any other required global data QFork process: - a copy of the parent process with a command line specifying QFork behavior - when a COW operation is requested via an event signal - opens the DLMAllocMemoryMap with PAGE_WRITECOPY - reserve space for DLMAllocMemoryMap at the memory location specified in ControlMemoryMap - locks the DLMalloc segments as specified in QForkConrolMemoryMap - maps global data from the QForkConrolMEmoryMap into this process - executes the requested operation - unmaps all the mm views (discarding any writes) - signals the parent when the operation is complete How the parent invokes the QFork process: - protects mapped memory segments with VirtualProtect using PAGE_WRITECOPY (both the allocated portions of DLMAllocMemoryMap and the QForkConrolMemoryMap) - QForked process is signaled to process command - Parent waits (asynchronously) until QForked process signals that operation is complete, then as an atomic operation: - signals and waits for the forked process to terminate - resotres protection status on mapped blocks - determines which pages have been modified and copies these to a buffer - unmaps the view of the heap (discarding COW changes form the view) - remaps the view - copies the changes back into the view */ #ifndef LODWORD #define LODWORD(_qw) ((DWORD)(_qw)) #endif #ifndef HIDWORD #define HIDWORD(_qw) ((DWORD)(((_qw) >> (sizeof(DWORD)*8)) & DWORD(~0))) #endif const SIZE_T cAllocationGranularity = 1 << 18; // 256KB per heap block (matches large block allocation threshold of dlmalloc) const int cMaxBlocks = 1 << 24; // 256KB * 16M heap blocks = 4TB. 4TB is the largest memory config Windows supports at present. const wchar_t* cMapFileBaseName = L"RedisQFork"; const char* qforkFlag = "--QFork"; const char* maxmemoryFlag = "maxmemory"; const char* maxheapFlag = "maxheap"; const int cDeadForkWait = 30000; size_t pageSize = 0; enum class BlockState : std::uint8_t {bsINVALID = 0, bsUNMAPPED = 1, bsMAPPED = 2}; struct QForkControl { HANDLE heapMemoryMapFile; HANDLE heapMemoryMap; int availableBlocksInHeap; // number of blocks in blockMap (dynamically determined at run time) SIZE_T heapBlockSize; BlockState heapBlockMap[cMaxBlocks]; LPVOID heapStart; OperationType typeOfOperation; HANDLE forkedProcessReady; HANDLE startOperation; HANDLE operationComplete; HANDLE operationFailed; HANDLE terminateForkedProcess; // global data pointers to be passed to the forked process QForkBeginInfo globalData; BYTE DLMallocGlobalState[1000]; size_t DLMallocGlobalStateSize; }; QForkControl* g_pQForkControl; HANDLE g_hQForkControlFileMap; HANDLE g_hForkedProcess; DWORD g_systemAllocationGranularity; BOOL QForkSlaveInit(HANDLE QForkConrolMemoryMapHandle, DWORD ParentProcessID) { try { SmartHandle shParent( OpenProcess(SYNCHRONIZE | PROCESS_DUP_HANDLE, TRUE, ParentProcessID), string("Could not open parent process")); SmartHandle shMMFile(shParent, QForkConrolMemoryMapHandle); SmartFileView<QForkControl> sfvMasterQForkControl( shMMFile, FILE_MAP_COPY, string("Could not map view of QForkControl in slave. Is system swap file large enough?")); g_pQForkControl = sfvMasterQForkControl; // duplicate handles and stuff into control structure (master protected by PAGE_WRITECOPY) SmartHandle dupHeapFileHandle(shParent, sfvMasterQForkControl->heapMemoryMapFile); g_pQForkControl->heapMemoryMapFile = dupHeapFileHandle; SmartHandle dupForkedProcessReady(shParent,sfvMasterQForkControl->forkedProcessReady); g_pQForkControl->forkedProcessReady = dupForkedProcessReady; SmartHandle dupStartOperation(shParent,sfvMasterQForkControl->startOperation); g_pQForkControl->startOperation = dupStartOperation; SmartHandle dupOperationComplete(shParent,sfvMasterQForkControl->operationComplete); g_pQForkControl->operationComplete = dupOperationComplete; SmartHandle dupOperationFailed(shParent,sfvMasterQForkControl->operationFailed); g_pQForkControl->operationFailed = dupOperationFailed; SmartHandle dupTerminateProcess(shParent,sfvMasterQForkControl->terminateForkedProcess); g_pQForkControl->terminateForkedProcess = dupTerminateProcess; // create section handle on MM file SIZE_T mmSize = g_pQForkControl->availableBlocksInHeap * cAllocationGranularity; SmartFileMapHandle sfmhMapFile( g_pQForkControl->heapMemoryMapFile, PAGE_WRITECOPY, HIDWORD(mmSize), LODWORD(mmSize), string("Could not open file mapping object in slave")); g_pQForkControl->heapMemoryMap = sfmhMapFile; // The key to mapping a heap larger than physical memory is to not map it all at once. SmartFileView<byte> sfvHeap( g_pQForkControl->heapMemoryMap, FILE_MAP_COPY, 0, 0, cAllocationGranularity, // Only map a portion of the heap . Deal with the unmapped pages with a VEH. g_pQForkControl->heapStart, string("Could not map heap in forked process. Is system swap file large enough?")); // setup DLMalloc global data if( SetDLMallocGlobalState(g_pQForkControl->DLMallocGlobalStateSize, g_pQForkControl->DLMallocGlobalState) != 0) { throw std::runtime_error("DLMalloc global state copy failed."); } // signal parent that we are ready SetEvent(g_pQForkControl->forkedProcessReady); // wait for parent to signal operation start WaitForSingleObject(g_pQForkControl->startOperation, INFINITE); // copy redis globals into fork process SetupGlobals(g_pQForkControl->globalData.globalData, g_pQForkControl->globalData.globalDataSize, g_pQForkControl->globalData.dictHashSeed); // execute requested operation if (g_pQForkControl->typeOfOperation == OperationType::otRDB) { do_rdbSave(g_pQForkControl->globalData.filename); } else if (g_pQForkControl->typeOfOperation == OperationType::otAOF) { do_aofSave(g_pQForkControl->globalData.filename); } else { throw runtime_error("unexpected operation type"); } // let parent know we are done SetEvent(g_pQForkControl->operationComplete); // parent will notify us when to quit WaitForSingleObject(g_pQForkControl->terminateForkedProcess, INFINITE); g_pQForkControl = NULL; return TRUE; } catch(std::system_error syserr) { printf("QForkSlaveInit: system error caught. error code=0x%08x, message=%s\n", syserr.code().value(), syserr.what()); g_pQForkControl = NULL; if(g_pQForkControl != NULL) { if(g_pQForkControl->operationFailed != NULL) { SetEvent(g_pQForkControl->operationFailed); } } return FALSE; } catch(std::runtime_error runerr) { printf("QForkSlaveInit: runtime error caught. message=%s\n", runerr.what()); g_pQForkControl = NULL; SetEvent(g_pQForkControl->operationFailed); return FALSE; } return FALSE; } BOOL QForkMasterInit( __int64 maxheapBytes ) { try { // allocate file map for qfork control so it can be passed to the forked process g_hQForkControlFileMap = CreateFileMappingW( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(QForkControl), NULL); if (g_hQForkControlFileMap == NULL) { throw std::system_error( GetLastError(), system_category(), "CreateFileMapping failed"); } g_pQForkControl = (QForkControl*)MapViewOfFile( g_hQForkControlFileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (g_pQForkControl == NULL) { throw std::system_error( GetLastError(), system_category(), "MapViewOfFile failed"); } // This must be called only once per process! Calling it more times than that will not recreate existing // section, and dlmalloc will ultimately fail with an access violation. Once is good. if (dlmallopt(M_GRANULARITY, cAllocationGranularity) == 0) { throw std::system_error( GetLastError(), system_category(), "DLMalloc failed initializing allocation granularity."); } g_pQForkControl->heapBlockSize = cAllocationGranularity; // ensure the number of blocks is a multiple of cAllocationGranularity SIZE_T allocationBlocks = maxheapBytes / cAllocationGranularity; allocationBlocks += ((maxheapBytes % cAllocationGranularity) != 0); g_pQForkControl->availableBlocksInHeap = (int)allocationBlocks; if (g_pQForkControl->availableBlocksInHeap <= 0) { throw std::runtime_error( "Invalid number of heap blocks."); } wchar_t heapMemoryMapPath[MAX_PATH]; swprintf_s( heapMemoryMapPath, MAX_PATH, L"%s_%d.dat", cMapFileBaseName, GetCurrentProcessId()); g_pQForkControl->heapMemoryMapFile = CreateFileW( heapMemoryMapPath, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL| FILE_FLAG_DELETE_ON_CLOSE, NULL ); if (g_pQForkControl->heapMemoryMapFile == INVALID_HANDLE_VALUE) { throw std::system_error( GetLastError(), system_category(), "CreateFileW failed."); } // There is a strange random failure toawrds the end of mapping the heap in the forked process in the VEH if // the underlying MMF is not larger than the MM space we are using. This seems to be some sort of // memory->file allocation granularity issue. Increasing the size of the file (by 16MB) takes care of the // issue in all cases. const size_t extraMMF = 64 * cAllocationGranularity; SIZE_T mmSize = g_pQForkControl->availableBlocksInHeap * cAllocationGranularity + extraMMF; g_pQForkControl->heapMemoryMap = CreateFileMappingW( g_pQForkControl->heapMemoryMapFile, NULL, PAGE_READWRITE, HIDWORD(mmSize), LODWORD(mmSize), NULL); if (g_pQForkControl->heapMemoryMap == NULL) { throw std::system_error( GetLastError(), system_category(), "CreateFileMapping failed."); } // Find a place in the virtual memory space where we can reserve space for our allocations that is likely // to be available in the forked process. (If this ever fails in the forked process, we will have to launch // the forked process and negotiate for a shared memory address here.) LPVOID pHigh = VirtualAllocEx( GetCurrentProcess(), NULL, mmSize, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE); if (pHigh == NULL) { throw std::system_error( GetLastError(), system_category(), "VirtualAllocEx failed."); } if (VirtualFree(pHigh, 0, MEM_RELEASE) == FALSE) { throw std::system_error( GetLastError(), system_category(), "VirtualFree failed."); } g_pQForkControl->heapStart = MapViewOfFileEx( g_pQForkControl->heapMemoryMap, FILE_MAP_ALL_ACCESS, 0,0, 0, pHigh); if (g_pQForkControl->heapStart == NULL) { throw std::system_error( GetLastError(), system_category(), "MapViewOfFileEx failed."); } for (int n = 0; n < cMaxBlocks; n++) { g_pQForkControl->heapBlockMap[n] = ((n < g_pQForkControl->availableBlocksInHeap) ? BlockState::bsUNMAPPED : BlockState::bsINVALID); } g_pQForkControl->typeOfOperation = OperationType::otINVALID; g_pQForkControl->forkedProcessReady = CreateEvent(NULL,TRUE,FALSE,NULL); if (g_pQForkControl->forkedProcessReady == NULL) { throw std::system_error( GetLastError(), system_category(), "CreateEvent failed."); } g_pQForkControl->startOperation = CreateEvent(NULL,TRUE,FALSE,NULL); if (g_pQForkControl->startOperation == NULL) { throw std::system_error( GetLastError(), system_category(), "CreateEvent failed."); } g_pQForkControl->operationComplete = CreateEvent(NULL,TRUE,FALSE,NULL); if (g_pQForkControl->operationComplete == NULL) { throw std::system_error( GetLastError(), system_category(), "CreateEvent failed."); } g_pQForkControl->operationFailed = CreateEvent(NULL,TRUE,FALSE,NULL); if (g_pQForkControl->operationFailed == NULL) { throw std::system_error( GetLastError(), system_category(), "CreateEvent failed."); } g_pQForkControl->terminateForkedProcess = CreateEvent(NULL,TRUE,FALSE,NULL); if (g_pQForkControl->terminateForkedProcess == NULL) { throw std::system_error( GetLastError(), system_category(), "CreateEvent failed."); } return TRUE; } catch(std::system_error syserr) { printf("QForkMasterInit: system error caught. error code=0x%08x, message=%s\n", syserr.code().value(), syserr.what()); } catch(std::runtime_error runerr) { printf("QForkMasterInit: runtime error caught. message=%s\n", runerr.what()); } catch(...) { printf("QForkMasterInit: other exception caught.\n"); } return FALSE; } LONG CALLBACK VectoredHeapMapper(PEXCEPTION_POINTERS info) { if( info->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION && info->ExceptionRecord->NumberParameters == 2) { intptr_t failingMemoryAddress = info->ExceptionRecord->ExceptionInformation[1]; intptr_t heapStart = (intptr_t)g_pQForkControl->heapStart; intptr_t heapEnd = heapStart + ((SIZE_T)g_pQForkControl->availableBlocksInHeap * g_pQForkControl->heapBlockSize); if( failingMemoryAddress >= heapStart && failingMemoryAddress <= heapEnd ) { intptr_t startOfMapping = failingMemoryAddress - failingMemoryAddress % g_systemAllocationGranularity; intptr_t mmfOffset = startOfMapping - heapStart; size_t bytesToMap = min( g_systemAllocationGranularity, heapEnd - startOfMapping); LPVOID pMapped = MapViewOfFileEx( g_pQForkControl->heapMemoryMap, FILE_MAP_COPY, HIDWORD(mmfOffset), LODWORD(mmfOffset), bytesToMap, (LPVOID)startOfMapping); if(pMapped != NULL) { return EXCEPTION_CONTINUE_EXECUTION; } else { printf("\nF(0x%p)", startOfMapping); printf( "\t MapViewOfFileEx failed with error 0x%08X. \n", GetLastError() ); printf( "\t heapStart 0x%p\n", heapStart); printf( "\t heapEnd 0x%p\n", heapEnd); printf( "\t failing access location 0x%p\n", failingMemoryAddress); printf( "\t offset into mmf to start mapping 0x%016X\n", mmfOffset); printf( "\t start of new mapping 0x%p \n", startOfMapping); printf( "\t bytes to map 0x%08x \n", bytesToMap); printf( "\t continuing exception handler search \n" ); } } } return EXCEPTION_CONTINUE_SEARCH; } // QFork API StartupStatus QForkStartup(int argc, char** argv) { bool foundSlaveFlag = false; HANDLE QForkConrolMemoryMapHandle = NULL; DWORD PPID = 0; __int64 maxheapBytes = -1; __int64 maxmemoryBytes = -1; int memtollerr = 0; SYSTEM_INFO si; GetSystemInfo(&si); g_systemAllocationGranularity = si.dwAllocationGranularity; if ((argc == 3) && (strcmp(argv[0], qforkFlag) == 0)) { // slave command line looks like: --QFork [QForkConrolMemoryMap handle] [parent process id] foundSlaveFlag = true; char* endPtr; QForkConrolMemoryMapHandle = (HANDLE)strtoul(argv[1],&endPtr,10); char* end = NULL; PPID = strtoul(argv[2], &end, 10); } else { for (int n = 1; n < argc; n++) { // check for flags in .conf file if( n == 1 && strncmp(argv[n],"--",2) != 0 ) { ifstream config; config.open(argv[n]); if (config.fail()) continue; while (!config.eof()) { string line; getline(config,line); istringstream iss(line); string token; if (getline(iss, token, ' ')) { if (_stricmp(token.c_str(), maxmemoryFlag) == 0) { string maxmemoryString; if (getline(iss, maxmemoryString, ' ')) { maxmemoryBytes = memtoll(maxmemoryString.c_str(),&memtollerr); if( memtollerr != 0) { printf ( "%s specified. Unable to convert %s to the number of bytes for the maxmemory flag.\n", maxmemoryBytes, argv[n+1] ); printf( "Failing startup.\n"); return StartupStatus::ssFAILED; } } } else if( _stricmp(token.c_str(), maxheapFlag) == 0 ) { string maxheapString; if (getline(iss, maxheapString, ' ')) { maxheapBytes = memtoll(maxheapString.c_str(),&memtollerr); if( memtollerr != 0) { printf ( "%s specified. Unable to convert %s to the number of bytes for the maxmemory flag.\n", maxmemoryBytes, argv[n+1] ); printf( "Failing startup.\n"); return StartupStatus::ssFAILED; } } } } } continue; } if( strncmp(argv[n],"--", 2) == 0) { if (_stricmp(argv[n]+2,maxmemoryFlag) == 0) { maxmemoryBytes = memtoll(argv[n+1],&memtollerr); if( memtollerr != 0) { printf ( "%s specified. Unable to convert %s to the number of bytes for the maxmemory flag.\n", maxmemoryBytes, argv[n+1] ); printf( "Failing startup.\n"); return StartupStatus::ssFAILED; } } else if(_stricmp(argv[n]+2,maxheapFlag) == 0) { maxheapBytes = memtoll(argv[n+1],&memtollerr); if( memtollerr != 0) { printf ( "%s specified. Unable to convert %s to the number of bytes for the maxmemory flag.\n", maxmemoryBytes, argv[n+1] ); printf( "Failing startup.\n"); return StartupStatus::ssFAILED; } } } } } PERFORMANCE_INFORMATION perfinfo; perfinfo.cb = sizeof(PERFORMANCE_INFORMATION); if (FALSE == GetPerformanceInfo(&perfinfo, sizeof(PERFORMANCE_INFORMATION))) { printf ( "GetPerformanceInfo failed.\n" ); printf( "Failing startup.\n" ); return StartupStatus::ssFAILED; } pageSize = perfinfo.PageSize; /* Not specifying the maxmemory or maxheap flags will result in the default behavior of: new key generation not bounded by heap usage, and the heap size equal to the size of physical memory. Redis will respect the maxmemory flag by preventing new key creation when the number of bytes allocated in the heap exceeds the level specified by the maxmemory flag. This does not account for heap fragmentation or memory usage by the heap allocator. To allow for this extra space maxheapBytes is implicitly set to (1.5 * maxmemory [rounded up to the nearest cAllocationGranularity boundary]). The maxheap flag may be specified along with the maxmemory flag to increase the heap further than this. If the maxmemory flag is not specified, but the maxheap flag is specified, the heap is sized according to this flag (rounded up to the nearest cAllocationGranularity boundary). The heap may be configured larger than physical memory with this flag. If maxmemory is sufficiently large enough, the heap will also be made larger than physical memory. This has implications for the system swap file size requirement and disk usage as discussed below. Specifying a heap larger than physical memory allows Redis to continue operating into virtual memory up to the limit of the heap size specified. Since the heap is entirely contained in the memory mapped file we are creating to share with the forked process, the size of the memory mapped file will be equal to the size of the heap. There must be sufficient disk space for this file. For instance, launching Redis on a server machine with 512GB of RAM and no flags specified for either maxmemory or maxheap will result in the allocation of a 512GB memory mapped file. Redis will fail to launch if there is not enough space available on the disk where redis is being launched from for this file. During forking the system swap file will be used for managing virtual memory sharing and the copy on write pages for both forker and forkee. There must be sufficient swap space availability for this. The maximum size of this swap space commit is roughly equal to (physical memory + (2 * size of the memory allocated in the redis heap)). For instance, if the heap is nearly maxed out on an 8GB machine and the heap has been configured to be twice the size of physical memory, the swap file comittment will be (physical + (2 * (2 * physical)) or (5 * physical). By default Windows will dynamically allocate a swap file that will expand up to about (3.5 * physical). In this case the forked process will fail with ERROR_COMMITMENT_LIMIT (1455/0x5AF) error. The fix for this is to ensure the system swap space is sufficiently large enough to handle this. The reason that the default heap size is equal to physical memory is so that Redis will work on a freshly configured OS without requireing reconfiguring either Redis or the machine (max comittment of (3 * physical)). */ int64_t maxMemoryPlusHalf = (3 * maxmemoryBytes) / 2; if( maxmemoryBytes != -1 ) { maxheapBytes = (maxheapBytes > maxMemoryPlusHalf) ? maxheapBytes : maxMemoryPlusHalf; } if( maxheapBytes == -1 ) { maxheapBytes = perfinfo.PhysicalTotal * pageSize; } if (foundSlaveFlag) { LPVOID exceptionHandler = AddVectoredExceptionHandler( 1, VectoredHeapMapper ); StartupStatus retVal = StartupStatus::ssFAILED; try { retVal = QForkSlaveInit( QForkConrolMemoryMapHandle, PPID ) ? StartupStatus::ssSLAVE_EXIT : StartupStatus::ssFAILED; } catch (...) { } RemoveVectoredExceptionHandler(exceptionHandler); return retVal; } else { return QForkMasterInit(maxheapBytes) ? StartupStatus::ssCONTINUE_AS_MASTER : StartupStatus::ssFAILED; } } BOOL QForkShutdown() { if(g_hForkedProcess != NULL) { TerminateProcess(g_hForkedProcess, -1); CloseHandle(g_hForkedProcess); g_hForkedProcess = NULL; } if( g_pQForkControl != NULL ) { if (g_pQForkControl->forkedProcessReady != NULL) { CloseHandle(g_pQForkControl->forkedProcessReady); g_pQForkControl->forkedProcessReady = NULL; } if (g_pQForkControl->startOperation != NULL) { CloseHandle(g_pQForkControl->startOperation); g_pQForkControl->startOperation = NULL; } if (g_pQForkControl->operationComplete != NULL) { CloseHandle(g_pQForkControl->operationComplete); g_pQForkControl->operationComplete = NULL; } if (g_pQForkControl->operationFailed != NULL) { CloseHandle(g_pQForkControl->operationFailed); g_pQForkControl->operationFailed = NULL; } if (g_pQForkControl->terminateForkedProcess != NULL) { CloseHandle(g_pQForkControl->terminateForkedProcess); g_pQForkControl->terminateForkedProcess = NULL; } if (g_pQForkControl->heapMemoryMap != NULL) { CloseHandle(g_pQForkControl->heapMemoryMap); g_pQForkControl->heapMemoryMap = NULL; } if (g_pQForkControl->heapMemoryMapFile != INVALID_HANDLE_VALUE) { CloseHandle(g_pQForkControl->heapMemoryMapFile); g_pQForkControl->heapMemoryMapFile = INVALID_HANDLE_VALUE; } if (g_pQForkControl->heapStart != NULL) { UnmapViewOfFile(g_pQForkControl->heapStart); g_pQForkControl->heapStart = NULL; } if(g_pQForkControl != NULL) { UnmapViewOfFile(g_pQForkControl); g_pQForkControl = NULL; } if (g_hQForkControlFileMap != NULL) { CloseHandle(g_hQForkControlFileMap); g_hQForkControlFileMap = NULL; }; } return TRUE; } BOOL BeginForkOperation(OperationType type, char* fileName, LPVOID globalData, int sizeOfGlobalData, DWORD* childPID, uint32_t dictHashSeed) { try { // copy operation data g_pQForkControl->typeOfOperation = type; strcpy_s(g_pQForkControl->globalData.filename, fileName); if (sizeOfGlobalData > MAX_GLOBAL_DATA) { throw std::runtime_error("Global state too large."); } memcpy(&(g_pQForkControl->globalData.globalData), globalData, sizeOfGlobalData); g_pQForkControl->globalData.globalDataSize = sizeOfGlobalData; g_pQForkControl->globalData.dictHashSeed = dictHashSeed; GetDLMallocGlobalState(&g_pQForkControl->DLMallocGlobalStateSize, NULL); if (g_pQForkControl->DLMallocGlobalStateSize > sizeof(g_pQForkControl->DLMallocGlobalState)) { throw std::runtime_error("DLMalloc global state too large."); } if(GetDLMallocGlobalState(&g_pQForkControl->DLMallocGlobalStateSize, g_pQForkControl->DLMallocGlobalState) != 0) { throw std::runtime_error("DLMalloc global state copy failed."); } // protect both the heap and the fork control map from propagating local changes DWORD oldProtect = 0; if (VirtualProtect(g_pQForkControl, sizeof(QForkControl), PAGE_WRITECOPY, &oldProtect) == FALSE) { throw std::system_error( GetLastError(), system_category(), "BeginForkOperation: VirtualProtect failed"); } if (VirtualProtect( g_pQForkControl->heapStart, g_pQForkControl->availableBlocksInHeap * g_pQForkControl->heapBlockSize, PAGE_WRITECOPY, &oldProtect) == FALSE ) { throw std::system_error( GetLastError(), system_category(), "BeginForkOperation: VirtualProtect failed"); } // ensure events are in the correst state if (ResetEvent(g_pQForkControl->operationComplete) == FALSE ) { throw std::system_error( GetLastError(), system_category(), "BeginForkOperation: ResetEvent() failed."); } if (ResetEvent(g_pQForkControl->operationFailed) == FALSE ) { throw std::system_error( GetLastError(), system_category(), "BeginForkOperation: ResetEvent() failed."); } if (ResetEvent(g_pQForkControl->startOperation) == FALSE ) { throw std::system_error( GetLastError(), system_category(), "BeginForkOperation: ResetEvent() failed."); } if (ResetEvent(g_pQForkControl->forkedProcessReady) == FALSE) { throw std::system_error( GetLastError(), system_category(), "BeginForkOperation: ResetEvent() failed."); } if (ResetEvent(g_pQForkControl->terminateForkedProcess) == FALSE) { throw std::system_error( GetLastError(), system_category(), "BeginForkOperation: ResetEvent() failed."); } // Launch the "forked" process char fileName[MAX_PATH]; if (0 == GetModuleFileNameA(NULL, fileName, MAX_PATH)) { throw system_error( GetLastError(), system_category(), "Failed to get module name."); } STARTUPINFOA si; memset(&si,0, sizeof(STARTUPINFOA)); si.cb = sizeof(STARTUPINFOA); char arguments[_MAX_PATH]; memset(arguments,0,_MAX_PATH); PROCESS_INFORMATION pi; sprintf_s(arguments, _MAX_PATH, "%s %ld %ld", qforkFlag, g_hQForkControlFileMap, GetCurrentProcessId()); if (FALSE == CreateProcessA(fileName, arguments, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { throw system_error( GetLastError(), system_category(), "Problem creating slave process" ); } (*childPID) = pi.dwProcessId; // wait for "forked" process to map memory if(WaitForSingleObject(g_pQForkControl->forkedProcessReady,10000) != WAIT_OBJECT_0) { throw system_error( GetLastError(), system_category(), "Forked Process did not respond in a timely manner."); } // signal the 2nd process that we want to do some work SetEvent(g_pQForkControl->startOperation); return TRUE; } catch(std::system_error syserr) { printf("BeginForkOperation: system error caught. error code=0x%08x, message=%s\n", syserr.code().value(), syserr.what()); } catch(std::runtime_error runerr) { printf("BeginForkOperation: runtime error caught. message=%s\n", runerr.what()); } catch(...) { printf("BeginForkOperation: other exception caught.\n"); } return FALSE; } OperationStatus GetForkOperationStatus() { if (WaitForSingleObject(g_pQForkControl->operationComplete, 0) == WAIT_OBJECT_0) { return OperationStatus::osCOMPLETE; } if (WaitForSingleObject(g_pQForkControl->operationFailed, 0) == WAIT_OBJECT_0) { return OperationStatus::osFAILED; } if (WaitForSingleObject(g_pQForkControl->forkedProcessReady, 0) == WAIT_OBJECT_0) { return OperationStatus::osINPROGRESS; } return OperationStatus::osUNSTARTED; } BOOL AbortForkOperation() { try { if( g_hForkedProcess != 0 ) { if (TerminateProcess(g_hForkedProcess, 1) == FALSE) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: Killing forked process failed."); } g_hForkedProcess = 0; } return EndForkOperation(); } catch(std::system_error syserr) { printf("0x%08x - %s\n", syserr.code().value(), syserr.what()); // If we can not properly restore fork state, then another fork operation is not possible. exit(1); } catch( ... ) { printf("Some other exception caught in EndForkOperation().\n"); exit(1); } return FALSE; } BOOL EndForkOperation() { try { SetEvent(g_pQForkControl->terminateForkedProcess); if( g_hForkedProcess != 0 ) { if (WaitForSingleObject(g_hForkedProcess, cDeadForkWait) == WAIT_TIMEOUT) { if (TerminateProcess(g_hForkedProcess, 1) == FALSE) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: Killing forked process failed."); } } CloseHandle(g_hForkedProcess); g_hForkedProcess = 0; } if (ResetEvent(g_pQForkControl->operationComplete) == FALSE ) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: ResetEvent() failed."); } if (ResetEvent(g_pQForkControl->operationFailed) == FALSE ) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: ResetEvent() failed."); } if (ResetEvent(g_pQForkControl->startOperation) == FALSE ) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: ResetEvent() failed."); } if (ResetEvent(g_pQForkControl->forkedProcessReady) == FALSE) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: ResetEvent() failed."); } if (ResetEvent(g_pQForkControl->terminateForkedProcess) == FALSE) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: ResetEvent() failed."); } // restore protection constants on shared memory blocks DWORD oldProtect = 0; if (VirtualProtect(g_pQForkControl, sizeof(QForkControl), PAGE_READWRITE, &oldProtect) == FALSE) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: VirtualProtect failed."); } if (VirtualProtect( g_pQForkControl->heapStart, g_pQForkControl->availableBlocksInHeap * g_pQForkControl->heapBlockSize, PAGE_READWRITE, &oldProtect) == FALSE ) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: VirtualProtect failed."); } // // What can be done to unify COW pages back into the section? // // 1. find the modified pages // 2. copy the modified pages into a buffer // 3. close the section map (discarding local changes) // 4. reopen the section map // 5. copy modified pages over reopened section map // // This assumes that the forked process is reasonably quick, such that this copy is not a huge burden. // typedef vector<INT_PTR> COWList; typedef COWList::iterator COWListIterator; COWList cowList; HANDLE hProcess = GetCurrentProcess(); size_t mmSize = g_pQForkControl->availableBlocksInHeap * g_pQForkControl->heapBlockSize; int pages = (int)(mmSize / pageSize); PSAPI_WORKING_SET_EX_INFORMATION* pwsi = new PSAPI_WORKING_SET_EX_INFORMATION[pages]; if (pwsi == NULL) { throw new system_error( GetLastError(), system_category(), "pwsi == NULL"); } memset(pwsi, 0, sizeof(PSAPI_WORKING_SET_EX_INFORMATION) * pages); int virtualLockFailures = 0; for (int page = 0; page < pages; page++) { pwsi[page].VirtualAddress = (BYTE*)g_pQForkControl->heapStart + page * pageSize; } if (QueryWorkingSetEx( hProcess, pwsi, sizeof(PSAPI_WORKING_SET_EX_INFORMATION) * pages) == FALSE) { throw system_error( GetLastError(), system_category(), "QueryWorkingSet failure"); } for (int page = 0; page < pages; page++) { if (pwsi[page].VirtualAttributes.Valid == 1) { // A 0 share count indicates a COW page if (pwsi[page].VirtualAttributes.ShareCount == 0) { cowList.push_back(page); } } } if (cowList.size() > 0) { LPBYTE cowBuffer = (LPBYTE)malloc(cowList.size() * pageSize); int bufPageIndex = 0; for (COWListIterator cli = cowList.begin(); cli != cowList.end(); cli++) { memcpy( cowBuffer + (bufPageIndex * pageSize), (BYTE*)g_pQForkControl->heapStart + ((*cli) * pageSize), pageSize); bufPageIndex++; } delete [] pwsi; pwsi = NULL; // discard local changes if (UnmapViewOfFile(g_pQForkControl->heapStart) == FALSE) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: UnmapViewOfFile failed."); } g_pQForkControl->heapStart = MapViewOfFileEx( g_pQForkControl->heapMemoryMap, FILE_MAP_ALL_ACCESS, 0,0, 0, g_pQForkControl->heapStart); if (g_pQForkControl->heapStart == NULL) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: Remapping ForkControl block failed."); } // copied back local changes to remapped view bufPageIndex = 0; for (COWListIterator cli = cowList.begin(); cli != cowList.end(); cli++) { memcpy( (BYTE*)g_pQForkControl->heapStart + ((*cli) * pageSize), cowBuffer + (bufPageIndex * pageSize), pageSize); bufPageIndex++; } delete cowBuffer; cowBuffer = NULL; } // now do the same with qfork control LPVOID controlCopy = malloc(sizeof(QForkControl)); if(controlCopy == NULL) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: allocation failed."); } memcpy(controlCopy, g_pQForkControl, sizeof(QForkControl)); if (UnmapViewOfFile(g_pQForkControl) == FALSE) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: UnmapViewOfFile failed."); } g_pQForkControl = (QForkControl*) MapViewOfFileEx( g_hQForkControlFileMap, FILE_MAP_ALL_ACCESS, 0,0, 0, g_pQForkControl); if (g_pQForkControl == NULL) { throw std::system_error( GetLastError(), system_category(), "EndForkOperation: Remapping ForkControl failed."); } memcpy(g_pQForkControl, controlCopy,sizeof(QForkControl)); delete controlCopy; controlCopy = NULL; return TRUE; } catch(std::system_error syserr) { printf("0x%08x - %s\n", syserr.code().value(), syserr.what()); // If we can not properly restore fork state, then another fork operation is not possible. exit(1); } catch( ... ) { printf("Some other exception caught in EndForkOperation().\n"); exit(1); } return FALSE; } int blocksMapped = 0; int totalAllocCalls = 0; int totalFreeCalls = 0; LPVOID AllocHeapBlock(size_t size, BOOL allocateHigh) { totalAllocCalls++; LPVOID retPtr = (LPVOID)NULL; if (size % g_pQForkControl->heapBlockSize != 0 ) { errno = EINVAL; return retPtr; } int contiguousBlocksToAllocate = (int)(size / g_pQForkControl->heapBlockSize); size_t mapped = 0; int startIndex = allocateHigh ? g_pQForkControl->availableBlocksInHeap - 1 : contiguousBlocksToAllocate - 1; int endIndex = allocateHigh ? -1 : g_pQForkControl->availableBlocksInHeap - contiguousBlocksToAllocate + 1; int direction = allocateHigh ? -1 : 1; int blockIndex = 0; int contiguousBlocksFound = 0; for(blockIndex = startIndex; blockIndex != endIndex; blockIndex += direction) { for (int n = 0; n < contiguousBlocksToAllocate; n++) { if (g_pQForkControl->heapBlockMap[blockIndex + n * direction] == BlockState::bsUNMAPPED) { contiguousBlocksFound++; } else { contiguousBlocksFound = 0; break; } } if (contiguousBlocksFound == contiguousBlocksToAllocate) { break; } } if (contiguousBlocksFound == contiguousBlocksToAllocate) { int allocationStart = blockIndex + (allocateHigh ? 1 - contiguousBlocksToAllocate : 0); LPVOID blockStart = reinterpret_cast<byte*>(g_pQForkControl->heapStart) + (g_pQForkControl->heapBlockSize * allocationStart); for(int n = 0; n < contiguousBlocksToAllocate; n++ ) { g_pQForkControl->heapBlockMap[allocationStart+n] = BlockState::bsMAPPED; blocksMapped++; mapped += g_pQForkControl->heapBlockSize; } retPtr = blockStart; } else { errno = ENOMEM; } return retPtr; } BOOL FreeHeapBlock(LPVOID block, size_t size) { totalFreeCalls++; if (size == 0) { return FALSE; } INT_PTR ptrDiff = reinterpret_cast<byte*>(block) - reinterpret_cast<byte*>(g_pQForkControl->heapStart); if (ptrDiff < 0 || (ptrDiff % g_pQForkControl->heapBlockSize) != 0) { return FALSE; } int blockIndex = (int)(ptrDiff / g_pQForkControl->heapBlockSize); if (blockIndex >= g_pQForkControl->availableBlocksInHeap) { return FALSE; } int contiguousBlocksToFree = (int)(size / g_pQForkControl->heapBlockSize); if (VirtualUnlock(block, size) == FALSE) { DWORD err = GetLastError(); if (err != ERROR_NOT_LOCKED) { return FALSE; } }; for (int n = 0; n < contiguousBlocksToFree; n++ ) { blocksMapped--; g_pQForkControl->heapBlockMap[blockIndex + n] = BlockState::bsUNMAPPED; } return TRUE; } extern "C" { // The external main() is redefined as redis_main() by Win32_QFork.h. // The CRT will call this replacement main() before the previous main() // is invoked so that the QFork allocator can be setup prior to anything // Redis will allocate. int main(int argc, char* argv[]) { #ifdef DEBUG_WITH_PROCMON hProcMonDevice = CreateFile( L"\\\\.\\Global\\ProcmonDebugLogger", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); #endif StartupStatus status = QForkStartup(argc, argv); if (status == ssCONTINUE_AS_MASTER) { int retval = redis_main(argc, argv); QForkShutdown(); return retval; } else if (status == ssSLAVE_EXIT) { // slave is done - clean up and exit QForkShutdown(); return 1; } else if (status == ssFAILED) { // master or slave failed initialization return 1; } else { // unexpected status return return 2; } } }
db #00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00 db #00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00 db #00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00 db #00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00 db #cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc db #cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc db #cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc db #cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc db #cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc db #cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc db #cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc db #cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc,#cc db #ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff db #ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff db #ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff db #ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff
; ; Initially include the zcc_opt.def file to find out lots of lovely ; information about what we should do.. ; IFNDEF CRT_ORG_CODE defc CRT_ORG_CODE = 40000 ENDIF defc TAR__clib_exit_stack_size = 32 defc TAR__register_sp = -1 INCLUDE "crt/classic/crt_rules.inc" org CRT_ORG_CODE ;---------------------- ; Execution starts here ;---------------------- start: ld (start1+1),sp INCLUDE "crt/classic/crt_init_sp.asm" INCLUDE "crt/classic/crt_init_atexit.asm" call crt0_init_bss ld (exitsp),sp ; Optional definition for auto MALLOC init ; it assumes we have free space between the end of ; the compiled program and the stack pointer IF DEFINED_USING_amalloc INCLUDE "crt/classic/crt_init_amalloc.asm" ENDIF ld ix,$CC ; Hide function key strings call msxbios call _main ld ix,$d2 ; TOTEXT - force text mode on exit call msxbios cleanup: IF CRT_ENABLE_STDIO = 1 EXTERN closeall call closeall ENDIF start1: ld sp,0 ret l_dcal: jp (hl) INCLUDE "crt/classic/crt_runtime_selection.asm" INCLUDE "crt/classic/crt_section.asm"
INCLUDE "hardware.inc" INCLUDE "header.inc" ;-------------------------------------------------------------------------- ;- RESTART VECTORS - ;-------------------------------------------------------------------------- SECTION "RST_00",HOME[$0000] ret ; Reserved for interrupt handler. If any interrupt vector is $0000 it jumps here and returns. SECTION "RST_08",HOME[$0008] jp hl ; Reserved for interrupt handler. (Or any other function that uses "call hl") SECTION "RST_10",HOME[$0010] ret SECTION "RST_18",HOME[$0018] ret SECTION "RST_20",HOME[$0020] ret SECTION "RST_28",HOME[$0028] ret SECTION "RST_30",HOME[$0030] ret SECTION "RST_38",HOME[$0038] ret ;-------------------------------------------------------------------------- ;- INTERRUPT VECTORS - ;-------------------------------------------------------------------------- SECTION "Interrupt Vectors",HOME[$0040] ; SECTION "VBL Interrupt Vector",HOME[$0040] push hl ld hl,_is_vbl_flag ld [hl],1 jr irq_VBlank ; SECTION "LCD Interrupt Vector",HOME[$0048] jp $FF80 nop nop nop nop nop ; SECTION "TIM Interrupt Vector",HOME[$0050] push hl ld hl,TIM_handler jr irq_Common nop nop ; SECTION "SIO Interrupt Vector",HOME[$0058] push hl ld hl,SIO_handler jr irq_Common nop nop ; SECTION "JOY Interrupt Vector",HOME[$0060] push hl ld hl,JOY_handler jr irq_Common ; nop ; nop ;-------------------------------------------------------------------------- ;- IRQS HANDLER - ;-------------------------------------------------------------------------- irq_VBlank: ld hl,VBL_handler irq_Common: push af ld a,[hl+] ld h,[hl] ld l,a ; If vector is $0000, it will jump there and return. Not needed to check here. push bc push de rst $08 ; call irq handler pop de pop bc pop af pop hl reti ;-------------------------------------------------------------------------- ;- wait_vbl() - ;-------------------------------------------------------------------------- wait_vbl: ld hl,_is_vbl_flag ld [hl],0 ._not_yet: halt bit 0,[hl] jr z,._not_yet ret ;-------------------------------------------------------------------------- ;- CARTRIDGE HEADER - ;-------------------------------------------------------------------------- SECTION "Cartridge Header",HOME[$0100] nop jp StartPoint DB $CE,$ED,$66,$66,$CC,$0D,$00,$0B,$03,$73,$00,$83,$00,$0C,$00,$0D DB $00,$08,$11,$1F,$88,$89,$00,$0E,$DC,$CC,$6E,$E6,$DD,$DD,$D9,$99 DB $BB,$BB,$67,$63,$6E,$0E,$EC,$CC,$DD,$DC,$99,$9F,$BB,$B9,$33,$3E ; 0123456789ABC DB "TESTING......" DW $0000 DB $00 ;GBC flag DB 0,0,0 ;SuperGameboy DB $1B ;CARTTYPE (MBC5+RAM+BATTERY) DB 0 ;ROMSIZE DB 2 ;RAMSIZE (8KB) DB $01 ;Destination (0 = Japan, 1 = Non Japan) DB $00 ;Manufacturer DB 0 ;Version DB 0 ;Complement check DW 0 ;Checksum ;-------------------------------------------------------------------------- ;- INITIALIZE THE GAMEBOY - ;-------------------------------------------------------------------------- SECTION "Program Start",HOME[$0150] StartPoint: di ld sp,$FFFE ; Use this as stack for a while push af ; Save CPU type push bc xor a,a ld [rNR52],a ; Switch off sound ld hl,_RAM ; Clear RAM ld bc,$2000 ld d,$00 call memset pop bc ; Get CPU type pop af ld [Init_Reg_A],a ; Save CPU type into RAM ld a,b ld [Init_Reg_B],a ld sp,StackTop ; Real stack call screen_off ld hl,_VRAM ; Clear VRAM ld bc,$2000 ld d,$00 call memset ld hl,_HRAM ; Clear high RAM (and rIE) ld bc,$0080 ld d,$00 call memset call init_OAM ; Copy OAM refresh function to high ram call refresh_OAM ; We filled RAM with $00, so this will clear OAM call rom_handler_init ; Real program starts here call Main ;Should never reach this point jp Reset ;-------------------------------------------------------------------------- ;- Reset() - ;-------------------------------------------------------------------------- Reset:: ld a,[Init_Reg_B] ld b,a ld a,[Init_Reg_A] jp $0100 ;-------------------------------------------------------------------------- ;- irq_set_VBL() bc = function pointer - ;- irq_set_LCD() bc = function pointer - ;- irq_set_TIM() bc = function pointer - ;- irq_set_SIO() bc = function pointer - ;- irq_set_JOY() bc = function pointer - ;-------------------------------------------------------------------------- irq_set_VBL:: ld hl,VBL_handler jr irq_set_handler irq_set_LCD:: ld hl,LCD_handler jr irq_set_handler irq_set_TIM:: ld hl,TIM_handler jr irq_set_handler irq_set_SIO:: ld hl,SIO_handler jr irq_set_handler irq_set_JOY:: ld hl,JOY_handler ; jr irq_set_handler irq_set_handler: ; hl = dest handler bc = function pointer ld [hl],c inc hl ld [hl],b ret ;-------------------------------------------------------------------------- ;- CPU_fast() - ;- CPU_slow() - ;-------------------------------------------------------------------------- CPU_fast:: ld a,[rKEY1] bit 7,a jr z,__CPU_switch ret CPU_slow:: ld a,[rKEY1] bit 7,a jr nz,__CPU_switch ret __CPU_switch: ld a,[rIE] ld b,a ; save IE xor a,a ld [rIE],a ld a,$30 ld [rP1],a ld a,$01 ld [rKEY1],a stop ld a,b ld [rIE],a ; restore IE ret ;-------------------------------------------------------------------------- ;- Variables - ;-------------------------------------------------------------------------- SECTION "StartupVars",BSS Init_Reg_A:: DS 1 Init_Reg_B:: DS 1 _is_vbl_flag: DS 1 VBL_handler: DS 2 LCD_handler: DS 2 TIM_handler: DS 2 SIO_handler: DS 2 JOY_handler: DS 2 SECTION "Stack",BSS[$CE00] Stack: DS $200 StackTop: ; $D000
; multi-segment executable file template. include emu8086.inc data segment ; add your data here! msg1 db 10,13,"please enter a string:$" str1 label byte max1 db 40 len1 db ? str1_1 db 40 dup('$') msg2 db 10,13,"reverse is:$" pkey db 10,13,"press any key...$" ends stack segment dw 128 dup(0) ends code segment start: ; set segment registers: mov ax, data mov ds, ax mov es, ax print_string msg1 read_string str1 toggle_case str1_1,len1 print_string msg2 print_string str1_1 print_string pkey read_key exit_program ends end start ; set entry point and stop the assembler.
; BOTH -- define different names for functions so that ; FORMAT.C and FORMATN.ASM can coexist. ; Native names are formed by appending "N" include w2.inc include noxport.inc include consts.inc include structs.inc ; NOTEXT equ 1 ; - don't include TextMetric struc & text drawing modes & stock objs. NORASTOPS equ 1 ; - don't include binary and ternary raster ops. NOVK equ 1 ; - don't include virtual key definitions NOMB equ 1 ; - don't include message box definitions NOWM equ 1 ; - don't include window messages include windows.inc .list createSeg _FORMAT,format,byte,public,CODE ; DEBUGGING DECLARATIONS ifdef DEBUG midFormatn2 equ 5 ; module ID, for native asserts NatPause equ 1 endif ifdef NatPause PAUSE MACRO int 3 ENDM else PAUSE MACRO ENDM endif cbszMax equ 30 ; EXTERNAL FUNCTIONS externFP <GetTextFace> externFP <FreeHandlesOfPfce> externFP <FReviveTossedPrinterDC> externFP <GetCharWidth> externFP <GetTextMetrics> ifdef HYBRID externFP <GetStockObjectPR> externFP <CreateFontIndirectPR> externFP <GetTextExtentPR> externFP <GlobalWirePR> externFP <GlobalUnlockPR> else ;!HYBRID externFP <GetStockObject> externFP <CreateFontIndirect> externFP <GetTextExtent> externFP <GlobalWire> externFP <GlobalUnlock> endif ;!HYBRID ifdef DEBUG externFP <SelectObjectFP> else ;!DEBUG ifdef HYBRID externFP <SelectObjectPR> else ;!HYBRID externFP <SelectObject> endif ;!HYBRID endif ;!DEBUG externFP <NMultDiv,FNeNcSz,CchSz,PpvAllocCb> externFP <N_IbstFindSzFfn,IbstAddStToSttb> externFP <PstFromSttb,N_PdodDoc,N_PdodMother> externFP <GetPhysicalFontHandle> externFP <GlobalFlags> externFP <FNeRgch> externNP <LN_NMultDiv> externFP <GenPrvwPlf> externFP <HqAllocLcb, LpLockHp, UnlockHp, ReloadSb> externFP <OurSetSas> externFP <SetErrorMatProc> ifdef DEBUG externFP <AssertProcForNative,ShakeHeapSb> externFP <CkFont,FreezeProc> externFP <S_ResetFont> externFP <ScribbleProc> externFP <CommSzNum,CommSzSz> externFP <LogGdiHandleProc> externFP <S_IbstFindSzFfn> endif ;DEBUG ; EXTERNAL DATA sBegin data externW vsab ; extern struct SAB vsab; externW vfli ; extern struct FLI vfli; externW vhsttbFont ; extern struct STTB **vhsttbFont; externW vfti ; extern struct FTI vfti; externW vftiDxt ; extern struct FTI vftiDxt; externW vflm ; extern int vflm; externW vpri ; extern struct PRI vpri; externW vmerr ; extern struct MERR vmerr; externW vlm ; extern int vlm; externW vfPrvwDisp ; extern int vfPrvwDisp; externW vsci ; extern struct SCI vsci; externW wwMac ; extern int wwMac; externW mpwwhwwd ; extern struct WWD **mpwwhwwd[]; externW vpref ; extern struct PREF vpref; externW rgfce ; extern struct FCE rgfce[ifceMax]; externW mpsbps ; extern SB mpsbps[]; externW vsasCur ; extern int vsasCur; ifdef DEBUG externW cHpFreeze externW vdbs externW vhgdis ; extern int vhgdis; endif sEnd data ; CODE SEGMENT _FORMAT sBegin format assumes cs,format assumes ds,dgroup assumes ss,dgroup ; /* D X U E X P A N D */ ; /* returns the character expansion number in dxuInch units */ ; native int DxuExpand(pchp, dxuInch) ; struct CHP *pchp; ; int dxuInch; ;LN_DxuExpand takes dxuInch in dx, pchp in di ;ax, bx, cx, dx are altered. ; %%Function:LN_DxuExpand %%Owner:BRADV PUBLIC LN_DxuExpand LN_DxuExpand: ; { ; int qps; ; ; if ((qps = pchp->qpsSpace) == 0 || pchp->fSpec) return 0; mov al,[di.qpsSpaceChp] errnz <maskQpsSpaceChp - 03Fh> and al,maskQpsSpaceChp jz DE04 test [di.fSpecChp],maskFSpecChp jnz DE04 ; /* qps is encoded to be in the range [-7, 56] */ ; if (qps > 56) qps -= 64; cmp al,56 jle DE01 sub al,64 DE01: cbw ; /* 4 (quarter) * 72 (points per inch) */ ; return NMultDiv(qps, dxuInch, 72 * 4); ; LN_NMultDiv performs NMultDiv(ax, dx, bx) ; ax, bx, cx, dx are altered. mov bx,288 call LN_NMultDiv db 03Dh ;turns next "xor ax,ax" into "cmp ax,immediate" DE04: xor ax,ax ;} ret ;------------------------------------------------------------------------- ; LoadFont( pchp,fWidthsOnly ) ;------------------------------------------------------------------------- ; %%Function:N_Loadfont %%Owner:BRADV cProc N_LoadFont,<PUBLIC,FAR>,<si,di> ParmW pchp ParmW fWidthsOnly ; /* LoadFont( pchp, fWidthsOnly ) ; * ; * Description: LoadFont loads the font specified by pchp into appropriate ; * DC's ; */ ; ; native LoadFont( pchp, fWidthsOnly ) ; struct CHP *pchp; ; int fWidthsOnly; ; { ; union FCID fcid; localV fcid, cbFcid ; struct DOD *pdod; ; cBegin ; Assert( vfli.doc != docNil ); ifdef DEBUG cmp [vfli.docFli],docNil jne LFnt01 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,800 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LFnt01: ; Assert( pchp != NULL); cmp [pchp],NULL jne LFnt02 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,801 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LFnt02: endif ;DEBUG ; ; /* Map font requests in short DOD back through parent DOD */ ; pdod = PdodMother(vfli.doc); cCall N_PdodMother,<[vfli.docFli]> xchg si,ax ; if (vfli.doc == docUndo) ; pdod = PdodDoc(PdodDoc(docUndo)->doc); mov ax,[vfli.docFli] cmp ax,docUndo jne LFnt025 cCall N_PdodDoc,<ax> xchg si,ax cCall N_PdodDoc,<[si.docDod]> xchg si,ax jmp LFnt03 ; /* font table was not actually copied to scrap, so map request back to ; data provider doc, just like MapStc does for styles */ ; else if (pdod == PdodDoc(docScrap) && vsab.docStsh != docNil) ; pdod = PdodDoc(vsab.docStsh); LFnt025: mov ax,docScrap cCall N_PdodDoc,<ax> cmp ax,si jnz LFnt03 mov cx,[vsab.docStshSab] jcxz LFnt03 cCall N_PdodDoc,<cx> xchg ax,si LFnt03: ; ; si = pdod ; /* Translate chp --> fcid */ ; fcid.lFcid = 0L; ; fcid.fItalic = pchp->fItalic; ; fcid.fBold = pchp->fBold; ; fcid.fStrike = pchp->fStrike; ; fcid.kul = pchp->kul; ; fcid.hps = pchp->hps; ;/* protect against out-of-range ftcs in case of bogus doc or ; failed ApplyGrpprlCa during font merge after interdoc paste */ ; fcid.ibstFont = (**pdod->hmpftcibstFont) [min( pchp->ftc, pdod->ftcMac-1)]; mov di,[pchp] ; di = pchp errnz <(fBoldChp) - 0> errnz <maskFBoldChp - 001h> errnz <(fBoldFcid) - 0> errnz <maskFBoldFcid - 001h> errnz <(fItalicChp) - 0> errnz <maskFItalicChp - 002h> errnz <(fItalicFcid) - 0> errnz <maskFItalicFcid - 002h> errnz <(fStrikeChp) - 0> errnz <maskFStrikeChp - 004h> errnz <(fStrikeFcid) - 0> errnz <maskFStrikeFcid - 004h> errnz <maskKulChp - 070h> errnz <(kulFcid) - 0> errnz <maskKulFcid - 038h> errnz <(hpsFcid) - 1> errnz <(ibstFontFcid) - 2> mov al,[di.fBoldChp] mov ah,[di.kulChp] and ax,maskFItalicFcid+maskFBoldFcid+maskFStrikeFcid+(maskKulChp SHL 8) shr ah,1 or al,ah mov ah,[di.hpsChp] mov wptr ([fcid.fBoldFcid]),ax mov ax,[si.ftcMacDod] dec ax mov si,[si.hmpftcibstFontDod] mov si,[si] cmp [di.ftcChp],ax ja Lfnt04 mov ax,[di.ftcChp] LFnt04: add si,ax lodsb xor ah,ah mov wptr ([fcid.ibstFontFcid]),ax ; vfti.dxpExpanded = vftiDxt.dxpExpanded = 0; xor ax,ax mov [vfti.dxpExpandedFti],ax mov [vftiDxt.dxpExpandedFti],ax ; if (vfli.fFormatAsPrint) lea bx,[fcid] ;default assume vfli.fFormatAsPrint is fFalse errnz <fFalse - 0> cmp [vfli.fFormatAsPrintFli],al jz LFnt08 ; { /* Two-device case: Displaying; formatting for printer */ ; /* First determine what font we can get for the printer */ ; LoadFcid( fcid, &vftiDxt, fTrue ); lea ax,[vftiDxt] push [fcid.HI_lFcid] push [fcid.LO_lFcid] push ax push ax push cs call near ptr N_LoadFcid ; if (pchp->qpsSpace != 0) ; vftiDxt.dxpExpanded = DxuExpand(pchp,vftiDxt.dxpInch); ; di = pchp test [di.qpsSpaceChp],maskQpsSpaceChp jz LFnt06 mov dx,[vftiDxt.dxpInchFti] ;LN_DxuExpand takes dxuInch in dx, pchp in di ;ax, bx, cx, dx are altered. call LN_DxuExpand mov [vftiDxt.dxpExpandedFti],ax LFnt06: ; ; /* Then request a screen font based on what we got back */ ; LoadFcid( vftiDxt.fcid, &vfti, fWidthsOnly ); mov bx,dataoffset [vftiDxt.fcidFti] ; } ; else ; { /* One-device case: 1. Printing ; 2. Displaying; formatting for screen */ ; LoadFcid( fcid, &vfti, fWidthsOnly ); LFnt08: lea ax,[vfti] push [bx.HI_lFcid] push [bx.LO_lFcid] push ax push [fWidthsOnly] push cs call near ptr N_LoadFcid ; } ; di = pchp test [di.qpsSpaceChp],maskQpsSpaceChp jz LFnt09 mov dx,[vfti.dxpInchFti] ;LN_DxuExpand takes dxuInch in dx, pchp in di ;ax, bx, cx, dx are altered. call LN_DxuExpand mov [vfti.dxpExpandedFti],ax LFnt09: ; } cEnd ;------------------------------------------------------------------------- ; LoadFcidFull( fcid ) ;------------------------------------------------------------------------- ;NATIVE LoadFcidFull( fcid ) ;union FCID fcid; ; { ; LoadFcid( fcid, &vfti, fFalse /* fWidthsOnly */); ; } ; %%Function:N_LoadFcidFull %%Owner:BRADV cProc N_LoadFcidFull,<PUBLIC,FAR>,<si,di> ParmD fcid cBegin mov dx,[SEG_fcid] mov ax,[OFF_fcid] mov bx,dataoffset [vfti] errnz <fFalse> xor cx,cx push dx push ax push bx push cx push cs call near ptr N_LoadFcid cEnd ;------------------------------------------------------------------------- ; LoadFcid( fcid, pfti, fWidthsOnly ) ;------------------------------------------------------------------------- ; %%Function:N_LoadFcid cProc N_LoadFcid,<PUBLIC,FAR>,<si,di> ParmD fcid ParmW pfti ParmW fWidthsOnly ; /* LoadFcid( fcid, pfti, fWidthsOnly ) ; * ; * Description: ; * ; * Loads a font described by fcid. ; * ; * Inputs: ; * fcid - a long describing the font ; * pfti - pointer to fti structure to fill out ; * ; * Outputs: ; * ; * *pfti is filled out with a description of the font actually realized for ; * the request. Note that it is frequently true that pfti->fcid != fcid passed ; * ; * Methods: ; * ; * The last ifceMax fonts requested through LoadFcid are kept in a LRU cache, ; * such that the descriptive information, width tables, and mapping from ; * requested to actual font are kept around for quick access. ; * ; * The fonts that are cached for the device described in *pfti are ; * kept on a chain extending from pfti->pfce. ; * ; * If a font is currently selected into the device, then pfti->hfont ; * will be non-null and pfti->fcid will describe the font. ; * ; * The fcid acts as the key field in looking up a font. FCID is structured ; * so that the first word, wProps, contains those fields considered most ; * likely to vary. ; * ; */ ; ; native LoadFcid( fcid, pfti, fWidthsOnly ) ; union FCID fcid; ; struct FTI *pfti; ; int fWidthsOnly; ; { ; extern int vflm; ; int dyp; ; struct FCE *pfce; ; struct FCE *pfceHead; ; int fFallback; ; LOGFONT lf; ; TEXTMETRIC tm; ; int dxp; ; HDC hdc; ; char *pdxp; ; int dxp; ; int ch; /* MUST be int so chDxpMax == 256 will work */ ; union FCID fcidActual; ; CHAR rgb [cbFfnLast]; ; struct FFN *pffn = (struct FFN *) &rgb [0]; ; localW dyp localV lf, cbLogfontMin localV tm, <SIZE TEXTMETRIC> localW dxp localW hdc localW pdxp localW ch1 localV rgb,cbFfnLast localW hfontT localW fFallback ifdef DEBUG localV szD, cbszMax endif cBegin ; Assert( vflm != flmIdle ); ifdef DEBUG ;Assert (vflm != flmIdle) with a call so as not ;to mess up short jumps. call LF40 endif ;DEBUG ; ; /* CASE 1: No fonts cached for this device */ ; ; if ((pfce = pfti->pfce) == NULL) mov di,[pfti] ; di = pfti mov si,[di.pfceFti] ; si = pfce errnz <NULL> or si,si ; { ; goto LNewFce; je Ltemp002 ; } ; /* CASE 2: There is a font already selected in, and it matches the request */ mov ax,[fcid.wPropsFcid] mov dx,[fcid.wExtraFcid] ; if (pfti->hfont != NULL) ; { cmp [di.hFontFti],NULL je LF06 ; if (fcid.wProps == pfce->fcidRequest.wProps && ; fcid.wExtra == pfce->fcidRequest.wExtra) ; { cmp ax,[si.fcidRequestFce.wPropsFcid] jne LF03 cmp dx,[si.fcidRequestFce.wExtraFcid] jne LF03 ; vfli.fGraphics |= pfce->fGraphics; ; return; test [si.fGraphicsFce],maskfGraphicsFce je LF02 or [vfli.fGraphicsFli],maskFGraphicsFli LF02: jmp LF37 ; } LF03: ; ; pfce = pfce->pfceNext; /* start following search with 2nd font in chain */ mov si,[si.pfceNextFce] ; } LF04: jmp short LF06 Ltemp002: jmp short LNewFce ;Assembler note: this line has been moved from the bottom of the ;while loop LF05: ; pfce = pfce->pfceNext; mov si,[si.pfceNextFce] ; /* CASE 3: Font request matches some cached request for this device */ ; while (pfce != NULL) ; { LF06: errnz <NULL> or si,si je LF10 ; if (pfce->fcidRequest.wProps == fcid.wProps && ; pfce->fcidRequest.wExtra == fcid.wExtra) ; { cmp ax,[si.fcidRequestFce.wPropsFcid] jne LF05 cmp dx,[si.fcidRequestFce.wExtraFcid] jne LF05 ; Assert( pfce->hfont != NULL ); ifdef DEBUG ;Assert (pfce->hfont != NULL) with a call so as not ;to mess up short jumps. call LF42 endif ;DEBUG ; if (vfPrvwDisp && !pfce->fPrvw || !vfPrvwDisp && pfce->fPrvw) ; goto LNextFce; /* Assembler Note: LF05 */ mov bl,[si.fPrvwFce] mov cx,[vfPrvwDisp] jcxz LF063 xor bl,maskfPrvwFce LF063: and bl,maskfPrvwFce jne LF05 ; /* Remove the FCE from its present position in its chain */ ; if (pfce == pfti->pfce) ; { cmp si,[di.pfceFti] jne LF07 ; pfti->pfce = pfce->pfceNext; mov cx,[si.pfceNextFce] mov [di.pfceFti],cx ; } jmp short LF08 ; else ; { LF07: ; Assert( pfce->pfcePrev != NULL ); ifdef DEBUG ;Assert (pfce->pfcePrev != NULL) with a call so as not ;to mess up short jumps. call LF44 endif ;DEBUG ; if ((pfce->pfcePrev->pfceNext = pfce->pfceNext) != 0) mov cx,[si.pfceNextFce] mov bx,[si.pfcePrevFce] mov [bx.pfceNextFce],cx jcxz LF08 ; pfce->pfceNext->pfcePrev = pfce->pfcePrev; push bx mov bx,[si.pfceNextFce] pop [bx.pfcePrevFce] ; } LF08: ; /* Optimization: don't actually select in the font if we know ; its width and we're just formatting so that's all we need */ ; if (fWidthsOnly) cmp [fWidthsOnly],fFalse jz LF09 ; pfti->hfont = NULL; mov [di.hFontFti],NULL Ltemp003: jmp LLoadFce LF09: ; else if (pfce->hfont == hfontSpecNil) ; goto LValidateFce; mov ax,[si.hfontFce] cmp ax,hfontSpecNil je LValidateFce ; else if (hfontT = pfce->hfont, ; !FSelectFont( pfti, &hfontT, &hdc)) ; { ;/* font could not be selected so system font was selected in its place */ mov [hfontT],ax push di ;save pfti push si ;save pfce mov bx,di lea si,[hfontT] lea di,[hdc] ;LN_FNotSelectFont takes pfti in bx, phfont in si, phdc in di ;ax, bx, cx, dx, si, di are altered. call LN_FNotSelectFont pop si ;restore pfce pop di ;restore pfti or ax,ax je Ltemp003 ; FreeHandlesOfPfce(pfce); ; goto LSystemFontErr; ; } cCall FreeHandlesOfPfce,<si> jmp LSystemFontErr ; goto LLoadFce; ; } ;Assembler note: this code has been moved to before the while loop. ; pfce = pfce->pfceNext; ; } LF10: ; ; /* CASE 4: No FCE in table for requested font, must build one */ ; ; LNewFce: LNewFce: ; ; /* Get a free FCE slot in which to build new entry */ ; pfce = PfceLruGet(); /* Kicks out LRU font, if no unallocated FCE slots exist */ push di ;save pfti ;LN_PfceLruGet returns its result in si. ;ax, bx, cx, dx, si, di are altered. call LN_PfceLruGet pop di ;restore pfti LValidateFce: ; pfce->fPrvwFce = vfPrvwDisp; and [si.fPrvwFce],NOT maskfPrvwFce cmp [vfPrvwDisp],fFalse je LF105 or [si.fPrvwFce],maskfPrvwFce LF105: ; fFallback = fFalse; ; pfce->fPrinter = pfti->fPrinter; ; pfce->fGraphics = fTrue; /* the safer assumption in case of failure */ mov bptr ([fFallback]),fFalse mov al,[di.fPrinterFti] and al,maskfPrinterFti errnz <(fGraphicsFce) - (fPrinterFce)> or al,maskfGraphicsFce errnz <maskFPrinterFti - maskFPrinterFce> and [si.fPrinterFce],NOT maskfPrinterFti or [si.fPrinterFce],al ; pfce->fcidRequest = fcid; mov ax,[fcid.LO_lFcid] mov dx,[fcid.HI_lFcid] mov [si.LO_fcidRequestFce],ax mov [si.HI_fcidRequestFce],dx ; if (pfti->fTossedPrinterDC) ; { test [di.fTossedPrinterDCFti],maskfTossedPrinterDCFti jz LF11 ; Assert( pfti->fPrinter ); ; Assert( fWidthsOnly ); ifdef DEBUG ;Assert (pfti->fPrinter && fWidthsOnly) with a call so as not ;to mess up short jumps. call LF46 endif ;DEBUG ; /* up till now, we have cheated -- we don't really have a printer DC, ; but we have been able to manage without it since our cache is filled ; with font widths. Now comes the time to pay the piper. ; Create a printer IC. */ ; if (!FReviveTossedPrinterDC(pfce)) ; goto LLoadFce; cCall FReviveTossedPrinterDC,<si> or ax,ax jnz LF11 jmp LLoadFce ; } ; } LF11: ; /* Translate FCID request to a logical font */ ; if (fcid.ibstFont == ibstFontNil || (!pfti->fPrinter && vpref.fDraftView)) /* ibstFontNil means use system font */ ; goto LSystemFont; cmp [fcid.ibstFontFcid],ibstFontNil je LSystemFont test [di.fPrinterFti],maskfPrinterFti jnz LF113 test [vpref.fDraftViewPref],maskfDraftViewPref jnz LSystemFont LF113: ; pfce->fGraphics = FGraphicsFcidToPlf( fcid, &lf, pfce->fPrinter ); push si push di mov cl,[si.fPrinterFce] and cx,maskfPrinterFce mov dx,[fcid.HI_lFcid] mov ax,[fcid.LO_lFcid] lea di,[lf] ;LN_FGraphicsFcidToPlf takes fcid in dx:ax, plf in di, fPrinterFont in cx ;ax, bx, cx, dx, si, di are altered. ; returns pffn->fGraphics in maskfGraphicsFfn bit of al call LN_FGraphicsFcidToPlf pop di pop si ; restore pfce errnz <maskfGraphicsFce-maskfGraphicsFfn> and [si.fGraphicsFce],al ; /* Call Windows to request the font */ ; if ((pfce->hfont = CreateFontIndirect( (LPLOGFONT)&lf )) == NULL) ; { lea ax,[lf] push ss push ax ifdef HYBRID cCall CreateFontIndirectPR,<> else ;!HYBRID cCall CreateFontIndirect,<> endif ;!HYBRID mov [si.hfontFce],ax errnz <NULL> or ax,ax jne LF13 ; LSystemFontErr: LSystemFontErr: ; SetErrorMat(matFont); ; fFallback = fTrue; call LN_SetErrorMat mov bptr ([fFallback]),fTrue ; LSystemFont: LSystemFont: ; pfce->hfont = GetStockObject( pfti->fPrinter ? ; DEVICEDEFAULT_FONT : SYSTEM_FONT ); mov ax,DEVICEDEFAULT_FONT test [di.fPrinterFti],maskfPrinterFti jnz LF12 errnz <DEVICEDEFAULT_FONT - SYSTEM_FONT - 1> dec ax LF12: push ax ifdef HYBRID cCall GetStockObjectPR,<> else ;!HYBRID cCall GetStockObject,<> endif ;!HYBRID mov [si.hfontFce],ax ; } LF13: ;LogGdiHandle(pfce->hfont, 10000); ;#define LogGdiHandle(hGdi,wId) (vhgdis ? LogGdiHandleProc(hGdi,wId) : 0) ifdef DEBUG ;Do this DEBUG stuff with a call so as not ;to mess up short jumps. call LF59 endif ;DEBUG ; /* Now fill out the FCE entry with the attributes of the new font */ ; /* A false return from FSelectFont means we got the system font instead, ; but we don't care here */ ; FSelectFont( pfti, &pfce->hfont, &hdc ); push di ;save pfti push si ;save pfce mov bx,di add si,(hfontFce) lea di,[hdc] ;LN_FNotSelectFont takes pfti in bx, phfont in si, phdc in di ;ax, bx, cx, dx, si, di are altered. call LN_FNotSelectFont pop si ;restore pfce pop di ;restore pfti ; LNewMetrics: LNewMetrics: ; Assert( hdc != NULL ); ifdef DEBUG ;Assert (hdc != NULL) with a call so as not ;to mess up short jumps. call LF53 endif ;DEBUG ; GetTextMetrics( hdc, (LPTEXTMETRIC) &tm ); push [hdc] lea ax,[tm] push ds push ax cCall GetTextMetrics,<> mov bx,di ;save pfti push si ;save pfce push ss pop es lea di,[si.dxpOverhangFce] lea si,[tm.tmAscent] ; pfce->dxpOverhang = tm.tmOverhang; mov ax,[tm.tmOverhang] stosw ; pfce->dypAscent = tm.tmAscent; errnz <(dypAscentFce) - (dxpOverhangFce) - 2> movsw ; pfce->dypDescent = tm.tmDescent; errnz <(dypDescentFce) - (dypAscentFce) - 2> errnz <(tmDescent) - (tmAscent) - 2> lodsw stosw ; pfce->dypXtraAscent = tm.tmAscent; ; if (pfti->fPrinter) ; pfce->dypXtraAscent += tm.tmExternalLeading; mov ax,[tm.tmAscent] test [bx.fPrinterFti],maskfPrinterFti jz LF14 add ax,[tm.tmExtLeading] LF14: errnz <(dypXtraAscentFce) - (dypDescentFce) - 2> stosw pop si ;restore pfce mov di,bx ;restore pfti ; /* Initialize the width table. */ ; Debug( vdbs.fShakeHeap ? ShakeHeap() : 0 ); ifdef DEBUG call LN_ShakeHeap endif ;DEBUG ; pfce->fFixedPitch = fTrue; ; pfce->dxpWidth = tm.tmAveCharWidth; ; pfce->fVisiBad = fFalse; and [si.fVisiBadFce],NOT maskfVisiBadFce or [si.fFixedPitchFce],maskfFixedPitchFce mov ax,[tm.tmAveCharWidth] mov [si.dxpWidthFce],ax ; if ((tm.tmPitchAndFamily & maskFVarPitchTM) && !fFallback) ; { test [tm.tmPitch],maskFVarPitchTM je Ltemp007 cmp bptr ([fFallBack]),fFalse jne Ltemp007 ; int ch; /* MUST be int so chDxpMax == 256 will work */ ; int *pdxp; ; int dxp; LF15: ; if ((pfce->hqrgdxp = HqAllocLcb( (long)((chDxpMax - chDxpMin ) << 1))) == hqNil) ;/* lose track of logical font & hqrgdxp, but that's tolerable */ ; goto LSystemFontErr; mov ax,(chDxpMax-chDxpMin) SHL 1 cwd cCall HqAllocLcb, <dx,ax> mov [si.LO_hqrgdxpFce], ax mov [si.HI_hqrgdxpFce], dx mov cx,ax or cx,dx jnz Ltemp005 Ltemp006: jmp LSystemFontErr Ltemp007: jmp LF21 Ltemp005: ; lpdxp = LpLockHq( pfce->hqrgdxp ); ; dx:ax = hqrgdxp, si = pfce, di = pfti mov di,ax mov bx,dx shl bx,1 mov ax,mpsbps [bx] mov es,ax shr ax,1 jc LF152 ; ReloadSb requires: ; bx = sb * 2 ; ax = mpsbps [sb]/2 ; returns es = physical address of seg ; ; reload sb trashes ax, cx, and dx cCall ReloadSb,<> LF152: mov di,es:[di] mov ax,[si.HI_hqrgdxpFce] push ax ; save hp for later unlock push di cCall LpLockHp,<ax,di> xchg ax,di ;/* WINDOWS BUG WORKAROUND (DAVIDBO): GetCharWidth RIPs on any mapping mode ; other than MM_TEXT ; if (vfPrvwDisp) ; OurGetCharWidth(hdc, chDxpMin, chDxpMax - 2, lpdxp); ;/* DRIVER BUG WORKAROUND (BL): Don't ask for n-255 or the EPSON24 and ; several other raster printer drivers will crash when you ask for widths */ ; else if (!GetCharWidth( hdc, chDxpMin, chDxpMax - 2, lpdxp )) ; OurGetCharWidth( hdc, chDxpMin, chDxpMax - 2, lpdxp ); ; OurGetCharWidth( hdc, chDxpMax - 1, chDxpMax - 1, &lpdxp [chDxpMax-1] ); ; si = pfce, dx:di = lpdxp, hp is pushed push di ;save low lpdxp push dx ;save high lpdxp errnz <chDxpMin - 0> xor cx,cx mov ax,chDxpMax-2 errnz <fFalse> cmp [vfPrvwDisp],cx jne LF157 push [hdc] push cx push ax push dx push di cCall GetCharWidth,<> xchg ax,cx LF157: pop es ;restore high lpdxp errnz <chDxpMin - 0> jcxz LF158 mov cx,chDxpMax-1 add di,(chDxpMax-1) SHL 1 LF158: ;***Begin in line OurGetCharWidth ;HANDNATIVE void OurGetCharWidth( hdc, chFirst, chLast, lpdxp ) ;HDC hdc; ;int chFirst, chLast; ;int far *lpdxp; ;{ ; Assert( hdc != NULL ); ; Assert( chFirst >= 0 && chLast <= 255 ); ; ; while (chFirst <= chLast) ; { ; *lpdxp++ = GetTextExtent( hdc, &chFirst, 1 ); ; chFirst++; ; } ;} push es ;save high lpdxp push cx ;get chFirst into memory mov bx,sp ;address of chFirst mov ax,1 push [hdc] push ds push bx push ax ifdef HYBRID cCall GetTextExtentPR,<> else ;!HYBRID cCall GetTextExtent,<> endif ;!HYBRID pop cx ;restore chFirst pop es ;restore high lpdxp stosw inc cx cmp cx,chDxpMax jb LF158 ;***End in line OurGetCharWidth pop di ;restore low lpdxp ; if (pfce->dxpOverhang) ; { ; lpdxpMin = lpdxp; ; lpdxpT = lpdxpMin + (chDxpMax - chDxpMin - 1); ; while (lpdxpT >= lpdxpMin) ; { ; *lpdxpT-- -= pfce->dxpOverhang; ; } ; } ; pfce->fFixedPitch = fFalse; ; pfce->fVisiBad = (lpdxp [chSpace] != lpdxp [chVisSpace]); ; es:di = lpdxp, hp is pushed, then pfce and [si.fFixedPitchFce],NOT maskfFixedPitchFce mov ax,es:[di+(chSpace SHL 1)] cmp ax,es:[di+(chVisSpace SHL 1)] je LF16 or [si.fVisiBadFce],maskfVisiBadFce ; bit was cleared above LF16: mov ax,[si.dxpOverhangFce] or ax,ax jz LF18 mov cx,(chDxpMax - chDxpMin) LF19: sub es:[di],ax inc di inc di loop LF19 LF18: ; UnlockHq( pfce->hqrgdxp ); ; } ;#define UnlockHq(hq) UnlockHp(HpOfHq(hq)) ; si = pfce, hp is pushed cCall UnlockHp,<> push ds pop es mov di,[pfti] LF21: ; ; /* Now built fcidActual according to the properties of the font we got */ ; /* We only care about fcidActual for printer fonts */ ; ; if (pfti->fPrinter) ; { test [di.fPrinterFti],maskfPrinterFti jnz Ltemp004 jmp LF31 Ltemp004: push di ;save pfti ; union FCID fcidActual; ; CHAR rgb [cbFfnLast]; ; struct FFN *pffn = (struct FFN *) &rgb [0]; lea di,[rgb] ; ; fcidActual.lFcid = 0L; ; ; /* Store back the real height we got */ ; ; fcidActual.hps = umin( 0xFF, ; (NMultDiv( tm.tmHeight - tm.tmInternalLeading, czaInch, ; vfli.dyuInch ) + (czaPoint / 4)) / (czaPoint / 2)); mov ax,[tm.tmHeight] sub ax,[tm.tmIntLeading] mov dx,czaInch mov bx,[vfli.dyuInchFli] ; LN_NMultDiv performs NMultDiv(ax, dx, bx) ; ax, bx, cx, dx are altered. call LN_NMultDiv add ax,czaPoint / 4 mov bx,czaPoint / 2 cwd ifdef DEBUG push dx or dx,dx jge LF213 neg dx LF213: cmp dx,czaPoint / 4 pop dx jb LF217 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1202 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LF217: endif ;DEBUG idiv bx errnz <(hpsFcid) - 1> xchg al,ah or al,al je LF22 mov ah,0FFh LF22: ;we now have ah = fcidActual.hps ;/* following line says: if we got back underlining, we can do double underlining too. ; That's because we print double underlines by printing underlined spaces ; just below the first underline. Also let dotted ul through ; regardless because it is only used on the screen */ ; if (tm.tmUnderlined || fcid.kul == kulDotted) ; fcidActual.kul = fcid.kul; errnz <(kulFcid) - 0> mov al,[fcid.kulFcid] and al,maskKulFcid cmp al,kulDotted SHL ibitKulFcid je LF23 cmp [tm.tmUnderlined],fFalse jne LF23 mov al,0 LF23: ; if (tm.tmWeight > (FW_NORMAL + FW_BOLD) / 2) ; fcidActual.fBold = fTrue; cmp [tm.tmWeight],(FW_NORMAL + FW_BOLD) / 2 jle LF24 errnz <(fBoldFcid) - 0> or al,maskfBoldFcid LF24: ; if (tm.tmItalic) ; fcidActual.fItalic = fTrue; cmp [tm.tmItalic],fFalse jz LF25 errnz <(fItalicFcid) - 0> or al,maskfItalicFcid LF25: ; if (tm.tmStruckOut) ; fcidActual.fStrike = fTrue; cmp [tm.tmStruckOut],fFalse jz LF26 errnz <(fStrikeFcid) - 0> or al,maskfStrikeFcid LF26: ; fcidActual.prq = (tm.tmPitchAndFamily & maskFVarPitchTM) ; ? VARIABLE_PITCH : FIXED_PITCH; mov cl,VARIABLE_PITCH SHL shiftPrqFcid test [tm.tmPitch],maskFVarPitchTM jnz LF27 errnz <(prqFcid) - 0> mov cl,FIXED_PITCH SHL shiftPrqFcid LF27: or al,cl ;Assembler note: the low part of pfce->fcidActual = fcidActual ;is actually done below in the C source. mov [si.LO_fcidActualFce],ax ; /* For printer fonts, we may get back a font with a different name than ; the one we requested. ; If this in fact happened, add the new name to the master font table ; */ ; GetTextFace( hdc, LF_FACESIZE, (LPSTR) pffn->szFfn ); lea cx,[di.szFfn] push cx ;first argument for FNeNcSz lea ax,[lf.lfFaceNameLogfont] push ax ;second argument for FNeNcSz push [hdc] mov ax,LF_FACESIZE push ax push ds push cx call far ptr GetTextFace ; if (!FNeNcSz(pffn->szFfn, lf.lfFaceName)) ; { ; /* The face name is the same as what we requested; so, the ; font index should be the same. */ ; fcidActual.ibstFont = pfce->fcidRequest.ibstFont; ; } cCall FNeNcSz,<> or ax,ax errnz <(ibstFontFcid) - 2> mov al,[si.fcidRequestFce.ibstFontFcid] jz LF30 ; else ; { /* Font supplied by printer is different from request */ ; int ibst; ; ; pffn->ffid = tm.tmPitchAndFamily & maskFfFfid; mov al,[tm.tmPitch] and al,maskFfFfid mov [di.ffidFfn],al ; pffn->cbFfnM1 = CbFfnFromCchSzFfn( CchSz( pffn->szFfn ) ) - 1; ; ChsPffn(pffn) = tm.tmCharSet; lea bx,[di.szFfn] push bx cCall CchSz,<> xchg ax,bx add bl,(szFfn) mov [di.cbFfnM1Ffn],bl mov al,[tm.tmCharSet] mov [di+bx],al ; if ((ibst = IbstFindSzFfn( vhsttbFont, pffn )) == iNil) push [vhsttbFont] push di ifdef DEBUG cCall S_IbstFindSzFfn,<> else cCall N_IbstFindSzFfn,<> endif ;DEBUG cmp ax,iNil ; ax = ibst jne LF29 ;/* Font supplied by printer is not in table, add it */ ;/* note: If ibstNil is returned from IbstAddStToSttb that's fine, ; it just means we will select the system font whenever we use the ; result. */ ; { ; Assert ((ibstNil & 0xFF) == ibstFontNil); ; ibst = IbstAddStToSttb( vhsttbFont, pffn ); ; } errnz <(ibstNil AND 0FFh) - ibstFontNil> push [vhsttbFont] push di cCall IbstAddStToSttb,<> LF29: ; fcidActual.ibstFont = ibst; ; } LF30: ; pfce->fcidActual = fcidActual; ;Assembler note: the low part of pfce->fcidActual = fcidActual ;has already been done above. errnz <(ibstFontFcid) - 2> xor ah,ah ; } pop di ;restore pfti jmp short LF33 LF31: ; else ; { /* Screen font - don't care about fcidActual */ ; if (vpref.fDraftView && ; (fcid.fBold || fcid.fItalic || fcid.kul != kulNone || fcid.fStrike) ; fcid.kul = kulSingle; ; pfce->fcidActual = fcid; mov ax,[fcid.LO_lFcid] test [vpref.fDraftViewPref],maskfDraftViewPref jz LF32 errnz <(fBoldFcid) - 0> errnz <(fItalicFcid) - 0> errnz <(fStrikeFcid) - 0> errnz <(kulFcid) - 0> errnz <kulNone> test al,maskFBoldFcid OR maskFItalicFcid OR maskKulFcid OR maskFStrikeFcid jz LF32 and al,NOT maskKulFcid or al,kulSingle SHL ibitKulFcid LF32: mov [si.LO_fcidActualFce],ax mov ax,[fcid.HI_lFcid] ; } LF33: mov [si.HI_fcidActualFce],ax ; LLoadFce: LLoadFce: ; /* Put pfce at the head of the chain extending from pfti */ ; /* When we get here, pfce is not in any chain */ ; pfceHead = pfti->pfce; ; pfti->pfce = pfce; mov bx,si xchg [di.pfceFti],bx ; bx = pfceHead ; pfce->pfcePrev = NULL; mov [si.pfcePrevFce],NULL ; pfce->pfceNext = pfceHead; mov [si.pfceNextFce],bx ; if (pfceHead != NULL) ; pfceHead->pfcePrev = pfce; errnz <NULL> or bx,bx jz LF34 mov [bx.pfcePrevFce],si LF34: ; /* Load info about fce into *pfti */ ; ; bltbyte( pfce, pfti, cbFtiFceSame ); push si push di push ds pop es errnz <cbFtiFceSame AND 1> mov cx,cbFtiFceSame / 2 rep movsw pop di pop si ; si = pfce, di = pfti, es = ds ; vfli.fGraphics |= pfce->fGraphics; test [si.fGraphicsFce],maskfGraphicsFce je LF343 or [vfli.fGraphicsFli],maskFGraphicsFli LF343: ; if (pfce->fFixedPitch) ; SetWords( pfti->rgdxp, pfce->dxpWidth, 256 ); ; else ; bltbh( HpOfHq( pfce->hqrgdxp ), (int huge *)pfti->rgdxp, 256 ); mov cx,256 mov ax,[si.dxpWidthFce] lea di,[di.rgdxpFti] test [si.fFixedPitchFce],maskfFixedPitchFce jnz LF35 mov bx,[si.HI_hqrgdxpFce] mov si,[si.LO_hqrgdxpFce] shl bx,1 mov ax,mpsbps[bx] mov es,ax shr ax,1 jc LF345 ; ReloadSb requires: ; bx = sb * 2 ; ax = mpsbps [sb]/2 ; returns es = physical address of seg ; ; reload sb trashes ax, cx, and dx cCall ReloadSb,<> LF345: push es pop ds mov si,[si] push ss pop es mov cx,256 rep movsw push ss pop ds db 03Dh ;turns next "rep stosw" into "cmp ax,immediate" LF35: rep stosw ; Debug( vdbs.fCkFont ? CkFont() : 0 ); ifdef DEBUG cmp [vdbs.fCkFontDbs],fFalse jz LF36 cCall CkFont,<> LF36: endif ;DEBUG LF37: ; } cEnd ; Assert( vflm != flmIdle ); ifdef DEBUG LF40: cmp [vflm],flmIdle jne LF41 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,900 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LF41: ret endif ;DEBUG ; Assert( pfce->hfont != NULL ); ifdef DEBUG LF42: cmp [si.hFontFce],NULL jne LF43 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,901 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LF43: ret endif ;DEBUG ; Assert( pfce->pfcePrev != NULL ); ifdef DEBUG LF44: cmp [si.pfcePrevFce],NULL jne LF45 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,902 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LF45: ret endif ;DEBUG ; Assert( pfti->fPrinter ); ; Assert( fWidthsOnly ); ifdef DEBUG LF46: test [di.fPrinterFti],maskfPrinterFti jnz LF47 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,903 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LF47: cmp [fWidthsOnly],fFalse jnz LF48 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,904 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LF48: ret endif ;DEBUG ; Assert( hdc != NULL ); ifdef DEBUG LF53: cmp [hdc],NULL jne LF54 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,906 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax LF54: ret endif ;DEBUG ifdef DEBUG LF56: push ax push bx push cx push dx push di mov di,[pfti] mov ax,DEVICEDEFAULT_FONT cmp [di.fPrinterFti],0 jnz LF57 mov ax,SYSTEM_FONT LF57: ifdef HYBRID cCall GetStockObjectPR,<ax> else ;!HYBRID cCall GetStockObject,<ax> endif ;!HYBRID cmp ax,[si.hfontFce] jnz LF58 mov ax,midFormatn2 mov bx,202 cCall AssertProcForNative,<ax,bx> LF58: pop di pop dx pop cx pop bx pop ax jmp LSystemFontErr endif ;DEBUG ifdef DEBUG ;LogGdiHandle(pfce->hfont, 10000); ;#define LogGdiHandle(hGdi,wId) (vhgdis ? LogGdiHandleProc(hGdi,wId) : 0) LF59: cmp [vhgdis],fFalse je LF60 push ax push bx push cx push dx mov ax,10000 cCall LogGdiHandleProc,<[si.hfontFce], ax> pop dx pop cx pop bx pop ax LF60: ret endif ;DEBUG ;------------------------------------------------------------------------- ; FSelectFont( pfti, phfont, phdc ) ;------------------------------------------------------------------------- ; native FSelectFont( pfti, phfont, phdc ) ; struct FTI *pfti; ; HFONT *phfont; ; HDC *phdc; ; { ; HFONT hfontOrig = *phfont; ; int ww; ; ; HFONT hfontSystem = GetStockObject( SYSTEM_FONT ); ; HFONT hfontSav; ; HANDLE hfontPhy; ;LN_FNotSelectFont takes pfti in bx, phfont in si, phdc in di ;ax, bx, cx, dx, si, di are altered. ; %%Function:LN_FNotSelectFont %%Owner:BRADV PUBLIC LN_FNotSelectFont LN_FNotSelectFont: push [si] ;save hfontOrig ; Assert( *phfont != NULL && *phfont != hfontSpecNil ); ifdef DEBUG errnz <NULL> errnz <hfontSpecNil-1> cmp wptr [si],hfontSpecNil ja FSF01 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1062 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FSF01: endif ; DEBUG ; Assert( pfti != NULL ); ifdef DEBUG errnz <NULL> or bx,bx jne FSF02 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1000 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FSF02: endif ;DEBUG ; if (pfti->fPrinter) ; { /* Selecting into printer DC */ test [bx.fPrinterFti],maskfPrinterFti push bx ;save pfti ; [sp] = pfti, [sp+2] = hfontOrig, bx = pfti, si = phfont, di = phdc jz FSF04 ; Assert( vpri.hdc != NULL ); ; /* We should not have been called if there is no printer device */ ; Assert( vpri.pfti != NULL ); ifdef DEBUG ;Assert (vpri.hdc != NULL) and ;Assert (vpri.pfti != NULL) with a call so as not ;to mess up short jumps. call FSF17 endif ;DEBUG ; *phdc = vpri.hdc; mov ax,[vpri.hdcPri] mov [di],ax ; ; if (SelectObject( *phdc, *phfont ) == NULL) ; { ifdef DEBUG cCall SelectObjectFP,<ax,[si]> else ;!DEBUG ifdef HYBRID cCall SelectObjectPR,<ax,[si]> else ;!HYBRID cCall SelectObject,<ax,[si]> endif ;!HYBRID endif ;!DEBUG errnz <NULL> or ax,ax ; [sp] = pfti, [sp+2] = hfontOrig, si = phfont, di = phdc jnz FSF03 ; /* Selecting a font into the printer DC failed */ ; /* This probably means we are out of global memory */ ; /* Use DEVICEDEFAULT_FONT instead; it is guaranteed to succeed */ ; SetErrorMat(matFont); call LN_SetErrorMat ; *phfont = GetStockObject( DEVICEDEFAULT_FONT ); mov ax,DEVICEDEFAULT_FONT ifdef HYBRID cCall GetStockObjectPR,<ax> else ;!HYBRID cCall GetStockObject,<ax> endif ;!HYBRID mov [si],ax ; AssertDo( SelectObject( *phdc, *phfont ) ); ;LN_OurSelectObject takes hdc in cx and h in [si]. ;The result is returned in ax. ax, bx, cx, dx are altered. mov cx,[di] call LN_OurSelectObject ifdef DEBUG ;Assert (SelectObject( *phdc, *phfont ) with a call so as not ;to mess up short jumps. call FSF21 endif ;DEBUG ; } ; [sp] = pfti, [sp+2] = hfontOrig, si = phfont, di = phdc FSF03: jmp FSF13 ; } ; else if (vfPrvwDisp) ; SelectPrvwFont(phFont, phdc); FSF04: cmp [vfPrvwDisp],fFalse ; [sp] = pfti, [sp+2] = hfontOrig jz FSF045 ; [sp] = pfti, [sp+2] = hfontOrig, si = phfont, di = phdc ;***Begin in-line SelectPrvwFont ;EXPORT SelectPrvwFont(phfont, phdc) ;HFONT *phfont; ;HDC *phdc; ; { ; *phdc = PwwdWw(wwLayout)->hdc; mov bx,[mpwwhwwd + (wwLayout SHL 1)] mov bx,[bx] mov cx,[bx.hdcWwd] mov [di],cx ; Assert(*phdc); ifdef DEBUG ;Assert (*phdc) with a call so as not ;to mess up short jumps. call FSF31 endif ;DEBUG ; if (OurSelectObject(*phdc, *phfont) == NULL) ; { ;LN_OurSelectObject takes hdc in cx and h in [si]. ;The result is returned in ax. ax, bx, cx, dx are altered. call LN_OurSelectObject errnz <NULL> or ax,ax jne FSF03 ; *phfont = GetStockObject(SYSTEM_FONT); mov ax,SYSTEM_FONT ifdef HYBRID cCall GetStockObjectPR,<ax> else ;!HYBRID cCall GetStockObject,<ax> endif ;!HYBRID mov [si],ax ; SelectObject(*phdc, *phfont); ifdef DEBUG cCall SelectObjectFP,<[di], [si]> else ;!DEBUG ifdef HYBRID cCall SelectObjectPR,<[di], [si]> else ;!HYBRID cCall SelectObject,<[di], [si]> endif ;!HYBRID endif ;!DEBUG ; } ; } ;***End in-line SelectPrvwFont ; [sp] = pfti, [sp+2] = hfontOrig, si = phfont, di = phdc jmp short FSF03 ; else ; { /* Selecting into screen DCs */ ; [sp] = pfti, [sp+2] = hfontOrig, si = phfont, di = phdc FSF045: ; HFONT hfontSystem = GetStockObject( SYSTEM_FONT ); mov ax,SYSTEM_FONT ifdef HYBRID cCall GetStockObjectPR,<ax> else ;!HYBRID cCall GetStockObject,<ax> endif ;!HYBRID xchg ax,dx ; Assert( vsci.pfti != NULL ); /* This should always be true */ ; /* or we should not have been called */ ; Assert( vsci.hdcScratch ); ifdef DEBUG ;Assert ( vsci.pfti != NULL ) and ;Assert ( vsci.hdcScratch ) with a call so as not ;to mess up short jumps. call FSF24 endif ;DEBUG ; [sp] = pfti, dx = hfontSystem, si = phfont, di = phdc ; *phdc = vsci.hdcScratch; mov ax,[vsci.hdcScratchSci] mov [di],ax ; [sp] = pfti, [sp+2] = hfontOrig, ; dx = hfontSystem, si = phfont, di = phdc ifdef DISABLE ; if (*phfont != hfontSystem) ; { cmp [si],dx endif ; DISABLE push dx ;save hfontSystem push di ;save phdc ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont ifdef DISABLE je FSF06 ; HFONT hfontSav; ; HANDLE hfontPhy; ; int f; ; ; if (!(hfontSav = SelectObject( vsci.hdcScratch, *phfont))) ; goto LScreenFail; ;LN_OurSelectObject takes hdc in cx and h in [si]. ;The result is returned in ax. ax, bx, cx, dx are altered. mov cx,[vsci.hdcScratchSci] call LN_OurSelectObject xchg ax,cx ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont jcxz LScreenFail ; hfontPhy = GetPhysicalFontHandle( vsci.hdcScratch ); ; if (!SelectObject( vsci.hdcScratch, hfontSav)) ; goto LScreenFail; xchg cx,[si] ;create pointer to hfontSav in si push cx ;save *phfont mov ax,[vsci.hdcScratchSci] push ax cCall GetPhysicalFontHandle,<ax> xchg ax,di ;save hfontPhy ;LN_OurSelectObject takes hdc in cx and h in [si]. ;The result is returned in ax. ax, bx, cx, dx are altered. pop cx call LN_OurSelectObject pop [si] ;restore *phfont (and trash hfontSav) xchg ax,cx ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = hfontPhy jcxz LScreenFail ; ResetFont(fFalse /*fPrinterFont*/); errnz <fFalse> xor ax,ax push ax ifdef DEBUG cCall S_ResetFont,<> else push cs call near ptr N_ResetFont endif ;DEBUG ; if (((f=GlobalFlags(hfontPhy)) & GMEM_LOCKCOUNT) == 0 && ; (f & ~GMEM_LOCKCOUNT) != 0) ; { cCall GlobalFlags,<di> errnz <GMEM_LOCKCOUNT - 000FFh> or al,al ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = hfontPhy jnz FSF06 or ah,ah jz FSF06 ; Scribble(ispWireFont, 'W'); ifdef DEBUG ;Do this debug stuff with a call so as not to mess up short jumps. call FSF27 endif ;DEBUG ; GlobalWire(hfontPhy); ; GlobalUnlock(hfontPhy); /* because GlobalWire locked it */ ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di=hfontPhy ifdef HYBRID cCall GlobalWirePR,<di> else ;!HYBRID cCall GlobalWire,<di> endif ;!HYBRID ifdef HYBRID cCall GlobalUnlockPR,<di> else ;!HYBRID cCall GlobalUnlock,<di> endif ;!HYBRID ; } ; } FSF06: endif ; DISABLE ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont ; for ( ;; ) FSF07: ; { ; /* Select the font into the scratchpad memory DC and all window DC's*/ ; ; if (vsci.hdcScratch) mov cx,[vsci.hdcScratchSci] ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont jcxz FSF09 ; if (!SelectObject( vsci.hdcScratch, *phfont )) ; { ;LN_OurSelectObject takes hdc in cx and h in [si]. ;The result is returned in ax. ax, bx, cx, dx are altered. call LN_OurSelectObject or ax,ax ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont jnz FSF09 ; /* could not select in the font: revert back to the system font */ ; LScreenFail: LScreenFail: ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont ; SetErrorMat(matFont); call LN_SetErrorMat ; if (*phfont != hfontSystem) ; { pop bx ;pop phdc pop ax ;restore hfontSystem cmp [si],ax ;[sp] = pfti, [sp+2] = hfontOrig, ax = hfontSystem, si = phfont ifdef DEBUG je FSF08 else ;not DEBUG je FSF13 endif ;DEBUG ; *phfont = hfontSystem; mov [si],ax ; continue; push ax ;save hfontSystem push bx ;save phdc ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont jmp short FSF07 ; } ; /* this should never happen, according to paulk, but just in case.. */ ; Assert( fFalse ); ifdef DEBUG FSF08: ;Assert ( fFalse ) with a jump so as not ;to mess up short jumps. ;[sp] = pfti, [sp+2] = hfontOrig, ax = hfontSystem, si = phfont jmp FSF30 endif ;DEBUG ; break; ; } ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont FSF09: ; for ( ww = wwDocMin; ww < wwMac; ww++ ) ; { mov di,wwDocMin ; di = ww ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = ww jmp short FSF12 FSF10: ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = ww ; struct WWD **hwwd = mpwwhwwd [ww]; mov bx,di mov bx,[bx+di.mpwwhwwd] ; bx = hwwd ; /* test for hdc == NULL is for wwdtClipboard, whose DC is only ; present inside clipboard update messages. See clipdisp.c */ ; if (hwwd != hNil && (hdc = (*hwwd)->hdc) != NULL) ; { errnz <hNil> or bx,bx ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = ww je FSF11 mov bx,[bx] mov cx,[bx.hdcWwd] ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = ww jcxz FSF11 ;/* Hack to workaround problem with font mapper 3/18/89: for some unknown ; reason, the mapper won't select the Preview and Terminal screen ; fonts for a window hdc, although it will for a memory DC compatible ; with it(!). To workaround this, store away hdc to make sure ; the font cache gets the metrics that will accurately reflect the screen ; results. (BL) */ ; *phdc = hdc; pop bx ;pop phdc push bx ;repush phdc mov [bx],cx ; if (!SelectObject( hdc, *phfont )) ;LN_OurSelectObject takes hdc in cx and h in [si]. ;The result is returned in ax. ax, bx, cx, dx are altered. call LN_OurSelectObject ; goto LScreenFail; or ax,ax ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = ww jz LScreenFail ; } FSF11: ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = ww inc di ; } FSF12: cmp di,[wwMac] ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = ww jl FSF10 ; break; ; } /* end for ( ;; ) */ ; } ;[sp] = phdc, [sp+2] = hfontSystem, [sp+4] = pfti, ;[sp+6] = hfontOrig, si = phfont, di = ww pop ax ;remove phdc from the stack pop ax ;remove hfontSystem from the stack ;[sp] = pfti, [sp+2] = hfontOrig, ax = hfontSystem, si = phfont FSF13: pop bx ;restore pfti ; Scribble(ispWireFont, ' '); ifdef DEBUG test [vdbs.grpfScribbleDbs], -1 jz FSF14 push ax push bx push cx push dx mov ax, ispWireFont mov bx, 020h cCall ScribbleProc, <ax, bx> pop dx pop cx pop bx pop ax FSF14: endif ;DEBUG ; pfti->hfont = *phfont; ;[sp+2] = hfontOrig, ax = hfontSystem, bx = pfti, si = phfont mov dx,[si] mov [bx.hfontFti],dx ; return *phfont == hfontOrig; pop ax ;restore hfontOrig sub ax,dx ; } ret ; Assert( vpri.hdc != NULL ); ; Assert( vpri.pfti != NULL ); ifdef DEBUG FSF17: cmp [vpri.hdcPri],NULL jne FSF18 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1063 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FSF18: cmp [vpri.pftiPri],NULL jne FSF19 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1063 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FSF19: ret endif ; DEBUG ; AssertDo( SelectObject( *phdc, *phfont ) ); ifdef DEBUG FSF21: or ax,ax jnz FSF22 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1003 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FSF22: ret endif ;DEBUG ; Assert( vsci.pfti != NULL ); /* This should always be true */ ; /* or we should not have been called */ ; Assert( vsci.hdcScratch ); ifdef DEBUG FSF24: cmp [vsci.pftiSci],NULL jnz FSF25 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1004 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FSF25: cmp [vsci.hdcScratchSci],fFalse jnz FSF26 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1005 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FSF26: ret endif ;DEBUG ; Scribble(ispWireFont, 'W'); ifdef DEBUG FSF27: test [vdbs.grpfScribbleDbs], -1 jz FSF28 push ax push bx push cx push dx mov ax, ispWireFont mov bx, 057h cCall ScribbleProc, <ax, bx> pop dx pop cx pop bx pop ax FSF28: ret endif ;DEBUG ifdef DEBUG ;Assert ( fFalse ) with a jump so as not ;to mess up short jumps. FSF30: push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1005 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax ;[sp] = pfti, [sp+2] = hfontOrig, ax = hfontSystem, si = phfont jmp FSF13 endif ;DEBUG ; Assert(*phdc); ifdef DEBUG FSF31: cmp wptr [di],0 jnz FSF32 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1020 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FSF32: ret endif ;DEBUG LN_SetErrorMat: mov ax,matFont cCall SetErrorMatProc,<ax> ret ;------------------------------------------------------------------------- ; ResetFont(fPrinterFont) ;------------------------------------------------------------------------- ; %%Function:N_ResetFont %%Owner:BRADV cProc N_ResetFont,<PUBLIC,FAR>,<si> ParmW fPrinterFont ; /* R E S E T F O N T */ ; ; native ResetFont(fPrinterFont) ; BOOL fPrinterFont; ; { ; /* This routine sets to NULL the currently selected printer or screen font, ; depending on the value of fPrint. It does not free any fonts, leaving the ; device's font chain intact. ; ; This should be done before freeing fonts to assure that none are selected ; into DC's. It may also be used if explicit use of the system font is required. ; ; */ ; ; extern BOOL vfPrinterValid; ; struct FTI *pfti; ; HFONT hfont; ; HFONT hdcT; localW hfont localW hdcT cBegin ; if ((pfti = (fPrinterFont) ? vpri.pfti : vsci.pfti) == NULL) ; return; /* device does not exist */ mov cx,[fPrinterFont] mov si,[vsci.pftiSci] jcxz RF01 mov si,[vpri.pftiPri] RF01: errnz <NULL> or si,si ; si = pfti jz RF05 ; if (fPrinterFont && vpri.pfti->fTossedPrinterDC) ; { /* printer DC was tossed away */ ; goto LNoFont; ; } jcxz RF02 mov bx,[vpri.pftiPri] test [bx.fTossedPrinterDCFti],maskfTossedPrinterDCFti jnz LNoFont RF02: ; hfont = GetStockObject( fPrinterFont ? DEVICEDEFAULT_FONT : SYSTEM_FONT ); mov ax,SYSTEM_FONT jcxz RF03 errnz <DEVICEDEFAULT_FONT - SYSTEM_FONT - 1> inc ax RF03: ifdef HYBRID cCall GetStockObjectPR,<ax> else ;!HYBRID cCall GetStockObject,<ax> endif ;!HYBRID mov [hfont],ax ; AssertDo(FSelectFont( pfti, &hfont, &hdcT )); push di push si mov bx,si lea si,[hfont] lea di,[hdcT] ;LN_FNotSelectFont takes pfti in bx, phfont in si, phdc in di ;ax, bx, cx, dx, si, di are altered. call LN_FNotSelectFont pop si pop di ifdef DEBUG or ax,ax je RF04 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1102 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax RF04: endif ;DEBUG ; LNoFont: LNoFont: ; pfti->hfont = NULL; /* So we know there's no cached font in pfti->hdc */ errnz <NULL> xor ax,ax mov [si.hfontFti],ax ; pfti->fcid.lFcid = fcidNil; errnz <fcidNil_LO - 0FFFFh> errnz <fcidNil_HI - 0FFFFh> dec ax mov [si.fcidFti.LO_lFcid],ax mov [si.fcidFti.HI_lFcid],ax ; } RF05: cEnd ;------------------------------------------------------------------------- ; FGraphicsFcidToPlf( fcid, plf, fPrinterFont ) ;------------------------------------------------------------------------- ; %%Function:N_FGraphicsFcidToPlf %%Owner:BRADV cProc N_FGraphicsFcidToPlf,<PUBLIC,FAR>,<si,di> ParmD fcid ParmW plf ParmW fPrinterFont ; ; /* F C I D T O P L F */ ; ; native FGraphicsFcidToPlf( fcid, plf, fPrinterFont ) ; union FCID fcid; ; LOGFONT *plf; ; int fPrinterFont; ; { /* Translate an FCID into a windows logical font request structure */ ; int ps; ; struct FFN *pffn; ; cBegin mov ax,[OFF_fcid] mov dx,[SEG_fcid] mov di,[plf] mov cx,[fPrinterFont] call LN_FGraphicsFcidToPlf and ax,maskFGraphicsFfn cEnd ;LN_FGraphicsFcidToPlf takes fcid in dx:ax, plf in di, fPrinterFont in cx ;ax, bx, cx, dx, si, di are altered. ; returns pffn->fGraphics in maskfGraphicsFfn bit of al LN_FGraphicsFcidToPlf: ; SetBytes(plf, 0, sizeof(LOGFONT)); push ds pop es ; ; /* Scale the request into device units */ ; ; Assert( fcid.hps > 0 ); ifdef DEBUG errnz <(hpsFcid) - 1> or ah,ah ja FTP01 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1100 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax FTP01: endif ;DEBUG ;plf->lfHeight = NMultDiv( fcid.hps * (czaPoint / 2), ; fPrinterFont ? vfli.dyuInch : vfli.dysInch, ; czaInch ); ;/* (BL) *** HACK *** *** ACK *** **** GAG **** *** BARF *** ; The Windows courier font has interesting non-international pixels ; in its internal leading area. So, when picking courier ; screen fonts, use positive lfHeight, meaning choose the font by ; CELL height instead of CHARACTER height. ; ChrisLa says this fiasco is Aldus' fault. */ ;if (fcid.ibstFont != ibstCourier || fPrinterFont) ; plf->lfHeight = -plf->lfHeight; push ax ;save LO_fcid push cx ;save fPrinterFont push dx ;save HI_fcid mov al,czaPoint / 2 errnz <(hpsFcid) - 1> mul ah mov dx,[vfli.dysInchFli] jcxz FTP02 mov dx,[vfli.dyuInchFli] FTP02: mov bx,czaInch ; LN_NMultDiv performs NMultDiv(ax, dx, bx) ; ax, bx, cx, dx are altered. call LN_NMultDiv pop dx ;restore HI_fcid pop cx ;restore fPrinterFont push cx errnz <(ibstFontFcid) - 2> cmp dl, ibstCourier jne FTP02Char jcxz FTP02Cell FTP02Char: neg ax FTP02Cell: errnz <(lfHeightLogfont) - 0> stosw xor ax,ax errnz <(lfWidthLogfont) - (lfHeightLogfont) - 2> stosw errnz <(lfEscapementLogfont) - (lfWidthLogfont) - 2> stosw errnz <(lfOrientationLogfont) - (lfEscapementLogfont) - 2> stosw ; ; ; Assert( fcid.ibstFont < (*vhsttbFont)->ibstMac ); ifdef DEBUG push ax push bx push cx push dx mov bx,[vhsttbFont] mov bx,[bx] errnz <(ibstFontFcid) - 2> xor dh,dh cmp dx,[bx.ibstMacSttb] jl FTP03 mov ax,midFormatn2 mov bx,1101 cCall AssertProcForNative,<ax, bx> FTP03: pop dx pop cx pop bx pop ax endif ;DEBUG ; pffn = PstFromSttb( vhsttbFont, fcid.ibstFont ); push [vhsttbFont] errnz <(ibstFontFcid) - 2> xor dh,dh push dx cCall PstFromSttb,<> push ds pop es ;restore es xchg ax,si ; si = pffn pop cx ;restore fPrinterFont pop bx ;restore LO_fcid ; plf->lfPitchAndFamily = (pffn->ffid & maskFfFfid) | fcid.prq; ;PAUSE mov ah,[si.ffidFfn] errnz <(prqFcid)-0> mov al,bl and ax,maskPrqFcid + (maskFfFfid SHL 8) errnz <maskPrqFcid-0C0h> rol al,1 rol al,1 or al,ah mov [di.lfPitchAndFamilyLogfont - bptr (lfWeightLogfont)],al ; /* Set Bold, Italic, StrikeOut, Underline */ ; plf->lfWeight = fcid.fBold ? FW_BOLD : FW_NORMAL; errnz <(fBoldFcid) - 0> test bl,maskFBoldFcid mov ax,FW_NORMAL jz FTP08 mov ax,FW_BOLD FTP08: errnz <(lfWeightLogfont) - (lfOrientationLogfont) - 2> stosw ; if (fcid.fItalic) xor ax,ax errnz <(fItalicFcid) - 0> test bl,maskfItalicFcid jz FTP09 ; plf->lfItalic = 1; inc ax FTP09: ; if (fPrinterFont && fcid.kul != kulNone) jcxz FTP10 errnz <(kulFcid) - 0> errnz <kulNone - 0> test bl,maskKulFcid jz FTP10 ; plf->lfUnderline = 1; inc ah FTP10: errnz <(lfItalicLogfont) - (lfWeightLogfont) - 2> errnz <(lfUnderlineLogfont) - (lfItalicLogfont) - 1> stosw ; if (fcid.fStrike) xor ax,ax errnz <(fStrikeFcid) - 0> test bl,maskfStrikeFcid jz FTP11 ; plf->lfStrikeOut = 1; inc ax FTP11: ; /* underlining for the screen is handled by drawing lines */ ; plf->lfCharSet = ChsPffn(pffn); xor bx,bx mov bl,[si.cbFfnM1Ffn] mov ah,[si+bx] errnz <(lfStrikeOutLogfont) - (lfUnderlineLogfont) - 1> errnz <(lfCharSetLogfont) - (lfStrikeOutLogfont) - 1> stosw errnz <(lfOutPrecisionLogfont) - (lfCharSetLogfont) - 1> errnz <(lfClipPrecisionLogfont) - (lfOutPrecisionLogfont) - 1> errnz <(lfQualityLogfont) - (lfClipPrecisionLogfont) - 1> xor ax,ax stosw stosb xchg ax,cx ;save fPrinterFont ; bltbyte( pffn->szFfn, plf->lfFaceName, LF_FACESIZE ); push si add si,(szFfn) errnz <(lfPitchAndFamilyLogfont) - (lfQualityLogfont) - 1> inc di errnz <(lfFaceNameLogfont) - (lfPitchAndFamilyLogfont) - 1> errnz <LF_FACESIZE AND 1> mov cx,LF_FACESIZE / 2 rep movsw pop si ; if (vfPrvwDisp && !fPrinterFont) ; GenPrvwPlf(plf); cmp [vfPrvwDisp],fFalse jz FTP13 or ax,ax jnz FTP13 sub di,(lfFaceNameLogfont)+LF_FACESIZE cCall GenPrvwPlf,<di> FTP13: ; return pffn->fGraphics; mov al,[si.fGraphicsFfn] or al,NOT maskfGraphicsFfn ; } ret ;------------------------------------------------------------------------- ; PfceLruGet() ;------------------------------------------------------------------------- ;LN_PfceLruGet returns its result in si. ;ax, bx, cx, dx, si, di are altered. ; %%Function:LN_PfceLruGet %%Owner:BRADV PUBLIC LN_PfceLruGet LN_PfceLruGet: ; /* P F C E L R U G E T */ ; ; native struct FCE * (PfceLruGet()) ; /* tosses out the LRU cache entry's information */ ; { ; struct FCE *pfce, *pfceEndChain; ; struct FTI *pfti; ; ; Debug( pfceEndChain = NULL ); ifdef DEBUG xor bx,bx ; bx = pfceEndChain endif ; ; /* motivation for algorithm is to free the LRU font if there is only */ ; /* one device's fonts in the cache; and to alternate randomly between */ ; /* the LRU fonts for each device if there are 2 */ ; ; /* NOTE: This algorithm could repeatedly select the same slot if there */ ; /* was a length-1 chain and a length-ifcMax-1 chain, but this case */ ; /* is not interesting here */ ; ; /* Search for an appropriate FCE slot to free: */ ; /* 1. If we find a slot that is free, use that */ ; /* 2. If not, use the last end-of-chain we come to */ ; ; for ( pfce = rgfce; pfce < &rgfce [ifceMax]; pfce++ ) ; { lea si,[rgfce] ; si = pfce mov cx,ifceMax PLG01: ; if (pfce->hfont == NULL) ; return pfce; cmp [si.hfontFce],NULL je PLG07 ; else if (pfce->pfceNext == NULL) cmp [si.pfceNextFce],NULL jne PLG02 ; pfceEndChain = pfce; mov bx,si ; } PLG02: add si,cbFceMin loop PLG01 ; /* found a currently allocated cache entry at the end of its device's LRU ; chain. Remove it from the chain and free its handles */ ; Assert( pfceEndChain != NULL ); ifdef DEBUG ;Assert( pfceEndChain != NULL ) with a call so as not to mess up ;short jumps. call PLG08 endif ;DEBUG ; pfti = pfceEndChain->fPrinter ? vpri.pfti : vsci.pfti; mov di,[vpri.pftiPri] ; di = pfti test [bx.fPrinterFce],maskfPrinterFce jnz PLG03 mov di,[vsci.pftiSci] PLG03: ; if (pfceEndChain->pfcePrev == NULL) ; { cmp [bx.pfcePrevFce],NULL jne PLG04 ; /* Since this font is at the head of the chain, it may be the one */ ; /* currently selected into the device DC(s). If so, deselect it */ ; ResetFont( pfti->fPrinter ); ;PLG10 performs ResetFont( di->fPrinter ); ;ax, cx, dx are altered. call PLG10 ; pfti->pfce = NULL; mov [di.pfceFti],NULL ; } jmp short PLG06 PLG04: ; else ; { ; /* also reset font selected into DC if the hfont is null -- we may ; have left this font selected in because of the fWidthsOnly ; optimization */ ; if (pfti->hfont == NULL) cmp [di.hfontFti],NULL jne PLG05 ; ResetFont( pfti->fPrinter ); ;PLG10 performs ResetFont( di->fPrinter ); ;ax, cx, dx are altered. call PLG10 PLG05: ; pfceEndChain->pfcePrev->pfceNext = NULL; ; pfceEndChain->pfcePrev = NULL; errnz <NULL> xor si,si xchg si,[bx.pfcePrevFce] mov [si.pfceNextFce],NULL ; } PLG06: ; FreeHandlesOfPfce( pfceEndChain ); mov si,bx push si call far ptr FreeHandlesOfPfce ; return pfceEndChain; ; } PLG07: ret ; Assert( pfceEndChain != NULL ); ifdef DEBUG PLG08: or bx,bx jne PLG09 push ax push bx push cx push dx mov ax,midFormatn2 mov bx,1200 cCall AssertProcForNative,<ax, bx> pop dx pop cx pop bx pop ax PLG09: ret endif ;DEBUG ;PLG10 performs ResetFont( di->fPrinter ); ;ax, cx, dx are altered. PLG10: ; ResetFont( pfti->fPrinter ); push bx ;save pfceEndChain mov al,[di.fPrinterFti] and ax,maskfPrinterFti push ax ifdef DEBUG cCall S_ResetFont,<> else push cs call near ptr N_ResetFont endif pop bx ;restore pfceEndChain ret ifdef DEBUG ; Debug( vdbs.fShakeHeap ? ShakeHeap() : 0 ); LN_ShakeHeap: cmp [vdbs.fShakeHeapDbs],0 jz LN_SH01 push ax push bx push cx push dx mov ax,1 cCall ShakeHeapSb,<ax> pop dx pop cx pop bx pop ax LN_SH01: ret endif ;DEBUG ;/* O U R S E L E C T O B J E C T */ ;/* performs a SelectObject, reducing the swap area SOME if it fails */ ;OurSelectObject(hdc, h) ;HDC hdc; ;HANDLE h; ;{ ; extern int vsasCur; ; HANDLE hRet = SelectObject(hdc, h); ; ; if (hRet == NULL && vsasCur <= sasOK) ; { ; /* reduce swap area to an acceptable level (won't swap too much, but ; may have more room for fonts) */ ; OurSetSas(sasOK); ; hRet = SelectObject(hdc, h); ; /* increase the swap area back as far as we can */ ; OurSetSas(sasFull); ; } ; ; return hRet; ;} ;LN_OurSelectObject takes hdc in cx and h in [si]. ;The result is returned in ax. ax, bx, cx, dx are altered. LN_OurSelectObject: push cx ;save hdc ifdef DEBUG cCall SelectObjectFP,<cx, [si]> else ;!DEBUG ifdef HYBRID cCall SelectObjectPR,<cx, [si]> else ;!HYBRID cCall SelectObject,<cx, [si]> endif ;!HYBRID endif ;!DEBUG pop cx ;restore hdc or ax,ax jne OSO01 cmp [vsasCur],sasMin ja OSO01 push cx ;save hdc mov ax,sasMin cCall OurSetSas,<ax> pop cx ;restore hdc ifdef DEBUG cCall SelectObjectFP,<cx, [si]> else ;!DEBUG ifdef HYBRID cCall SelectObjectPR,<cx, [si]> else ;!HYBRID cCall SelectObject,<cx, [si]> endif ;!HYBRID endif ;!DEBUG push ax ;save hRet errnz <sasFull - 0> xor ax,ax cCall OurSetSas,<ax> pop ax ;restore hRet OSO01: ret sEnd format end
// Copyright 2020 VMware, Inc. // SPDX-License-Identifier: Apache-2.0 // #include "herald/default_sensor_delegate.h" namespace herald { DefaultSensorDelegate::DefaultSensorDelegate() {} void DefaultSensorDelegate::sensor(SensorType sensor, const TargetIdentifier& didDetect) { }; void DefaultSensorDelegate::sensor(SensorType sensor, const PayloadData& didRead, const TargetIdentifier& fromTarget) { }; void DefaultSensorDelegate::sensor(SensorType sensor, const ImmediateSendData& didReceive, const TargetIdentifier& fromTarget) { }; void DefaultSensorDelegate::sensor(SensorType sensor, const std::vector<PayloadData>& didShare, const TargetIdentifier& fromTarget) { }; void DefaultSensorDelegate::sensor(SensorType sensor, const Proximity& didMeasure, const TargetIdentifier& fromTarget) { }; template <typename LocationT> void DefaultSensorDelegate::sensor(SensorType sensor, const Location<LocationT>& didVisit) { }; void DefaultSensorDelegate::sensor(SensorType sensor, const Proximity& didMeasure, const TargetIdentifier& fromTarget, const PayloadData& withPayload) { }; void DefaultSensorDelegate::sensor(SensorType sensor, const SensorState& didUpdateState) { }; } // end namespace
; ; Created by Drapegnik on 19.06.15. ; .386 .model flat .code _func@8 proc push ebp mov ebp, esp mov eax, dword ptr [ebp+8] ; n mov ebx, dword ptr [ebp+12] ; a[] ;xor ecx,ecx ;mov edx,24 ;mov [ebx][ecx*4],edx pop ebp ret 8 _func@8 endp end
############################################################################### # 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 6, 0x90 .globl EncryptOFB_RIJ128_AES_NI .type EncryptOFB_RIJ128_AES_NI, @function EncryptOFB_RIJ128_AES_NI: push %r12 push %r15 sub $(168), %rsp mov (192)(%rsp), %rax movdqu (%rax), %xmm0 movdqa %xmm0, (%rsp) movslq %r8d, %r8 movslq %r9d, %r9 mov %rcx, %r15 lea (,%rdx,4), %rax lea (-144)(%r15,%rax,4), %rax lea (,%r9,4), %r10 .p2align 6, 0x90 .Lblks_loopgas_1: cmp %r10, %r8 cmovl %r8, %r10 xor %rcx, %rcx .L__0009gas_1: movb (%rdi,%rcx), %r11b movb %r11b, (96)(%rsp,%rcx) add $(1), %rcx cmp %r10, %rcx jl .L__0009gas_1 mov %r10, %r12 xor %r11, %r11 .p2align 6, 0x90 .Lsingle_blkgas_1: pxor (%r15), %xmm0 cmp $(12), %rdx jl .Lkey_128_sgas_1 jz .Lkey_192_sgas_1 .Lkey_256_sgas_1: aesenc (-64)(%rax), %xmm0 aesenc (-48)(%rax), %xmm0 .Lkey_192_sgas_1: aesenc (-32)(%rax), %xmm0 aesenc (-16)(%rax), %xmm0 .Lkey_128_sgas_1: aesenc (%rax), %xmm0 aesenc (16)(%rax), %xmm0 aesenc (32)(%rax), %xmm0 aesenc (48)(%rax), %xmm0 aesenc (64)(%rax), %xmm0 aesenc (80)(%rax), %xmm0 aesenc (96)(%rax), %xmm0 aesenc (112)(%rax), %xmm0 aesenc (128)(%rax), %xmm0 aesenclast (144)(%rax), %xmm0 movdqa %xmm0, (16)(%rsp) movdqu (96)(%rsp,%r11), %xmm1 pxor %xmm0, %xmm1 movdqu %xmm1, (32)(%rsp,%r11) movdqu (%rsp,%r9), %xmm0 movdqa %xmm0, (%rsp) add %r9, %r11 sub %r9, %r12 jg .Lsingle_blkgas_1 xor %rcx, %rcx .L__000Agas_1: movb (32)(%rsp,%rcx), %r11b movb %r11b, (%rsi,%rcx) add $(1), %rcx cmp %r10, %rcx jl .L__000Agas_1 add %r10, %rdi add %r10, %rsi sub %r10, %r8 jg .Lblks_loopgas_1 mov (192)(%rsp), %rax movdqa (%rsp), %xmm0 movdqu %xmm0, (%rax) add $(168), %rsp vzeroupper pop %r15 pop %r12 ret .Lfe1: .size EncryptOFB_RIJ128_AES_NI, .Lfe1-(EncryptOFB_RIJ128_AES_NI) .p2align 6, 0x90 .globl EncryptOFB128_RIJ128_AES_NI .type EncryptOFB128_RIJ128_AES_NI, @function EncryptOFB128_RIJ128_AES_NI: movdqu (%r9), %xmm0 movslq %r8d, %r8 lea (,%rdx,4), %rax lea (-144)(%rcx,%rax,4), %rax .Lblks_loopgas_2: pxor (%rcx), %xmm0 movdqu (%rdi), %xmm1 cmp $(12), %rdx jl .Lkey_128_sgas_2 jz .Lkey_192_sgas_2 .Lkey_256_sgas_2: aesenc (-64)(%rax), %xmm0 aesenc (-48)(%rax), %xmm0 .Lkey_192_sgas_2: aesenc (-32)(%rax), %xmm0 aesenc (-16)(%rax), %xmm0 .Lkey_128_sgas_2: aesenc (%rax), %xmm0 aesenc (16)(%rax), %xmm0 aesenc (32)(%rax), %xmm0 aesenc (48)(%rax), %xmm0 aesenc (64)(%rax), %xmm0 aesenc (80)(%rax), %xmm0 aesenc (96)(%rax), %xmm0 aesenc (112)(%rax), %xmm0 aesenc (128)(%rax), %xmm0 aesenclast (144)(%rax), %xmm0 pxor %xmm0, %xmm1 movdqu %xmm1, (%rsi) add $(16), %rdi add $(16), %rsi sub $(16), %r8 jg .Lblks_loopgas_2 movdqu %xmm0, (%r9) vzeroupper ret .Lfe2: .size EncryptOFB128_RIJ128_AES_NI, .Lfe2-(EncryptOFB128_RIJ128_AES_NI)
#include "L1Trigger/TrackFindingTracklet/interface/FPGAWord.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" using namespace std; using namespace trklet; FPGAWord::FPGAWord() {} FPGAWord::FPGAWord(int value, int nbits, bool positive, int line, const char* file) { set(value, nbits, positive, line, file); } void FPGAWord::set(int value, int nbits, bool positive, int line, const char* file) { value_ = value; nbits_ = nbits; positive_ = positive; if (positive) { if (value < 0) { edm::LogProblem("Tracklet") << "FPGAWord got negative value:" << value << " (" << file << ":" << line << ")"; } assert(value >= 0); } if (nbits >= 22) { edm::LogPrint("Tracklet") << "FPGAWord got too many bits:" << nbits << " (" << file << ":" << line << ")"; } assert(nbits < 22); if (nbits <= 0) { edm::LogPrint("Tracklet") << "FPGAWord got too few bits:" << nbits << " (" << file << ":" << line << ")"; } assert(nbits > 0); if (positive) { if (value >= (1 << nbits)) { if (file != nullptr) { edm::LogProblem("Tracklet") << "value too large:" << value << " " << (1 << nbits) << " (" << file << ":" << line << ")"; } } assert(value < (1 << nbits)); } else { if (value > (1 << (nbits - 1))) { edm::LogProblem("Tracklet") << "value too large:" << value << " " << (1 << (nbits - 1)) << " (" << file << ":" << line << ")"; } assert(value <= (1 << (nbits - 1))); if (value < -(1 << (nbits - 1))) { edm::LogProblem("Tracklet") << "value too negative:" << value << " " << -(1 << (nbits - 1)) << " (" << file << ":" << line << ")"; } assert(value >= -(1 << (nbits - 1))); } } std::string FPGAWord::str() const { const int nbit = nbits_; if (!(nbit > 0 && nbit < 22)) edm::LogVerbatim("Tracklet") << "nbit: " << nbit; if (nbit == -1) return "?"; if (nbit == 0) return "~"; int valtmp = value_; string str = ""; for (int i = 0; i < nbit; i++) { str = ((valtmp & 1) ? "1" : "0") + str; valtmp >>= 1; } return str; } unsigned int FPGAWord::bits(unsigned int lsb, unsigned int nbit) const { assert(lsb + nbit <= (unsigned int)nbits()); return (value_ >> lsb) & ((1 << nbit) - 1); } bool FPGAWord::atExtreme() const { if (positive_) { return (value_ == 0) || (value_ == (1 << nbits_) - 1); } return ((value_ == (-(1 << (nbits_ - 1)))) || (value_ == ((1 << (nbits_ - 1)) - 1))); } bool FPGAWord::operator==(const FPGAWord& other) const { return (value_ == other.value_) && (nbits_ == other.nbits_) && (positive_ == other.positive_); }
; ; Small C+ Runtime Library ; ; Z88 Application functions ; ; *** Z88 SPECIFIC FUNCTION - probably no equiv for your machine! *** ; ; 11/4/99 ; ; Read Mail ; ; int readmail(char *type, char *info, int length) ; ; Returns 0 on failure, 1 on success PUBLIC readmail INCLUDE "saverst.def" .readmail ld hl,2 add hl,sp ;point to length parameter ld c,(hl) inc hl inc hl ld e,(hl) inc hl ld d,(hl) ; lower 16 of info ld b,0 ; we keep it local (near) inc hl ld a,(hl) inc hl ld h,(hl) ld l,a ; hl holds name of info type ex de,hl ; get parameters the right way round ld a,SR_RPD call_oz(os_sr) ld hl,0 ret c inc hl ret
; A016771: a(n) = (3*n)^7. ; 0,2187,279936,4782969,35831808,170859375,612220032,1801088541,4586471424,10460353203,21870000000,42618442977,78364164096,137231006679,230539333248,373669453125,587068342272,897410677851,1338925209984,1954897493193,2799360000000,3938980639167,5455160701056,7446353252589,10030613004288,13348388671875,17565568854912,22876792454961,29509034655744,37725479487783,47829690000000,60170087060757,75144747810816,93206534790699,114868566764928,140710042265625,171382426877952,207616015289871,250226879128704,300124211606973,358318080000000,425927596977747,504189521813376,594467302491009,698260569735168,817215093984375,953133216331392,1107984764452581,1283918464548864,1483273860320763,1708593750000000,1962637152460137,2248392813428736,2569093262823519,2928229434235008,3329565857578125,3777156435935232,4275360817613091,4828861374436224,5442680797299153,6122200320000000,6873178582377927,7701771143776896,8614550657858229,9618527719784448,10721172396796875,11930436453209472,13254776280841401,14703176545910784,16285174563412143,18010885410000000,19891027786401117,21936950640377856,24160660561265139,26574849957103488,29192926025390625,32029040528474112,35098120384607511,38415899085692544,41998948952729733,45864714240000000,50031545098999707,54518732413151616,59346543514314249,64536258792112128,70110209207109375,76091814718849152,82505623639781421,89377352926101504,96733929416521923,104603532030000000,113015634933443697,122001051690418176,131591980401875559,141822049849930368,152726366655703125,164341563462254592,176705848153633131,189859054121057664,203842691587258713 pow $0,7 mul $0,2187
db DEX_DODRIO ; pokedex id db 60 ; base hp db 110 ; base attack db 70 ; base defense db 100 ; base speed db 60 ; base special db NORMAL ; species type 1 db FLYING ; species type 2 db 46 ; catch rate db 158 ; base exp yield INCBIN "pic/ymon/dodrio.pic",0,1 ; 77, sprite dimensions dw DodrioPicFront dw DodrioPicBack ; attacks known at lvl 0 db PECK db GROWL db FURY_ATTACK db 0 db 0 ; growth rate ; learnset tmlearn 4,6,8 tmlearn 9,10,15 tmlearn 20 tmlearn 31,32 tmlearn 33,34,40 tmlearn 43,44 tmlearn 49,50,52 db BANK(DodrioPicFront)
;; lux OS kernel ;; copyright (c) 2018 by Omar Mohammad format elf64 use64 section '.text' ; void *memcpy(void *destination, const void *source, size_t count) public memcpy memcpy: push rdi mov rcx, rdx cmp rcx, 128 jl .normal test rsi, 0x0F jnz .unaligned test rdi, 0x0F jnz .unaligned .aligned: push rcx shr rcx, 7 ; div 128 .aligned_loop: movdqa xmm0, [rsi] movdqa xmm1, [rsi+0x10] movdqa xmm2, [rsi+0x20] movdqa xmm3, [rsi+0x30] movdqa xmm4, [rsi+0x40] movdqa xmm5, [rsi+0x50] movdqa xmm6, [rsi+0x60] movdqa xmm7, [rsi+0x70] movdqa [rdi], xmm0 movdqa [rdi+0x10], xmm1 movdqa [rdi+0x20], xmm2 movdqa [rdi+0x30], xmm3 movdqa [rdi+0x40], xmm4 movdqa [rdi+0x50], xmm5 movdqa [rdi+0x60], xmm6 movdqa [rdi+0x70], xmm7 add rsi, 128 add rdi, 128 loop .aligned_loop pop rcx .normal: push rcx and rcx, 0x7F shr rcx, 3 rep movsq pop rcx and rcx, 7 rep movsb pop rax ret .unaligned: push rcx shr rcx, 7 ; div 128 .unaligned_loop: movdqu xmm0, [rsi] movdqu xmm1, [rsi+0x10] movdqu xmm2, [rsi+0x20] movdqu xmm3, [rsi+0x30] movdqu xmm4, [rsi+0x40] movdqu xmm5, [rsi+0x50] movdqu xmm6, [rsi+0x60] movdqu xmm7, [rsi+0x70] movdqu [rdi], xmm0 movdqu [rdi+0x10], xmm1 movdqu [rdi+0x20], xmm2 movdqu [rdi+0x30], xmm3 movdqu [rdi+0x40], xmm4 movdqu [rdi+0x50], xmm5 movdqu [rdi+0x60], xmm6 movdqu [rdi+0x70], xmm7 add rsi, 128 add rdi, 128 loop .unaligned_loop pop rcx jmp .normal ; void sse2_copy(void *destination, void* source, size_t count) public sse2_copy sse2_copy: mov rcx, rdx .loop: movdqa xmm0, [rsi] movdqa xmm1, [rsi+0x10] movdqa xmm2, [rsi+0x20] movdqa xmm3, [rsi+0x30] movdqa xmm4, [rsi+0x40] movdqa xmm5, [rsi+0x50] movdqa xmm6, [rsi+0x60] movdqa xmm7, [rsi+0x70] movdqa [rdi], xmm0 movdqa [rdi+0x10], xmm1 movdqa [rdi+0x20], xmm2 movdqa [rdi+0x30], xmm3 movdqa [rdi+0x40], xmm4 movdqa [rdi+0x50], xmm5 movdqa [rdi+0x60], xmm6 movdqa [rdi+0x70], xmm7 add rsi, 128 add rdi, 128 loop .loop ret
;****************************************************************** ;* Main routine ;****************************************************************** org $2000 lds #STACK jsr HW_INIT jsr INIT loc loop_c`: jsr MODO_CONFIG tst NumVueltas beq loop_c` loop_m`: brset PTH,$C0,race` bclr PIEH,$09 brset PTH,$80,overview` bclr TIE,$20 clr Veloc clr Vueltas clr VelProm brset PTH,$40,config` idle`: jsr MODO_LIBRE bra loop_m` race`: bset PIEH,$09 bset TIE,$20 jsr MODO_COMPETENCIA bra loop_m` overview`: jsr MODO_RESUMEN bra loop_m` config`: jsr MODO_CONFIG bra loop_m`
#ifndef PATTERN_H #define PATTERN_H #include "defines.hpp" #include "utils.hpp" typedef struct s_pattern{ bitboard b_bits; bitboard w_bits; bitboard e_bits; int color; int r_shift = 0; int c_shift = 0; int start_r; int start_c; int end_r; int end_c; int direction; int c_delta; int r_delta; int size; } pattern; typedef pattern (*pattern_generator)(int, int, int); bool shift_pattern_to(pattern &pat, int row, int col); // bool shift_pattern_to_other_end(pattern &pat, int row, int col); void print_pattern(pattern &pat); pattern create_capture_pattern(int direction, int player, int variant = 0); pattern create_pair_pattern(int direction, int player, int variant = 0); pattern create_triplet_pattern(int direction, int player, int variant = 0); pattern create_quator_pattern(int direction, int player, int variant = 0); pattern create_penta_pattern(int direction, int player, int variant = 0); pattern create_victory_pattern(int direction, int player); void swap_colors(pattern &pat); #endif // DEBUG
/** * @file * @copyright defined in eos/LICENSE */ #pragma once #include <appbase/application.hpp> #include <eosio/chain/asset.hpp> #include <eosio/chain/authority.hpp> #include <eosio/chain/account_object.hpp> #include <eosio/chain/block.hpp> #include <eosio/chain/controller.hpp> #include <eosio/chain/contract_table_objects.hpp> #include <eosio/chain/resource_limits.hpp> #include <eosio/chain/transaction.hpp> #include <eosio/chain/abi_serializer.hpp> #include <eosio/chain/plugin_interface.hpp> #include <eosio/chain/types.hpp> #include <boost/container/flat_set.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <fc/static_variant.hpp> namespace fc { class variant; } namespace eosio { using chain::controller; using std::unique_ptr; using std::pair; using namespace appbase; using chain::name; using chain::uint128_t; using chain::public_key_type; using chain::transaction; using chain::transaction_id_type; using fc::optional; using boost::container::flat_set; using chain::asset; using chain::symbol; using chain::authority; using chain::account_name; using chain::action_name; using chain::abi_def; using chain::abi_serializer; namespace chain_apis { struct empty{}; struct permission { name perm_name; name parent; authority required_auth; }; template<typename> struct resolver_factory; // see specializations for uint64_t and double in source file template<typename Type> Type convert_to_type(const string& str, const string& desc) { try { return fc::variant(str).as<Type>(); } FC_RETHROW_EXCEPTIONS(warn, "Could not convert ${desc} string '${str}' to key type.", ("desc", desc)("str",str) ) } template<> uint64_t convert_to_type(const string& str, const string& desc); template<> double convert_to_type(const string& str, const string& desc); class read_only { const controller& db; const fc::microseconds abi_serializer_max_time; bool shorten_abi_errors = true; public: static const string KEYi64; read_only(const controller& db, const fc::microseconds& abi_serializer_max_time) : db(db), abi_serializer_max_time(abi_serializer_max_time) {} void validate() const {} void set_shorten_abi_errors( bool f ) { shorten_abi_errors = f; } using get_info_params = empty; struct get_info_results { string server_version; chain::chain_id_type chain_id; uint32_t head_block_num = 0; uint32_t last_irreversible_block_num = 0; chain::block_id_type last_irreversible_block_id; chain::block_id_type head_block_id; fc::time_point head_block_time; account_name head_block_producer; double difficulity; uint64_t virtual_block_cpu_limit = 0; uint64_t virtual_block_net_limit = 0; uint64_t block_cpu_limit = 0; uint64_t block_net_limit = 0; //string recent_slots; //double participation_rate = 0; optional<string> server_version_string; }; get_info_results get_info(const get_info_params&) const; struct producer_info { name producer_name; }; using account_resource_limit = chain::resource_limits::account_resource_limit; struct get_account_results { name account_name; uint32_t head_block_num = 0; fc::time_point head_block_time; bool privileged = false; fc::time_point last_code_update; fc::time_point created; optional<asset> core_liquid_balance; int64_t ram_quota = 0; int64_t net_weight = 0; int64_t cpu_weight = 0; account_resource_limit net_limit; account_resource_limit cpu_limit; int64_t ram_usage = 0; vector<permission> permissions; fc::variant total_resources; fc::variant self_delegated_bandwidth; fc::variant refund_request; fc::variant voter_info; }; struct get_account_params { name account_name; optional<symbol> expected_core_symbol; }; get_account_results get_account( const get_account_params& params )const; struct get_code_results { name account_name; string wast; string wasm; fc::sha256 code_hash; optional<abi_def> abi; }; struct get_code_params { name account_name; bool code_as_wasm = false; }; struct get_code_hash_results { name account_name; fc::sha256 code_hash; }; struct get_code_hash_params { name account_name; }; struct get_abi_results { name account_name; optional<abi_def> abi; }; struct get_abi_params { name account_name; }; struct get_raw_code_and_abi_results { name account_name; chain::blob wasm; chain::blob abi; }; struct get_raw_code_and_abi_params { name account_name; }; struct get_raw_abi_params { name account_name; optional<fc::sha256> abi_hash; }; struct get_raw_abi_results { name account_name; fc::sha256 code_hash; fc::sha256 abi_hash; optional<chain::blob> abi; }; get_code_results get_code( const get_code_params& params )const; get_code_hash_results get_code_hash( const get_code_hash_params& params )const; get_abi_results get_abi( const get_abi_params& params )const; get_raw_code_and_abi_results get_raw_code_and_abi( const get_raw_code_and_abi_params& params)const; get_raw_abi_results get_raw_abi( const get_raw_abi_params& params)const; struct abi_json_to_bin_params { name code; name action; fc::variant args; }; struct abi_json_to_bin_result { vector<char> binargs; }; abi_json_to_bin_result abi_json_to_bin( const abi_json_to_bin_params& params )const; struct abi_bin_to_json_params { name code; name action; vector<char> binargs; }; struct abi_bin_to_json_result { fc::variant args; }; abi_bin_to_json_result abi_bin_to_json( const abi_bin_to_json_params& params )const; struct get_required_keys_params { fc::variant transaction; flat_set<public_key_type> available_keys; }; struct get_required_keys_result { flat_set<public_key_type> required_keys; }; get_required_keys_result get_required_keys( const get_required_keys_params& params)const; using get_transaction_id_params = transaction; using get_transaction_id_result = transaction_id_type; get_transaction_id_result get_transaction_id( const get_transaction_id_params& params)const; struct get_block_params { string block_num_or_id; }; fc::variant get_block(const get_block_params& params) const; struct get_block_header_state_params { string block_num_or_id; }; fc::variant get_block_header_state(const get_block_header_state_params& params) const; struct get_table_rows_params { bool json = false; name code; string scope; name table; string table_key; string lower_bound; string upper_bound; uint32_t limit = 10; string key_type; // type of key specified by index_position string index_position; // 1 - primary (first), 2 - secondary index (in order defined by multi_index), 3 - third index, etc string encode_type{"dec"}; //dec, hex , default=dec optional<bool> reverse; optional<bool> show_payer; // show RAM pyer }; struct get_table_rows_result { vector<fc::variant> rows; ///< one row per item, either encoded as hex String or JSON object bool more = false; ///< true if last element in data is not the end and sizeof data() < limit }; get_table_rows_result get_table_rows( const get_table_rows_params& params )const; struct get_table_by_scope_params { name code; // mandatory name table = 0; // optional, act as filter string lower_bound; // lower bound of scope, optional string upper_bound; // upper bound of scope, optional uint32_t limit = 10; optional<bool> reverse; }; struct get_table_by_scope_result_row { name code; name scope; name table; name payer; uint32_t count; }; struct get_table_by_scope_result { vector<get_table_by_scope_result_row> rows; string more; ///< fill lower_bound with this value to fetch more rows }; get_table_by_scope_result get_table_by_scope( const get_table_by_scope_params& params )const; struct get_currency_balance_params { name code; name account; optional<string> symbol; }; vector<asset> get_currency_balance( const get_currency_balance_params& params )const; struct get_currency_stats_params { name code; string symbol; }; struct get_currency_stats_result { asset supply; asset max_supply; account_name issuer; }; fc::variant get_currency_stats( const get_currency_stats_params& params )const; struct get_producers_params { bool json = false; string lower_bound; uint32_t limit = 50; }; struct get_producers_result { vector<fc::variant> rows; ///< one row per item, either encoded as hex string or JSON object uint64_t total_wood; string more; ///< fill lower_bound with this value to fetch more rows }; get_producers_result get_producers( const get_producers_params& params )const; struct get_dbps_params { bool json = false; string lower_bound; uint32_t limit = 50; }; struct get_dbps_result { vector<fc::variant> rows; ///< one row per item, either encoded as hex string or JSON object int64_t total_dbp_resouresweight = 0; int64_t total_unpaid_resouresweight = 0; string more; ///< fill lower_bound with this value to fetch more rows }; get_dbps_result get_dbps( const get_dbps_params& params )const; struct get_producer_schedule_params { }; struct get_producer_schedule_result { fc::variant active; fc::variant pending; fc::variant proposed; }; get_producer_schedule_result get_producer_schedule( const get_producer_schedule_params& params )const; struct get_scheduled_transactions_params { bool json = false; string lower_bound; /// timestamp OR transaction ID uint32_t limit = 50; }; struct get_scheduled_transactions_result { fc::variants transactions; string more; ///< fill lower_bound with this to fetch next set of transactions }; get_scheduled_transactions_result get_scheduled_transactions( const get_scheduled_transactions_params& params ) const; static void copy_inline_row(const chain::key_value_object& obj, vector<char>& data) { data.resize( obj.value.size() ); memcpy( data.data(), obj.value.data(), obj.value.size() ); } template<typename Function> void walk_key_value_table(const name& code, const name& scope, const name& table, Function f) const { const auto& d = db.db(); const auto* t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(code, scope, table)); if (t_id != nullptr) { const auto &idx = d.get_index<chain::key_value_index, chain::by_scope_primary>(); decltype(t_id->id) next_tid(t_id->id._id + 1); auto lower = idx.lower_bound(boost::make_tuple(t_id->id)); auto upper = idx.lower_bound(boost::make_tuple(next_tid)); for (auto itr = lower; itr != upper; ++itr) { if (!f(*itr)) { break; } } } } static uint64_t get_table_index_name(const read_only::get_table_rows_params& p, bool& primary); template <typename IndexType, typename SecKeyType, typename ConvFn> read_only::get_table_rows_result get_table_rows_by_seckey( const read_only::get_table_rows_params& p, const abi_def& abi, ConvFn conv )const { read_only::get_table_rows_result result; const auto& d = db.db(); uint64_t scope = convert_to_type<uint64_t>(p.scope, "scope"); abi_serializer abis; abis.set_abi(abi, abi_serializer_max_time); bool primary = false; const uint64_t table_with_index = get_table_index_name(p, primary); const auto* t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(p.code, scope, p.table)); const auto* index_t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(p.code, scope, table_with_index)); if( t_id != nullptr && index_t_id != nullptr ) { using secondary_key_type = std::result_of_t<decltype(conv)(SecKeyType)>; static_assert( std::is_same<typename IndexType::value_type::secondary_key_type, secondary_key_type>::value, "Return type of conv does not match type of secondary key for IndexType" ); const auto& secidx = d.get_index<IndexType, chain::by_secondary>(); auto lower_bound_lookup_tuple = std::make_tuple( index_t_id->id._id, eosio::chain::secondary_key_traits<secondary_key_type>::true_lowest(), std::numeric_limits<uint64_t>::lowest() ); auto upper_bound_lookup_tuple = std::make_tuple( index_t_id->id._id, eosio::chain::secondary_key_traits<secondary_key_type>::true_highest(), std::numeric_limits<uint64_t>::max() ); if( p.lower_bound.size() ) { if( p.key_type == "name" ) { name s(p.lower_bound); SecKeyType lv = convert_to_type<SecKeyType>( s.to_string(), "lower_bound name" ); // avoids compiler error std::get<1>(lower_bound_lookup_tuple) = conv( lv ); } else { SecKeyType lv = convert_to_type<SecKeyType>( p.lower_bound, "lower_bound" ); std::get<1>(lower_bound_lookup_tuple) = conv( lv ); } } if( p.upper_bound.size() ) { if( p.key_type == "name" ) { name s(p.upper_bound); SecKeyType uv = convert_to_type<SecKeyType>( s.to_string(), "upper_bound name" ); std::get<1>(upper_bound_lookup_tuple) = conv( uv ); } else { SecKeyType uv = convert_to_type<SecKeyType>( p.upper_bound, "upper_bound" ); std::get<1>(upper_bound_lookup_tuple) = conv( uv ); } } if( upper_bound_lookup_tuple < lower_bound_lookup_tuple ) return result; auto walk_table_row_range = [&]( auto itr, auto end_itr ) { auto cur_time = fc::time_point::now(); auto end_time = cur_time + fc::microseconds(1000 * 10); /// 10ms max time vector<char> data; for( unsigned int count = 0; cur_time <= end_time && count < p.limit && itr != end_itr; ++itr, cur_time = fc::time_point::now() ) { const auto* itr2 = d.find<chain::key_value_object, chain::by_scope_primary>( boost::make_tuple(t_id->id, itr->primary_key) ); if( itr2 == nullptr ) continue; copy_inline_row(*itr2, data); fc::variant data_var; if( p.json ) { data_var = abis.binary_to_variant( abis.get_table_type(p.table), data, abi_serializer_max_time, shorten_abi_errors ); } else { data_var = fc::variant( data ); } if( p.show_payer && *p.show_payer ) { result.rows.emplace_back( fc::mutable_variant_object("data", std::move(data_var))("payer", itr->payer) ); } else { result.rows.emplace_back( std::move(data_var) ); } ++count; } if( itr != end_itr ) { result.more = true; } }; auto lower = secidx.lower_bound( lower_bound_lookup_tuple ); auto upper = secidx.upper_bound( upper_bound_lookup_tuple ); if( p.reverse && *p.reverse ) { walk_table_row_range( boost::make_reverse_iterator(upper), boost::make_reverse_iterator(lower) ); } else { walk_table_row_range( lower, upper ); } } return result; } template <typename IndexType> read_only::get_table_rows_result get_table_rows_ex( const read_only::get_table_rows_params& p, const abi_def& abi )const { read_only::get_table_rows_result result; const auto& d = db.db(); uint64_t scope = convert_to_type<uint64_t>(p.scope, "scope"); abi_serializer abis; abis.set_abi(abi, abi_serializer_max_time); const auto* t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(p.code, scope, p.table)); if( t_id != nullptr ) { const auto& idx = d.get_index<IndexType, chain::by_scope_primary>(); auto lower_bound_lookup_tuple = std::make_tuple( t_id->id, std::numeric_limits<uint64_t>::lowest() ); auto upper_bound_lookup_tuple = std::make_tuple( t_id->id, std::numeric_limits<uint64_t>::max() ); if( p.lower_bound.size() ) { if( p.key_type == "name" ) { name s(p.lower_bound); std::get<1>(lower_bound_lookup_tuple) = s.value; } else { auto lv = convert_to_type<typename IndexType::value_type::key_type>( p.lower_bound, "lower_bound" ); std::get<1>(lower_bound_lookup_tuple) = lv; } } if( p.upper_bound.size() ) { if( p.key_type == "name" ) { name s(p.upper_bound); std::get<1>(upper_bound_lookup_tuple) = s.value; } else { auto uv = convert_to_type<typename IndexType::value_type::key_type>( p.upper_bound, "upper_bound" ); std::get<1>(upper_bound_lookup_tuple) = uv; } } if( upper_bound_lookup_tuple < lower_bound_lookup_tuple ) return result; auto walk_table_row_range = [&]( auto itr, auto end_itr ) { auto cur_time = fc::time_point::now(); auto end_time = cur_time + fc::microseconds(1000 * 10); /// 10ms max time vector<char> data; for( unsigned int count = 0; cur_time <= end_time && count < p.limit && itr != end_itr; ++count, ++itr, cur_time = fc::time_point::now() ) { copy_inline_row(*itr, data); fc::variant data_var; if( p.json ) { data_var = abis.binary_to_variant( abis.get_table_type(p.table), data, abi_serializer_max_time, shorten_abi_errors ); } else { data_var = fc::variant( data ); } if( p.show_payer && *p.show_payer ) { result.rows.emplace_back( fc::mutable_variant_object("data", std::move(data_var))("payer", itr->payer) ); } else { result.rows.emplace_back( std::move(data_var) ); } } if( itr != end_itr ) { result.more = true; } }; auto lower = idx.lower_bound( lower_bound_lookup_tuple ); auto upper = idx.upper_bound( upper_bound_lookup_tuple ); if( p.reverse && *p.reverse ) { walk_table_row_range( boost::make_reverse_iterator(upper), boost::make_reverse_iterator(lower) ); } else { walk_table_row_range( lower, upper ); } } return result; } chain::symbol extract_core_symbol()const; friend struct resolver_factory<read_only>; using get_question_block_number_params = empty; struct get_question_block_number_result{ uint32_t question_block_number; }; get_question_block_number_result get_question_block_number(const get_question_block_number_params&)const; struct verify_wood_params{ uint32_t block_number; string account; string wood; }; struct verify_wood_result{ bool result; }; verify_wood_result verify_wood(const verify_wood_params& params)const; struct get_block_random_params{ string block_num_or_id; }; struct get_block_random_result{ uint64_t block_random; }; get_block_random_result get_block_random(const get_block_random_params& params)const; // }; class read_write { controller& db; const fc::microseconds abi_serializer_max_time; public: read_write(controller& db, const fc::microseconds& abi_serializer_max_time); void validate() const; using push_block_params = chain::signed_block; using push_block_results = empty; void push_block(push_block_params&& params, chain::plugin_interface::next_function<push_block_results> next); using push_transaction_params = fc::variant_object; struct push_transaction_results { chain::transaction_id_type transaction_id; fc::variant processed; }; void push_transaction(const push_transaction_params& params, chain::plugin_interface::next_function<push_transaction_results> next); using push_transactions_params = vector<push_transaction_params>; using push_transactions_results = vector<push_transaction_results>; void push_transactions(const push_transactions_params& params, chain::plugin_interface::next_function<push_transactions_results> next); friend resolver_factory<read_write>; }; //support for --key_types [sha256,ripemd160] and --encoding [dec/hex] constexpr const char i64[] = "i64"; constexpr const char i128[] = "i128"; constexpr const char i256[] = "i256"; constexpr const char float64[] = "float64"; constexpr const char float128[] = "float128"; constexpr const char sha256[] = "sha256"; constexpr const char ripemd160[] = "ripemd160"; constexpr const char dec[] = "dec"; constexpr const char hex[] = "hex"; template<const char*key_type , const char *encoding=chain_apis::dec> struct keytype_converter ; template<> struct keytype_converter<chain_apis::sha256, chain_apis::hex> { using input_type = chain::checksum256_type; using index_type = chain::index256_index; static auto function() { return [](const input_type& v) { chain::key256_t k; k[0] = ((uint128_t *)&v._hash)[0]; //0-127 k[1] = ((uint128_t *)&v._hash)[1]; //127-256 return k; }; } }; //key160 support with padding zeros in the end of key256 template<> struct keytype_converter<chain_apis::ripemd160, chain_apis::hex> { using input_type = chain::checksum160_type; using index_type = chain::index256_index; static auto function() { return [](const input_type& v) { chain::key256_t k; memset(k.data(), 0, sizeof(k)); memcpy(k.data(), v._hash, sizeof(v._hash)); return k; }; } }; template<> struct keytype_converter<chain_apis::i256> { using input_type = boost::multiprecision::uint256_t; using index_type = chain::index256_index; static auto function() { return [](const input_type v) { chain::key256_t k; k[0] = ((uint128_t *)&v)[0]; //0-127 k[1] = ((uint128_t *)&v)[1]; //127-256 return k; }; } }; } // namespace chain_apis class chain_plugin : public plugin<chain_plugin> { public: APPBASE_PLUGIN_REQUIRES() chain_plugin(); virtual ~chain_plugin(); virtual void set_program_options(options_description& cli, options_description& cfg) override; void plugin_initialize(const variables_map& options); void plugin_startup(); void plugin_shutdown(); chain_apis::read_only get_read_only_api() const { return chain_apis::read_only(chain(), get_abi_serializer_max_time()); } chain_apis::read_write get_read_write_api() { return chain_apis::read_write(chain(), get_abi_serializer_max_time()); } void accept_block( const chain::signed_block_ptr& block ); void accept_transaction(const chain::packed_transaction& trx, chain::plugin_interface::next_function<chain::transaction_trace_ptr> next); void accept_transaction(const chain::transaction_metadata_ptr& trx, chain::plugin_interface::next_function<chain::transaction_trace_ptr> next); bool block_is_on_preferred_chain(const chain::block_id_type& block_id); static bool recover_reversible_blocks( const fc::path& db_dir, uint32_t cache_size, optional<fc::path> new_db_dir = optional<fc::path>(), uint32_t truncate_at_block = 0 ); static bool import_reversible_blocks( const fc::path& reversible_dir, uint32_t cache_size, const fc::path& reversible_blocks_file ); static bool export_reversible_blocks( const fc::path& reversible_dir, const fc::path& reversible_blocks_file ); // Only call this after plugin_initialize()! controller& chain(); // Only call this after plugin_initialize()! const controller& chain() const; chain::chain_id_type get_chain_id() const; fc::microseconds get_abi_serializer_max_time() const; void handle_guard_exception(const chain::guard_exception& e) const; static void handle_db_exhaustion(); private: void log_guard_exception(const chain::guard_exception& e) const; unique_ptr<class chain_plugin_impl> my; }; } FC_REFLECT( eosio::chain_apis::permission, (perm_name)(parent)(required_auth) ) FC_REFLECT(eosio::chain_apis::empty, ) FC_REFLECT(eosio::chain_apis::read_only::get_info_results, (server_version)(chain_id)(head_block_num)(last_irreversible_block_num)(last_irreversible_block_id)(head_block_id)(head_block_time)(head_block_producer)(difficulity)(virtual_block_cpu_limit)(virtual_block_net_limit)(block_cpu_limit)(block_net_limit)(server_version_string) ) FC_REFLECT(eosio::chain_apis::read_only::get_block_params, (block_num_or_id)) FC_REFLECT(eosio::chain_apis::read_only::get_block_header_state_params, (block_num_or_id)) FC_REFLECT( eosio::chain_apis::read_write::push_transaction_results, (transaction_id)(processed) ) FC_REFLECT( eosio::chain_apis::read_only::get_table_rows_params, (json)(code)(scope)(table)(table_key)(lower_bound)(upper_bound)(limit)(key_type)(index_position)(encode_type)(reverse)(show_payer) ) FC_REFLECT( eosio::chain_apis::read_only::get_table_rows_result, (rows)(more) ); FC_REFLECT( eosio::chain_apis::read_only::get_table_by_scope_params, (code)(table)(lower_bound)(upper_bound)(limit)(reverse) ) FC_REFLECT( eosio::chain_apis::read_only::get_table_by_scope_result_row, (code)(scope)(table)(payer)(count)); FC_REFLECT( eosio::chain_apis::read_only::get_table_by_scope_result, (rows)(more) ); FC_REFLECT( eosio::chain_apis::read_only::get_currency_balance_params, (code)(account)(symbol)); FC_REFLECT( eosio::chain_apis::read_only::get_currency_stats_params, (code)(symbol)); FC_REFLECT( eosio::chain_apis::read_only::get_currency_stats_result, (supply)(max_supply)(issuer)); FC_REFLECT( eosio::chain_apis::read_only::get_producers_params, (json)(lower_bound)(limit) ) FC_REFLECT( eosio::chain_apis::read_only::get_producers_result, (rows)(total_wood)(more)); FC_REFLECT( eosio::chain_apis::read_only::get_dbps_params, (json)(lower_bound)(limit) ) FC_REFLECT( eosio::chain_apis::read_only::get_dbps_result, (rows)(total_dbp_resouresweight)(total_unpaid_resouresweight)(more) ); FC_REFLECT_EMPTY( eosio::chain_apis::read_only::get_producer_schedule_params ) FC_REFLECT( eosio::chain_apis::read_only::get_producer_schedule_result, (active)(pending)(proposed) ); FC_REFLECT( eosio::chain_apis::read_only::get_scheduled_transactions_params, (json)(lower_bound)(limit) ) FC_REFLECT( eosio::chain_apis::read_only::get_scheduled_transactions_result, (transactions)(more) ); FC_REFLECT( eosio::chain_apis::read_only::get_account_results, (account_name)(head_block_num)(head_block_time)(privileged)(last_code_update)(created) (core_liquid_balance)(ram_quota)(net_weight)(cpu_weight)(net_limit)(cpu_limit)(ram_usage)(permissions) (total_resources)(self_delegated_bandwidth)(refund_request)(voter_info) ) FC_REFLECT( eosio::chain_apis::read_only::get_code_results, (account_name)(code_hash)(wast)(wasm)(abi) ) FC_REFLECT( eosio::chain_apis::read_only::get_code_hash_results, (account_name)(code_hash) ) FC_REFLECT( eosio::chain_apis::read_only::get_abi_results, (account_name)(abi) ) FC_REFLECT( eosio::chain_apis::read_only::get_account_params, (account_name)(expected_core_symbol) ) FC_REFLECT( eosio::chain_apis::read_only::get_code_params, (account_name)(code_as_wasm) ) FC_REFLECT( eosio::chain_apis::read_only::get_code_hash_params, (account_name) ) FC_REFLECT( eosio::chain_apis::read_only::get_abi_params, (account_name) ) FC_REFLECT( eosio::chain_apis::read_only::get_raw_code_and_abi_params, (account_name) ) FC_REFLECT( eosio::chain_apis::read_only::get_raw_code_and_abi_results, (account_name)(wasm)(abi) ) FC_REFLECT( eosio::chain_apis::read_only::get_raw_abi_params, (account_name)(abi_hash) ) FC_REFLECT( eosio::chain_apis::read_only::get_raw_abi_results, (account_name)(code_hash)(abi_hash)(abi) ) FC_REFLECT( eosio::chain_apis::read_only::producer_info, (producer_name) ) FC_REFLECT( eosio::chain_apis::read_only::abi_json_to_bin_params, (code)(action)(args) ) FC_REFLECT( eosio::chain_apis::read_only::abi_json_to_bin_result, (binargs) ) FC_REFLECT( eosio::chain_apis::read_only::abi_bin_to_json_params, (code)(action)(binargs) ) FC_REFLECT( eosio::chain_apis::read_only::abi_bin_to_json_result, (args) ) FC_REFLECT( eosio::chain_apis::read_only::get_required_keys_params, (transaction)(available_keys) ) FC_REFLECT( eosio::chain_apis::read_only::get_required_keys_result, (required_keys) ) FC_REFLECT( eosio::chain_apis::read_only::get_question_block_number_result, (question_block_number) ) FC_REFLECT( eosio::chain_apis::read_only::verify_wood_result, (result) ) FC_REFLECT( eosio::chain_apis::read_only::verify_wood_params, (block_number) (account)(wood)) FC_REFLECT( eosio::chain_apis::read_only::get_block_random_params, (block_num_or_id)) FC_REFLECT( eosio::chain_apis::read_only::get_block_random_result, (block_random))
#include "Stream.h" #include "Sample.h" #include "soloud.h" #include "soloud_wavstream.h" #include <memory> #include <set> using namespace MX; using namespace MX::Sound; class StreamAllGatherer : public Singleton<StreamAllGatherer> { public: void AddStream(Stream* stream) { //_streams.insert(stream); } void RemoveStream(Stream* stream) { //_streams.erase(stream); } void CloseAll() { //for (auto &stream : _streams) // stream->Close(); } #ifdef SDLAUDIO static FMOD_RESULT F_CALLBACK stream_callback(FMOD_CHANNELCONTROL* chanControl, FMOD_CHANNELCONTROL_TYPE controlType, FMOD_CHANNELCONTROL_CALLBACK_TYPE callbackType, void* commandData1, void* commandData2) { if (controlType != FMOD_CHANNELCONTROL_CHANNEL) return FMOD_OK; FMOD_CHANNEL* channel = (FMOD_CHANNEL*)chanControl; Stream* stream = nullptr; FMOD_Channel_GetUserData(channel, (void**)&stream); if (callbackType == FMOD_CHANNELCONTROL_CALLBACK_END) { stream->onPlayedUpToEnd(); return FMOD_OK; } return FMOD_OK; } #endif std::set<Stream*> _streams; }; void Stream::CloseAll() { StreamAllGatherer::get().CloseAll(); } Stream::Stream(const char* path) { _stream = std::make_shared<SoLoud::WavStream>(); _stream->load(path); StreamAllGatherer::get().AddStream(this); //WIPLOG } Stream::~Stream() { StreamAllGatherer::get().RemoveStream(this); Close(); } void Stream::Close() { Stop(); _stream.reset(); } std::shared_ptr<Stream> Stream::Create(const char* path) { auto stream = std::make_shared<Stream>(path); if (stream->empty()) return nullptr; return stream; } void Stream::Rewind() { if (_channel != -1) Sample::soLoud().seek(_channel, 0); } void Stream::Play() { _channel = Sample::soLoud().play(*_stream); Sample::soLoud().setProtectVoice(_channel, true); SetSpeed(_speed); SetGain(_gain); SetPan(_pan); #ifdef SDLAUDIO if (_channel || !_sample) return; if (FMOD_OK == FMOD_System_PlaySound(Sample::system(), _sample, 0, true, &_channel)) { float rate = 44100.0f; FMOD_Channel_SetPosition(_channel, 0, FMOD_TIMEUNIT_MS); FMOD_Channel_SetUserData(_channel, this); FMOD_Channel_SetCallback(_channel, &StreamAllGatherer::stream_callback); FMOD_Channel_SetVolume(_channel, _gain); FMOD_Channel_SetFrequency(_channel, rate * _speed); FMOD_Channel_SetPan(_channel, _pan); FMOD_Channel_SetPriority(_channel, 0); SetLooped(_looped); FMOD_Channel_SetPaused(_channel, false); } #endif } void Stream::Stop() { if (_channel != -1) { Sample::soLoud().setProtectVoice(_channel, false); Sample::soLoud().stop(_channel); } _channel = -1; } void Stream::SetSpeed(float speed) { _speed = speed; float rate = 44100.0f; if (_channel != -1) Sample::soLoud().setRelativePlaySpeed(_channel, _speed); } void Stream::SetGain(float gain) { _gain = gain; if (_channel != -1) Sample::soLoud().setVolume(_channel, _gain); } void Stream::SetPan(float pan) { _pan = pan; if (_channel != -1) Sample::soLoud().setPan(_channel, _pan); } void Stream::SetLooped(bool looped) { _looped = looped; _stream->setLooping(looped); } bool Stream::empty() { return _stream == nullptr; } StreamManager::StreamManager() { float vol = 0.0f; #ifdef WIPSERIALIZE if (MX::Database::get().settings().try_get("StreamManager.Settings.Volume", vol)) volume = vol; #endif using namespace std::placeholders; volume.onValueChanged.connect(std::bind(&StreamManager::OnGainChanged, this, _1), this); } void StreamManager::SetDefaultVolume(float v) { float vol = 0.0f; #ifdef WIPSERIALIZE if (!MX::Database::get().settings().try_get("StreamManager.Settings.Volume", vol)) volume = v; #endif } void StreamManager::SetCurrent(const std::shared_ptr<StreamBase>& stream) { if (_currentStream == stream) return; if (_oldStream) { if (_oldStream) _oldStream->Stop(); _oldStream = nullptr; } if (_crossfading) { _crossfading = false; //we are crossfading now, so disable old streams altogether if (_currentStream) _currentStream->Stop(); _oldStream = nullptr; } else { _stopWatch.Start(_changeTime); _crossfading = true; _oldStream = _currentStream; } _currentStream = stream; if (stream) { stream->SetGain(_crossfading ? 0.0f : volume.directValueAccess()); stream->SetLooped(true); stream->Rewind(); stream->Play(); } } void StreamManager::Run() { if (_crossfading) { if (_stopWatch.Tick()) { if (_oldStream) _oldStream->Stop(); _oldStream = nullptr; _crossfading = false; } if (_oldStream) _oldStream->SetGain(volume * _stopWatch.inverse_percent()); if (_currentStream) _currentStream->SetGain(volume * _stopWatch.percent()); } } void StreamManager::Deinit() { #ifdef SDLAUDIO MX::Database::get().settings().set("StreamManager.Settings.Volume", volume.directValueAccess()); #endif if (_oldStream) _oldStream->Stop(); _oldStream = nullptr; if (_currentStream) _currentStream->Stop(); _currentStream = nullptr; } void StreamManager::OnGainChanged(float gain) { if (_currentStream && !_crossfading) _currentStream->SetGain(gain * _stopWatch.percent()); } void StreamManager::SetChangeTime(float time) { _changeTime = time; }
// 5min 2 WA class Solution { public: vector<int> getRow(int rowIndex) { vector<int> res; res.push_back(1); if (rowIndex <= 0) return res; res.push_back(1); if (rowIndex == 1) return res; rowIndex -= 1; while(rowIndex-- > 0) { vector<int> newRes; newRes.push_back(1); for (int i = 1; i < res.size(); i++) { newRes.push_back(res[i]+res[i-1]); } newRes.push_back(1); res = newRes; } return res; } };
; A220414: a(n) = 6*a(n-1) - a(n-2), with a(1) = 13, a(2) = 73. ; 13,73,425,2477,14437,84145,490433,2858453,16660285,97103257,565959257,3298652285,19225954453,112057074433,653116492145,3806641878437,22186734778477,129313766792425,753695865976073,4392861429064013,25603472708408005,149227974821384017,869764376219896097,5069358282497992565,29546385318768059293,172208953630110363193,1003707336461894119865,5850035065141254355997,34096503054385632016117,198728983261172537740705,1158277396512649594428113,6750935395814725028827973,39347334978375700578539725,229333074474439478442410377,1336651111868261170075922537,7790573596735127542013124845,45406790468542504082002826533,264650169214519896950003834353,1542494224818576877618020179585,8990315179696941368758117243157,52399396853363071334930683279357,305406065940481486640825982432985,1780036998789525848510025211318553,10374815926796673604419325285478333,60468858561990515778005926501551445,352438335445146421063616233723830337 mov $1,4 mov $2,9 lpb $0 sub $0,1 add $2,$1 add $1,$2 add $1,$2 add $2,$1 lpe add $1,$2 mov $0,$1
#include <random> #include <vector> #include "gtest/gtest.h" #include "simeng/Pool.hh" namespace { // Tests that memory is reused correctly TEST(FixedPoolTest, MemoryReused) { auto p = simeng::fixedPool_<10, 2>(); void* ptr = p.allocate(); void* ptr2 = p.allocate(); // The pool will grow by 4. Total size is 6. void* ptr3 = p.allocate(); ASSERT_NE(ptr, nullptr); ASSERT_NE(ptr2, nullptr); ASSERT_NE(ptr3, nullptr); p.deallocate(ptr); p.deallocate(ptr2); p.deallocate(ptr3); void* ptr4 = p.allocate(); void* ptr5 = p.allocate(); void* ptr6 = p.allocate(); EXPECT_EQ(ptr3, ptr4); EXPECT_EQ(ptr5, ptr2); EXPECT_EQ(ptr6, ptr); } // Tests that the pointer returned by allocate is sufficiently aligned TEST(FixedPoolTest, Alignment) { auto p = simeng::fixedPool_<25>(); uintptr_t ptr = reinterpret_cast<uintptr_t>(p.allocate()); EXPECT_EQ(ptr & (alignof(std::max_align_t) - 1), 0); } // Tests general usage works correctly. To be tested with sanitizers TEST(FixedPoolTest, GeneralUsage) { std::mt19937 gen; std::uniform_int_distribution<> distribution(0, 1); auto p = simeng::fixedPool_<10>(); for (size_t i = 0; i < 65535; i++) { void* ptr = p.allocate(); // Allocation was successful. ASSERT_NE(ptr, nullptr); // Test that we can access all the bytes. memset(ptr, 0, 10); // Randomly deallocate to simulate real usage. if (distribution(gen)) p.deallocate(ptr); } } } // namespace
; /***************************************************************************** ; * ugBASIC - an isomorphic BASIC language compiler for retrocomputers * ; ***************************************************************************** ; * Copyright 2021 Marco Spedaletti (asimov@mclink.it) ; * ; * 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. ; *---------------------------------------------------------------------------- ; * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0 ; * (la "Licenza"); è proibito usare questo file se non in conformità alla ; * Licenza. Una copia della Licenza è disponibile all'indirizzo: ; * ; * http://www.apache.org/licenses/LICENSE-2.0 ; * ; * Se non richiesto dalla legislazione vigente o concordato per iscritto, ; * il software distribuito nei termini della Licenza è distribuito ; * "COSì COM'è", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o ; * implicite. Consultare la Licenza per il testo specifico che regola le ; * autorizzazioni e le limitazioni previste dalla medesima. ; ****************************************************************************/ ;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ;* * ;* STARTUP ROUTINE ON VIC-I * ;* * ;* by Marco Spedaletti * ;* * ;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ; VIC1LINES = 312 ; VIC1CYCLESPERLINE = 71 ; VIC1TIMERVALUE = ( VIC1LINES * VIC1CYCLESPERLINE - 2 ) / 4 ; VIC1BANK: .BYTE 1 ; VIC1IRQ: ; VIC1IRQX2: ; ; lda $9114 ; get the NMI timer A value ; ; ; (42 to 49 cycles delay at this stage) ; ; ; sta $1e00 ; uncomment these if you want to monitor ; ; ; ldy $9115 ; the reference timer on the screen ; ; ; sty $1e01 ; ; cmp #8 ; are we more than 7 cycles ahead of time? ; ; bcc VIC1IRQX0 ; ; pha ; yes, spend 8 extra cycles ; ; pla ; ; and #7 ; and reset the high bit ; ; VIC1IRQX0: ; ; cmp #4 ; ; bcc VIC1IRQX1 ; ; bit $24 ; waste 4 cycles ; ; and #3 ; ; VIC1IRQX1: ; ; cmp #2 ; spend the rest of the cycles ; ; bcs *+2 ; ; bcs *+2 ; ; lsr ; ; bcs *+2 ; now it has taken 82 cycles from the beginning of the IRQ ; ; LDA VIC1BANK ; ; BEQ VIC1IRQL4A ; ; VIC1IRQL4B: ; ; LDA $9004 ; ; CMP #82 ; ; BCS VIC1IRQEX ; ; VIC1IRQL4B1: ; ; LDA $9004 ; ; CMP #82 ; ; BNE VIC1IRQL4B1 ; ; LDA #$CF ; ; STA $9005 ; ; LDA #6 ; ; STA $900F ; ; LDA #0 ; ; STA VIC1BANK ; ; JMP VIC1IRQEX ; ; VIC1IRQL4A: ; ; LDA $9004 ; ; CMP #0 ; ; BNE VIC1IRQL4A ; ; LDA #$CD ; ; STA $9005 ; ; LDA #2 ; ; STA $900F ; ; LDA #1 ; ; STA VIC1BANK ; ; JMP VIC1IRQEX ; ; VIC1IRQEX: ; JMP $EABF VIC1STARTUP: ; LDA #$7f ; STA $912e ; disable and acknowledge interrupts ; STA $912d ; STA $911e ; disable NMIs (Restore key) ; ;synchronize with the screen ; VIC1STARTUPSYNC: ; LDX #28 ; wait for this raster line (times 2) ; VIC1STARTUPSYNC2: ; CPX $9004 ; BNE VIC1STARTUPSYNC2 ; ; at this stage, the inaccuracy is 7 clock cycles ; ; the processor is in this place 2 to 9 cycles ; ; after $9004 has changed ; LDY #9 ; BIT $24 ; VIC1STARTUPSYNC3: ; LDX $9004 ; TXA ; BIT $24 ; LDX #24 ; VIC1STARTUPSYNC4: ; DEX ; BNE VIC1STARTUPSYNC4 ; ; first spend some time (so that the whole ; CMP $9004 ; loop will be 2 raster lines) ; BCS *+2 ; save one cycle if $9004 changed too late ; DEY ; BNE VIC1STARTUPSYNC3 ; VIC1STARTUPSYNC5: ; ; now it is fully synchronized ; ; 6 cycles have passed since last $9004 change ; ; and we are on line 2(28+9)=74 ; VIC1STARTUPTIMERS: ; LDA #$40 ; enable Timer A free run of both VIAs ; STA $911b ; STA $912b ; LDA #<VIC1TIMERVALUE ; LDX #>VIC1TIMERVALUE ; STA $9116 ; load the timer low byte latches ; STA $9126 ; LDY #7 ; VIC1STARTUPTIMERS2: ; DEY ; BNE VIC1STARTUPTIMERS2 ; NOP ; NOP ; STX $9125 ; ; start the IRQ timer A ; ; 6560-101: 65 cycles from $9004 change ; ; 6561-101: 77 cycles from $9004 change ; LDY #10 ; ; spend some time (1+5*9+4=55 cycles) ; VIC1STARTUPTIMERS3: ; DEY ; ; before starting the reference timer ; BNE VIC1STARTUPTIMERS3 ; STX $9115 ; start the reference timer ; VIC1POINTERS: ; SEI ; LDA #<VIC1IRQ ; set the raster IRQ routine pointer ; STA $314 ; LDA #>VIC1IRQ ; STA $315 ; CLI ; LDA #$c0 ; STA $912e ; enable Timer A underflow interrupts ; ; bits 4-7 select background color ; ; bits 0-2 select border color ; ; bit 3 selects inverted or normal mode LDA #$00 STA $900F ; Lowercase font LDA $9005 AND #$F0 ORA #$0E STA $9005 LDA #$0 STA XCURSYS LDA #$0 STA YCURSYS RTS
/** * \file src/serialization/impl/extern_c_opr.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "megbrain/serialization/extern_c_opr.h" #include "megbrain/comp_node_env.h" #include "megbrain/graph/extern_copr_api.h" #include "megbrain/serialization/extern_c_opr_io.h" #include "megbrain/serialization/opr_load_dump.h" #include <cstdlib> using namespace mgb; using namespace serialization; using namespace opr; namespace { const char PLACEHOLDER_TYPE_NAME[] = "placeholder"; typedef MGBOprDesc* (*opr_desc_transformer_t)(void* input); using LoaderMap = std::unordered_map<std::string, std::pair<MGBOprLoader, opr_desc_transformer_t>>; //! singleton LoaderMap LoaderMap& loader_map() { static LoaderMap ret; return ret; } class MGBOprDescHash final : public HashableVD { MGB_DYN_TYPE_OBJ_FINAL_DECL; MGBOprDesc* const m_desc; bool is_same_st(const Hashable& rhs) const override { return m_desc->is_same(m_desc, static_cast<const MGBOprDescHash&>(rhs).m_desc); } public: MGBOprDescHash(MGBOprDesc* desc) : m_desc{desc} {} size_t hash() const override { return m_desc->hash(m_desc); } }; MGB_DYN_TYPE_OBJ_FINAL_IMPL(MGBOprDescHash); MGBDType dtype_cpp2c(DType dtype) { switch (dtype.enumv()) { case DTypeEnum::Float32: return MGB_DTYPE_FLOAT32; case DTypeEnum::Int32: return MGB_DTYPE_INT32; case DTypeEnum::Int16: return MGB_DTYPE_INT16; case DTypeEnum::Uint8: return MGB_DTYPE_UINT8; #if !MEGDNN_DISABLE_FLOAT16 case DTypeEnum::Float16: return MGB_DTYPE_FLOAT16; #endif default: mgb_throw(InternalError, "unsupported dtype for extern C API: %s", dtype.name()); } } DType dtype_c2cpp(MGBDType dtype) { switch (dtype) { case MGB_DTYPE_UINT8: return dtype::Uint8{}; case MGB_DTYPE_INT16: return dtype::Int16{}; case MGB_DTYPE_INT32: return dtype::Int32{}; case MGB_DTYPE_FLOAT32: return dtype::Float32{}; #if !MEGDNN_DISABLE_FLOAT16 case MGB_DTYPE_FLOAT16: return dtype::Float16{}; #endif default: mgb_throw(SerializationError, "bad dtype value: %d", static_cast<int>(dtype)); } } template <typename S> MGBTensor tensor_to_c(const TensorND<S>& src) { MGBTensor ret; ret.data = const_cast<void*>(static_cast<const void*>(src.raw_ptr())); ret.layout.dtype = dtype_cpp2c(src.dtype()); ret.layout.shape = ExternCOprRunner::tensor_shape_to_c(src.shape()); return ret; } struct MGBOprDescV23 { size_t nr_input, nr_output; //! operator type name const char* type_name; //! release this descriptor void (*release)(MGBOprDescV23* self); //! compute hash size_t (*hash)(const MGBOprDescV23* self); //! equality check int (*is_same)(const MGBOprDescV23* self, const MGBOprDescV23* rhs); //! perform the computation void (*execute)(const MGBOprDescV23* self, const MGBTensor* input, const MGBTensor* output); //! infer output shapes from input shapes void (*infer_shape)(const MGBOprDescV23* self, const MGBTensorShape* input, MGBTensorShape* output); //! custom user data to be associated with this descriptor void* user_data; static MGBOprDesc* as_opr_desc(void* v23_raw) { auto release = [](MGBOprDesc* self) { auto p = static_cast<MGBOprDescV23*>(self->user_data); p->release(p); delete self; }; auto hash = [](const MGBOprDesc* self) { auto p = static_cast<MGBOprDescV23*>(self->user_data); return p->hash(p); }; auto is_same = [](const MGBOprDesc* self, const MGBOprDesc* rhs) { auto p0 = static_cast<MGBOprDescV23*>(self->user_data); auto p1 = static_cast<MGBOprDescV23*>(rhs->user_data); return p0->is_same(p0, p1); }; auto execute = [](const MGBOprDesc* self, const MGBTensor* input, const MGBTensor* output) { auto p = static_cast<MGBOprDescV23*>(self->user_data); p->execute(p, input, output); }; auto infer_shape = [](const MGBOprDesc* self, const MGBTensorShape* input, MGBTensorShape* output) { auto p = static_cast<MGBOprDescV23*>(self->user_data); p->infer_shape(p, input, output); }; auto v23 = static_cast<MGBOprDescV23*>(v23_raw); auto ret = std::make_unique<MGBOprDesc>(); mgb_init_opr_desc(ret.get(), v23->nr_output, v23->type_name); ret->user_data = v23; #define ASSIGN(name) ret->name = name; MGB_OPR_DESC_FOREACH_MEM_FN(ASSIGN); #undef ASSIGN return ret.release(); } }; //! impl MGBOprDesc for ExternCOprRunner::make_placeholder class PlaceholderMGBOprDesc { struct UserData { std::string name; TensorShapeArray output_shapes; SmallVector<DType> output_dtypes; std::unique_ptr<uint8_t[]> data; size_t data_len; }; static UserData* user_data(const MGBOprDesc* self) { return static_cast<UserData*>(self->user_data); } static void release(MGBOprDesc* self) { user_data(self)->~UserData(); ::free(self); } static size_t hash(const MGBOprDesc* self) { return reinterpret_cast<size_t>(self); // hash disabled } static int is_same(const MGBOprDesc* self, const MGBOprDesc* rhs) { return self == rhs; } //! perform the computation static void execute(const MGBOprDesc*, const MGBTensor*, const MGBTensor*) { mgb_throw(MegBrainError, "placeholder ExternCOprRunner can not be executed"); } static void infer_shape(const MGBOprDesc* self, const MGBTensorShape* input, MGBTensorShape* output); static void infer_dtype(const struct MGBOprDesc* self, const MGBDType* input, MGBDType* output); public: static MGBOprDesc* make(size_t nr_input, const char* name, const TensorShapeArray& output_shapes, const SmallVector<DType>& output_dtypes, const void* data, size_t data_len); static void dump(OprDumpContext& ctx, MGBOprDesc* desc); }; } // anonymous namespace /* ===================== PlaceholderMGBOprDesc ===================== */ void PlaceholderMGBOprDesc::infer_shape(const MGBOprDesc* self, const MGBTensorShape* input, MGBTensorShape* output) { auto ud = user_data(self); for (size_t i = 0; i < ud->output_shapes.size(); ++i) { output[i] = ExternCOprRunner::tensor_shape_to_c(ud->output_shapes[i]); } } void PlaceholderMGBOprDesc::infer_dtype(const struct MGBOprDesc* self, const MGBDType* input, MGBDType* output) { auto ud = user_data(self); for (size_t i = 0; i < ud->output_dtypes.size(); ++i) { output[i] = dtype_cpp2c(ud->output_dtypes[i]); } } MGBOprDesc* PlaceholderMGBOprDesc::make(size_t nr_input, const char* name, const TensorShapeArray& output_shapes, const SmallVector<DType>& output_dtypes, const void* data, size_t data_len) { constexpr size_t align = std::max(alignof(MGBOprDesc), alignof(UserData)), desc_size = ((sizeof(MGBOprDesc) - 1) / align + 1) * align; std::unique_ptr<uint8_t, void (*)(void*)> ptr( static_cast<uint8_t*>(malloc(desc_size + sizeof(UserData))), ::free); mgb_assert(ptr); auto del_ud = [](UserData* p) { p->~UserData(); }; std::unique_ptr<UserData, decltype(del_ud)> ud( new (ptr.get() + desc_size) UserData, del_ud); ud->name = name; ud->output_shapes = output_shapes; ud->output_dtypes = output_dtypes; ud->data.reset(new uint8_t[data_len]); ud->data_len = data_len; memcpy(ud->data.get(), data, data_len); auto desc = new (ptr.get()) MGBOprDesc; mgb_init_opr_desc(desc, output_shapes.size(), PLACEHOLDER_TYPE_NAME); desc->user_data = ud.release(); #define s(n) desc->n = &PlaceholderMGBOprDesc::n; MGB_OPR_DESC_FOREACH_MEM_FN(s); if (!output_dtypes.empty()) { desc->infer_dtype = &PlaceholderMGBOprDesc::infer_dtype; } #undef s return reinterpret_cast<MGBOprDesc*>(ptr.release()); } void PlaceholderMGBOprDesc::dump(OprDumpContext& ctx, MGBOprDesc* desc) { mgb_assert(desc->type_name == PLACEHOLDER_TYPE_NAME, "only placeholder ExternCOprRunner can be dumped; got type %s", desc->type_name); auto ud = user_data(desc); ctx.dump_buf_with_len(ud->name.c_str(), ud->name.size()); ctx.dump_buf_with_len(ud->data.get(), ud->data_len); } /* ===================== ExternCOprRunner ===================== */ MGB_DYN_TYPE_OBJ_FINAL_IMPL(ExternCOprRunner); ExternCOprRunner::ExternCOprRunner(std::string& name, const VarNodeArray& inputs, std::shared_ptr<MGBOprDesc> desc, const OperatorNodeConfig& config) : Super{inputs[0]->owner_graph(), config, desc->type_name, inputs}, m_desc{std::move(desc)}, m_dump_name{name}, m_param{nullptr} { mgb_assert(m_desc->size == sizeof(MGBOprDesc), "invalid MGBOprDesc size: expect=%zu got=%u, may caused by " "extern_c_opr.h mismatch, please confirm that the " "extern_c_opr.h used when compiling the loader is consistent " "with the runtime caller build used", sizeof(MGBOprDesc), m_desc->size); for (auto i : inputs) { add_input({i}); } auto nr_out = m_desc->nr_output; if (nr_out > 1) { for (size_t i = 0, it = nr_out; i < it; ++i) add_output(ssprintf("o%zu", i)); } else { mgb_assert(nr_out == 1, "could not create an operator with %u outputs: %s", nr_out, cname()); add_output(None); } add_equivalence_component<MGBOprDescHash>(m_desc.get()); } void ExternCOprRunner::get_output_var_shape(const TensorShapeArray& inp_shape, TensorShapeArray& out_shape) const { SmallVector<MGBTensorShape> c_inp(inp_shape.size()), c_out(out_shape.size()); for (size_t i = 0; i < inp_shape.size(); ++i) { c_inp[i] = tensor_shape_to_c(inp_shape[i]); } m_desc->infer_shape(m_desc.get(), c_inp.data(), c_out.data()); for (size_t i = 0; i < out_shape.size(); ++i) { out_shape[i] = tensor_shape_from_c(c_out[i]); } } void ExternCOprRunner::init_output_dtype() { if (!m_desc->infer_dtype) { Super::init_output_dtype(); return; } SmallVector<MGBDType> inp_dtypes, out_dtypes(output().size()); inp_dtypes.reserve(input().size()); for (auto i : input()) { inp_dtypes.push_back(dtype_cpp2c(i->dtype())); } m_desc->infer_dtype(m_desc.get(), inp_dtypes.data(), out_dtypes.data()); for (size_t i = 0; i < out_dtypes.size(); ++i) { output(i)->dtype(dtype_c2cpp(out_dtypes[i])); } } void ExternCOprRunner::check_param() { //! check extern dynamic param validity //! nr_input=0 or nr_output=0 means do not provide input/output //! ExternDeviceTensor for some case, ExternCOprParam may only config //! device_id, extra_info, etc. so we need consider nr_input=0 or //! nr_output=0 auto check = [](size_t nr_config_tensor, size_t var_node_size, ExternDeviceTensor* e_tensor, const VarNodeArray& var_node_array, const char* msg) { mgb_assert(e_tensor, "%s ExternDeviceTensor should not be null!!", msg); mgb_assert( nr_config_tensor == var_node_size, "param %s size provided by `config_extern_c_opr_dynamic_param` " "mismatch with the number of %s, got %zu, expected %zu", msg, msg, nr_config_tensor, var_node_size); for (size_t i = 0; i < nr_config_tensor; i++) { mgb_assert(e_tensor[i].device_ptr, "%s ExternDeviceTensor(index: %zu) device_ptr should " "not be null!!", msg, i); auto param_shape = e_tensor[i].layout.shape; auto shape = var_node_array.at(i)->shape(); auto param_dtype = e_tensor[i].layout.dtype; auto dtype = dtype_cpp2c(var_node_array.at(i)->dtype()); mgb_assert(param_dtype == dtype, "%s dtype provided mismatch, expected: %u, got: %d", msg, param_dtype, dtype); mgb_assert(shape.ndim == param_shape.ndim, "%s ndim provided mismatch got: %u, expect: %zu of " "index: %zu", msg, param_shape.ndim, shape.ndim, i); for (size_t j = 0; j < shape.ndim; j++) { mgb_assert(param_shape.shape[j] == shape.shape[j], "config %s shape should same with c opr %s shape: " "(got: %u expect: %zu) of index: %zu", msg, msg, param_shape.shape[j], shape.shape[j], j); } } }; if (m_param && m_param->nr_input > 0) { check(m_param->nr_input, input().size(), m_param->input, input(), "input"); } if (m_param && m_param->nr_output > 0) { check(m_param->nr_output, output().size(), m_param->output, output(), "output"); } } void ExternCOprRunner::scn_do_execute() { SmallVector<MGBTensor> c_inp(input().size()), c_out(output().size()); SmallVector<HostTensorND> cpu_inp, cpu_out; check_param(); bool need_copy = false; if (comp_node().device_type() == CompNode::DeviceType::CPU) { for (size_t i = 0; i < input().size(); ++i) { c_inp[i] = tensor_to_c(input(i)->dev_tensor()); } for (size_t i = 0; i < output().size(); ++i) { c_out[i] = tensor_to_c(output(i)->dev_tensor()); } } else { need_copy = true; mgb_log_debug( "copy is needed to execute extern C " "opr `%s' on comp node `%s'", cname(), comp_node().to_string().c_str()); cpu_inp.resize(input().size()); cpu_out.resize(output().size()); for (size_t i = 0; i < input().size(); ++i) { cpu_inp[i].copy_from(input(i)->dev_tensor()); c_inp[i] = tensor_to_c(cpu_inp[i]); } for (size_t i = 0; i < output().size(); ++i) { cpu_out[i] .comp_node(comp_node()) .dtype(output(i)->dtype()) .resize(output(i)->shape()); c_out[i] = tensor_to_c(cpu_out[i]); } } if (need_copy) { comp_node().sync(); m_desc->execute(m_desc.get(), c_inp.data(), c_out.data()); for (size_t i = 0; i < output().size(); ++i) output(i)->dev_tensor().copy_from_fixlayout(cpu_out[i]); } else { CompNodeEnv::from_comp_node(comp_node()) .cpu_env() .dispatch([this, c_inp, c_out]() mutable { m_desc->execute(m_desc.get(), c_inp.data(), c_out.data()); }); } } void ExternCOprRunner::add_input_layout_constraint() { for (auto i : input()) i->add_layout_constraint_contiguous(); } cg::OperatorNodeBase* ExternCOprRunner::make_placeholder( const SymbolVarArray& inputs, const TensorShapeArray& output_shapes, const char* name, const void* data, size_t data_len, const OperatorNodeConfig& config, const SmallVector<DType>& output_dtypes) { auto desc = PlaceholderMGBOprDesc::make(inputs.size(), name, output_shapes, output_dtypes, data, data_len); VarNodeArray var_inp(inputs.size()); for (size_t i = 0; i < inputs.size(); ++i) { var_inp[i] = inputs[i].node(); } auto dump_name = std::string{name}; return make_from_desc(dump_name, var_inp, desc, config); } cg::OperatorNodeBase* ExternCOprRunner::make_from_desc( std::string& name, const VarNodeArray& inputs, MGBOprDesc* desc, const OperatorNodeConfig& config) { auto desc_del = [](MGBOprDesc* ptr) { ptr->release(ptr); }; return make_from_desc_shared(name, inputs, {desc, desc_del}, config); } cg::OperatorNodeBase* ExternCOprRunner::make_from_desc_shared( std::string& name, const VarNodeArray& inputs, std::shared_ptr<MGBOprDesc> desc, const OperatorNodeConfig& config) { mgb_assert(!inputs.empty() && desc->nr_output); #define CHECK(name) mgb_assert(desc->name, #name " is not given"); MGB_OPR_DESC_FOREACH_MEM_FN(CHECK); #undef CHECK if (!config.name().valid()) const_cast<OperatorNodeConfig&>(config).name(name); auto opr = inputs[0]->owner_graph()->insert_opr( std::make_unique<ExternCOprRunner>(name, inputs, std::move(desc), config)); return &opr->cast_final_safe<ExternCOprRunner>(); } bool ExternCOprRunner::unregister_loader(const char* name) { return loader_map().erase(name); } void ExternCOprRunner::dump(OprDumpContext& ctx, const cg::OperatorNodeBase& opr_) { auto&& opr = opr_.cast_final<ExternCOprRunner>(); PlaceholderMGBOprDesc::dump(ctx, opr.m_desc.get()); } cg::OperatorNodeBase* ExternCOprRunner::load(OprLoadContext& ctx, const cg::VarNodeArray& inputs, const OperatorNodeConfig& config) { auto dump_name = ctx.load_buf_with_len(); auto name = dump_name; //! use to compat dump ExternCOprRunner with more info if (auto index = name.find(":")) name = name.substr(0, index); auto&& map = loader_map(); auto iter = map.find(name); mgb_assert(iter != map.end(), "can not find loader for ExternCOprRunner `%s'", name.c_str()); auto data = ctx.load_shared_buf_with_len(); auto desc = iter->second.first.create_desc(inputs.size(), data.data(), data.size()); if (auto trans = iter->second.second) { desc = trans(desc); } return make_from_desc(dump_name, inputs, desc, config); } cg::OperatorNodeBase* ExternCOprRunner::shallow_copy( const serialization::OprShallowCopyContext& ctx, const cg::OperatorNodeBase& opr_, const VarNodeArray& inputs, const OperatorNodeConfig& config) { auto&& opr = opr_.cast_final_safe<ExternCOprRunner>(); auto dump_name = opr.m_dump_name; return make_from_desc_shared(dump_name, inputs, opr.m_desc, config); } MGBTensorShape ExternCOprRunner::tensor_shape_to_c(const TensorShape& shape) { mgb_assert(shape.ndim <= MGB_TENSOR_MAX_NDIM, "shape ndim too large: %zu", shape.ndim); MGBTensorShape ret; ret.ndim = shape.ndim; for (size_t i = 0; i < shape.ndim; ++i) { ret.shape[i] = shape[i]; } return ret; } TensorShape ExternCOprRunner::tensor_shape_from_c(const MGBTensorShape& shape) { mgb_assert(shape.ndim <= TensorShape::MAX_NDIM, "shape ndim too large: %u", shape.ndim); TensorShape ret; ret.ndim = shape.ndim; for (size_t i = 0; i < shape.ndim; ++i) { ret.shape[i] = shape.shape[i]; } return ret; } void mgb::config_extern_c_opr_dynamic_param( std::unique_ptr<cg::AsyncExecutable>& func, std::shared_ptr<ExternCOprParam> param) { mgb_throw_if(!param, MegBrainError, "invalid ExternCOprParam param!!"); auto find_config_opr = false; auto cb = [&](cg::OperatorNodeBase* opr) { if (auto c_opr = opr->try_cast_final<opr::ExternCOprRunner>()) { auto dump_name = c_opr->get_dump_name().c_str(); if (!param->extern_c_opr_dump_name || !strncmp(param->extern_c_opr_dump_name, dump_name, strlen(dump_name))) { c_opr->set_param(param); find_config_opr = true; mgb_log_debug("config dynamic param for extern c opr: %s", dump_name); } } return !find_config_opr; }; func->iter_opr_seq(cb); mgb_throw_if(!find_config_opr, MegBrainError, "graph do not include a ExternCOprRunner opr or error config " "extern_c_opr_dump_name!!"); } /* ===================== public APIs ===================== */ const MGBExternCOprApi* mgb_get_extern_c_opr_api_versioned(int version) { auto unreg = [](const char* name) -> int { return ExternCOprRunner::unregister_loader(name); }; if (version == 0x23) { auto reg23 = [](const MGBOprLoader* loader) -> int { return loader_map() .insert({loader->name, {*loader, MGBOprDescV23::as_opr_desc}}) .second; }; static const MGBExternCOprApi ret = {reg23, unreg}; return &ret; } if (version != MGB_EXTERN_C_OPR_VERSION) return nullptr; auto reg = [](const MGBOprLoader* loader) -> int { return loader_map().insert({loader->name, {*loader, nullptr}}).second; }; static const MGBExternCOprApi ret = {reg, unreg}; return &ret; } // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
; A227400: Decimal expansion of 5/(3*phi^2) where phi is the golden ratio. ; Submitted by Jon Maiga ; 6,3,6,6,1,0,0,1,8,7,5,0,1,7,5,2,5,2,9,9,2,3,5,5,2,7,6,0,5,7,2,6,9,8,0,3,7,9,9,4,8,4,7,0,0,3,2,3,7,2,8,5,6,3,1,0,7,5,8,5,6,2,8,8,2,4,5,6,5,8,9,5,3,0,1,8,2,9,2,5,0,4,8,7,9,8 add $0,2 mov $2,1 mov $3,$0 mul $3,4 lpb $3 mul $1,$3 mul $2,$3 add $1,$2 div $1,$0 div $2,$0 add $2,$1 sub $3,1 lpe add $2,$1 div $1,6 mov $4,10 pow $4,$0 div $2,$4 div $1,$2 mod $1,10 mov $0,$1
; ; CPM Library ; ; Fputc_cons ; ; Stefano Bodrato - Apr. 2000 ; ; ; $Id: fputc_cons.asm,v 1.9 2016-05-15 20:15:45 dom Exp $ ; SECTION code_clib PUBLIC fputc_cons_native EXTERN __bdos ; ; Entry: hl = points to char ; .fputc_cons_native ld hl,2 add hl,sp ld d,0 ld a,(hl) ld e,a cp 12 ; FF (CLS) ? jr z,docls IF STANDARDESCAPECHARS cp 10 ; LF ? jr nz,nocrlf ld de,13 ld c,2 call __bdos ld de,10 ELSE cp 13 ; CR ? jr nz,nocrlf ld c,2 call __bdos ld de,10 ENDIF .nocrlf ld c,2 jp __bdos .docls ; This is the ANSI CLS call ld e,27 ld c,2 call __bdos ld e,'[' ld c,2 call __bdos ld e,'J' ld c,2 jp __bdos
; ASM source file created by SevenuP v1.20 ; SevenuP (C) Copyright 2002-2006 by Jaime Tejedor Gomez, aka Metalbrain ;GRAPHIC DATA: ;Pixel Size: ( 24, 32) ;Char Size: ( 3, 4) ;Sort Priorities: X char, Char line, Y char ;Data Outputted: Gfx ;Interleave: Sprite ;Mask: No barbaro_idle: DEFB 0, 31, 0, 0, 32,128, 0, 64 DEFB 64, 0,138, 64, 0, 15, 0, 1 DEFB 207, 64, 3,230, 32, 7,240, 64 DEFB 7,216,160, 7,221,128, 15,141 DEFB 32, 9, 2, 64, 30, 15, 0, 31 DEFB 31, 0, 15, 13, 0, 2, 66, 64 DEFB 0,240, 32, 0,112, 64, 0,112 DEFB 32, 0, 0, 0, 0, 64, 0, 0 DEFB 121, 64, 0,122,128, 0,121, 64 DEFB 0,242,128, 0, 0, 0, 0,242 DEFB 128, 0, 96, 0, 0,130, 0, 0 DEFB 196, 0, 1,170,128, 1,225, 64
; A037504: Base-3 digits are, in order, the first n terms of the periodic sequence with initial period 1,2,0. ; 1,5,15,46,140,420,1261,3785,11355,34066,102200,306600,919801,2759405,8278215,24834646,74503940,223511820,670535461,2011606385,6034819155,18104457466,54313372400,162940117200,488820351601,1466461054805,4399383164415,13198149493246,39594448479740,118783345439220,356350036317661,1069050108952985,3207150326858955 add $0,1 mov $2,6 lpb $0,1 sub $0,1 mul $2,3 mov $1,$2 add $1,3 mov $2,$1 div $1,13 lpe
push int32(6) push int32(7) mul assert int32(42) pop push int8(2) push int32(100000) mul assert int32(200000) pop push int16(3) push float(1.50) mul assert double(4.5) pop exit
//================================================================================================= /*! // \file src/mathtest/operations/smatdmatschur/MCaM4x4a.cpp // \brief Source file for the MCaM4x4a sparse matrix/dense matrix Schur product math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/operations/smatdmatschur/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MCaM4x4a'..." << std::endl; using blazetest::mathtest::TypeA; try { // Matrix type definitions using MCa = blaze::CompressedMatrix<TypeA>; using M4x4a = blaze::StaticMatrix<TypeA,4UL,4UL>; // Creator type definitions using CMCa = blazetest::Creator<MCa>; using CM4x4a = blazetest::Creator<M4x4a>; // Running the tests for( size_t i=0UL; i<=16UL; ++i ) { RUN_SMATDMATSCHUR_OPERATION_TEST( CMCa( 4UL, 4UL, i ), CM4x4a() ); } } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix Schur product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
; =============================================================== ; Stefano Bodrato ; aralbrec: accommodate nmos z80 bug ; =============================================================== ; ; unsigned char z80_get_int_state(void) ; ; Retrieve the current ei/di status. ; ; =============================================================== INCLUDE "config_private.inc" SECTION code_clib SECTION code_z80 PUBLIC asm_z80_get_int_state PUBLIC asm_cpu_get_int_state asm_z80_get_int_state: asm_cpu_get_int_state: ; exit : l = ei/di status ; ; uses : af, hl IF __CPU_R2KA__ | __CPU_R3K__ push ip dec sp pop hl ld l,h ret ELSE IF __CPU_8085__ rim ELSE IF __Z80 & __Z80_NMOS ; nmos z80 bug prevents use of "ld a,i" to gather IFF2 into p/v flag ; see http://www.z80.info/zip/ZilogProductSpecsDatabook129-143.pdf ; this is zilog's suggested solution, note status in carry flag not p/v ld hl,0 push hl pop hl ; zero written underneath SP scf ld a,i jp pe, continue ; carry set if ints enabled dec sp dec sp pop hl ; have a look at zero word underneath SP ld a,h or l jr z, continue ; int did not occur, ints are disabled, carry reset scf ; int occurred, set carry ELSE ; cmos z80 has no bug ld a,i ENDIF ENDIF continue: push af pop hl ret ENDIF
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Layer.h" #include "paddle/math/Matrix.h" #include "paddle/utils/Logging.h" #include "paddle/utils/Stat.h" namespace paddle { /** * A layer for sum-to-one normalization, * which is used in NEURAL TURING MACHINE. * \f[ * out[i] = \frac {in[i]} {\sum_{k=1}^N in[k]} * \f] * where \f$in\f$ is a (batchSize x dataDim) input vector, * and \f$out\f$ is a (batchSize x dataDim) output vector. * * The config file api is sum_to_one_norm_layer. */ class SumToOneNormLayer : public Layer { protected: /// reciprocalRowSum_ = \f$1 / \sum_{k=1}^N in[k]\f$ MatrixPtr reciprocalRowSum_; /// dotSum = output_.grad \f$.*\f$ output_.value MatrixPtr dotSum_; public: explicit SumToOneNormLayer(const LayerConfig& config) : Layer(config) {} bool init(const LayerMap& layerMap, const ParameterMap& parameterMap) override; void forward(PassType passType) override; void backward(const UpdateCallback& callback = nullptr) override; }; REGISTER_LAYER(sum_to_one_norm, SumToOneNormLayer); bool SumToOneNormLayer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { Layer::init(layerMap, parameterMap); CHECK_EQ(inputLayers_.size(), 1U); return true; } void SumToOneNormLayer::forward(PassType passType) { Layer::forward(passType); MatrixPtr inV = getInputValue(0); /* malloc memory for the output_ if necessary */ size_t batchSize = inV->getHeight(); size_t dataDim = getSize(); CHECK_EQ(dataDim, inV->getWidth()); { REGISTER_TIMER_INFO("FwResetTimer", getName().c_str()); resetOutput(batchSize, dataDim); } MatrixPtr outV = getOutputValue(); { REGISTER_TIMER_INFO("FwSumToOneNormTimer", getName().c_str()); Matrix::resizeOrCreate(reciprocalRowSum_, batchSize, 1, false, useGpu_); inV->rowSum(*reciprocalRowSum_); // todo: matrix checks CHECK_GT(reciprocalRowSum_->getMin(), 0.0); reciprocalRowSum_->scalarDiv(*reciprocalRowSum_, 1.0); // outV = inV * reciprocalRowSum outV->rowScale(0, *inV, *reciprocalRowSum_); } } void SumToOneNormLayer::backward(const UpdateCallback& callback) { MatrixPtr inV = getInputValue(0); MatrixPtr inG = getInputGrad(0); MatrixPtr outV = getOutputValue(); MatrixPtr outG = getOutputGrad(); size_t batchSize = inV->getHeight(); if (inG) { REGISTER_TIMER_INFO("BwSumToOneTimer", getName().c_str()); Matrix::resizeOrCreate(dotSum_, batchSize, 1, false, useGpu_); // dotSum = outG .* outV dotSum_->zeroMem(); dotSum_->rowDotMul(0, *outG, *outV); // inG += -1 * (dotSum / rowSum) dotSum_->dotMul(*dotSum_, *reciprocalRowSum_); inG->rowAdd(0, *inG, *dotSum_, -1.0); // inG += outG * (1/rowSum) inG->addRowScale(0, *outG, *reciprocalRowSum_); } } } // namespace paddle
/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the subset of IEEE 802.15.4 primitives required for Thread. */ #include "mac.hpp" #include <stdio.h> #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/random.hpp" #include "crypto/aes_ccm.hpp" #include "crypto/sha256.hpp" #include "mac/mac_frame.hpp" #include "radio/radio.hpp" #include "thread/link_quality.hpp" #include "thread/mle_router.hpp" #include "thread/thread_netif.hpp" #include "thread/topology.hpp" namespace ot { namespace Mac { const uint8_t Mac::sMode2Key[] = {0x78, 0x58, 0x16, 0x86, 0xfd, 0xb4, 0x58, 0x0f, 0xb0, 0x92, 0x54, 0x6a, 0xec, 0xbd, 0x15, 0x66}; const otExtAddress Mac::sMode2ExtAddress = { {0x35, 0x06, 0xfe, 0xb8, 0x23, 0xd4, 0x87, 0x12}, }; const otExtendedPanId Mac::sExtendedPanidInit = { {0xde, 0xad, 0x00, 0xbe, 0xef, 0x00, 0xca, 0xfe}, }; const char Mac::sNetworkNameInit[] = "OpenThread"; Mac::Mac(Instance &aInstance) : InstanceLocator(aInstance) , mEnabled(true) , mPendingActiveScan(false) , mPendingEnergyScan(false) , mPendingTransmitBeacon(false) , mPendingTransmitDataDirect(false) #if OPENTHREAD_FTD , mPendingTransmitDataIndirect(false) #endif , mPendingTransmitPoll(false) , mPendingTransmitOobFrame(false) , mPendingWaitingForData(false) , mShouldTxPollBeforeData(false) , mRxOnWhenIdle(false) , mPromiscuous(false) , mBeaconsEnabled(false) , mUsingTemporaryChannel(false) #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS , mShouldDelaySleep(false) , mDelayingSleep(false) #endif , mOperation(kOperationIdle) , mBeaconSequence(Random::NonCrypto::GetUint8()) , mDataSequence(Random::NonCrypto::GetUint8()) , mBroadcastTransmitCount(0) , mPanId(kPanIdBroadcast) , mPanChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL) , mRadioChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL) , mSupportedChannelMask(Get<Radio>().GetSupportedChannelMask()) , mNetworkName() , mScanChannel(Radio::kChannelMin) , mScanDuration(0) , mScanChannelMask() , mMaxFrameRetriesDirect(kDefaultMaxFrameRetriesDirect) #if OPENTHREAD_FTD , mMaxFrameRetriesIndirect(kDefaultMaxFrameRetriesIndirect) #endif , mActiveScanHandler(NULL) // Initialize `mActiveScanHandler` and `mEnergyScanHandler` union , mScanHandlerContext(NULL) , mSubMac(aInstance) , mOperationTask(aInstance, &Mac::HandleOperationTask, this) , mTimer(aInstance, &Mac::HandleTimer, this) , mOobFrame(NULL) , mKeyIdMode2FrameCounter(0) , mCcaSampleCount(0) #if OPENTHREAD_CONFIG_MAC_FILTER_ENABLE , mFilter() #endif { ExtAddress randomExtAddress; randomExtAddress.GenerateRandom(); mCcaSuccessRateTracker.Reset(); ResetCounters(); mExtendedPanId.Clear(); mSubMac.Enable(); SetExtendedPanId(static_cast<const ExtendedPanId &>(sExtendedPanidInit)); SetNetworkName(sNetworkNameInit); SetPanId(mPanId); SetExtAddress(randomExtAddress); SetShortAddress(GetShortAddress()); } otError Mac::ActiveScan(uint32_t aScanChannels, uint16_t aScanDuration, ActiveScanHandler aHandler, void *aContext) { otError error = OT_ERROR_NONE; VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); VerifyOrExit(!IsActiveScanInProgress() && !IsEnergyScanInProgress(), error = OT_ERROR_BUSY); mActiveScanHandler = aHandler; mScanHandlerContext = aContext; if (aScanDuration == 0) { aScanDuration = kScanDurationDefault; } Scan(kOperationActiveScan, aScanChannels, aScanDuration); exit: return error; } otError Mac::EnergyScan(uint32_t aScanChannels, uint16_t aScanDuration, EnergyScanHandler aHandler, void *aContext) { otError error = OT_ERROR_NONE; VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); VerifyOrExit(!IsActiveScanInProgress() && !IsEnergyScanInProgress(), error = OT_ERROR_BUSY); mEnergyScanHandler = aHandler; mScanHandlerContext = aContext; Scan(kOperationEnergyScan, aScanChannels, aScanDuration); exit: return error; } void Mac::Scan(Operation aScanOperation, uint32_t aScanChannels, uint16_t aScanDuration) { mScanDuration = aScanDuration; mScanChannel = ChannelMask::kChannelIteratorFirst; if (aScanChannels == 0) { aScanChannels = GetSupportedChannelMask().GetMask(); } mScanChannelMask.SetMask(aScanChannels); mScanChannelMask.Intersect(mSupportedChannelMask); StartOperation(aScanOperation); } bool Mac::IsInTransmitState(void) const { bool retval = false; switch (mOperation) { case kOperationTransmitDataDirect: #if OPENTHREAD_FTD case kOperationTransmitDataIndirect: #endif case kOperationTransmitBeacon: case kOperationTransmitPoll: case kOperationTransmitOutOfBandFrame: retval = true; break; case kOperationIdle: case kOperationActiveScan: case kOperationEnergyScan: case kOperationWaitingForData: retval = false; break; } return retval; } otError Mac::ConvertBeaconToActiveScanResult(const RxFrame *aBeaconFrame, ActiveScanResult &aResult) { otError error = OT_ERROR_NONE; Address address; const Beacon * beacon = NULL; const BeaconPayload *beaconPayload = NULL; uint16_t payloadLength; memset(&aResult, 0, sizeof(ActiveScanResult)); VerifyOrExit(aBeaconFrame != NULL, error = OT_ERROR_INVALID_ARGS); VerifyOrExit(aBeaconFrame->GetType() == Frame::kFcfFrameBeacon, error = OT_ERROR_PARSE); SuccessOrExit(error = aBeaconFrame->GetSrcAddr(address)); VerifyOrExit(address.IsExtended(), error = OT_ERROR_PARSE); aResult.mExtAddress = address.GetExtended(); aBeaconFrame->GetSrcPanId(aResult.mPanId); aResult.mChannel = aBeaconFrame->GetChannel(); aResult.mRssi = aBeaconFrame->GetRssi(); aResult.mLqi = aBeaconFrame->GetLqi(); payloadLength = aBeaconFrame->GetPayloadLength(); beacon = reinterpret_cast<const Beacon *>(aBeaconFrame->GetPayload()); beaconPayload = reinterpret_cast<const BeaconPayload *>(beacon->GetPayload()); if ((payloadLength >= (sizeof(*beacon) + sizeof(*beaconPayload))) && beacon->IsValid() && beaconPayload->IsValid()) { aResult.mVersion = beaconPayload->GetProtocolVersion(); aResult.mIsJoinable = beaconPayload->IsJoiningPermitted(); aResult.mIsNative = beaconPayload->IsNative(); static_cast<NetworkName &>(aResult.mNetworkName).Set(beaconPayload->GetNetworkName()); aResult.mExtendedPanId = beaconPayload->GetExtendedPanId(); } LogBeacon("Received", *beaconPayload); exit: return error; } otError Mac::UpdateScanChannel(void) { otError error; VerifyOrExit(mEnabled, error = OT_ERROR_ABORT); error = mScanChannelMask.GetNextChannel(mScanChannel); exit: return error; } void Mac::PerformActiveScan(void) { if (UpdateScanChannel() == OT_ERROR_NONE) { // If there are more channels to scan, send the beacon request. BeginTransmit(); } else { mSubMac.SetPanId(mPanId); FinishOperation(); ReportActiveScanResult(NULL); PerformNextOperation(); } } void Mac::ReportActiveScanResult(const RxFrame *aBeaconFrame) { VerifyOrExit(mActiveScanHandler != NULL); if (aBeaconFrame == NULL) { mActiveScanHandler(NULL, mScanHandlerContext); } else { ActiveScanResult result; SuccessOrExit(ConvertBeaconToActiveScanResult(aBeaconFrame, result)); mActiveScanHandler(&result, mScanHandlerContext); } exit: return; } void Mac::PerformEnergyScan(void) { otError error = OT_ERROR_NONE; SuccessOrExit(error = UpdateScanChannel()); if (mScanDuration == 0) { while (true) { mSubMac.Receive(mScanChannel); ReportEnergyScanResult(mSubMac.GetRssi()); SuccessOrExit(error = UpdateScanChannel()); } } else { error = mSubMac.EnergyScan(mScanChannel, mScanDuration); } exit: if (error != OT_ERROR_NONE) { FinishOperation(); if (mEnergyScanHandler != NULL) { mEnergyScanHandler(NULL, mScanHandlerContext); } PerformNextOperation(); } } void Mac::ReportEnergyScanResult(int8_t aRssi) { EnergyScanResult result; VerifyOrExit((mEnergyScanHandler != NULL) && (aRssi != kInvalidRssiValue)); result.mChannel = mScanChannel; result.mMaxRssi = aRssi; mEnergyScanHandler(&result, mScanHandlerContext); exit: return; } void Mac::EnergyScanDone(int8_t aEnergyScanMaxRssi) { ReportEnergyScanResult(aEnergyScanMaxRssi); PerformEnergyScan(); } void Mac::SetRxOnWhenIdle(bool aRxOnWhenIdle) { VerifyOrExit(mRxOnWhenIdle != aRxOnWhenIdle); mRxOnWhenIdle = aRxOnWhenIdle; // If the new value for `mRxOnWhenIdle` is `true` (i.e., radio should // remain in Rx while idle) we stop any ongoing or pending `WaitingForData` // operation (since this operation only applies to sleepy devices). if (mRxOnWhenIdle) { if (mPendingWaitingForData) { mTimer.Stop(); mPendingWaitingForData = false; } if (mOperation == kOperationWaitingForData) { mTimer.Stop(); FinishOperation(); mOperationTask.Post(); } #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS mDelayingSleep = false; mShouldDelaySleep = false; #endif } mSubMac.SetRxOnWhenBackoff(mRxOnWhenIdle || mPromiscuous); UpdateIdleMode(); exit: return; } otError Mac::SetPanChannel(uint8_t aChannel) { otError error = OT_ERROR_NONE; VerifyOrExit(mSupportedChannelMask.ContainsChannel(aChannel), error = OT_ERROR_INVALID_ARGS); SuccessOrExit(Get<Notifier>().Update(mPanChannel, aChannel, OT_CHANGED_THREAD_CHANNEL)); mCcaSuccessRateTracker.Reset(); VerifyOrExit(!mUsingTemporaryChannel); mRadioChannel = mPanChannel; UpdateIdleMode(); exit: return error; } otError Mac::SetTemporaryChannel(uint8_t aChannel) { otError error = OT_ERROR_NONE; VerifyOrExit(mSupportedChannelMask.ContainsChannel(aChannel), error = OT_ERROR_INVALID_ARGS); mUsingTemporaryChannel = true; mRadioChannel = aChannel; UpdateIdleMode(); exit: return error; } void Mac::ClearTemporaryChannel(void) { if (mUsingTemporaryChannel) { mUsingTemporaryChannel = false; mRadioChannel = mPanChannel; UpdateIdleMode(); } } void Mac::SetSupportedChannelMask(const ChannelMask &aMask) { ChannelMask newMask = aMask; newMask.Intersect(ChannelMask(Get<Radio>().GetSupportedChannelMask())); Get<Notifier>().Update(mSupportedChannelMask, newMask, OT_CHANGED_SUPPORTED_CHANNEL_MASK); } otError Mac::SetNetworkName(const char *aNameString) { // When setting Network Name from a string, we treat it as `Data` // with `kMaxSize + 1` chars. `NetworkName::Set(data)` will look // for null char in the data (within its given size) to calculate // the name's length and ensure that the name fits in `kMaxSize` // chars. The `+ 1` ensures that a `aNameString` with length // longer than `kMaxSize` is correctly rejected (returning error // `OT_ERROR_INVALID_ARGS`). NetworkName::Data data(aNameString, NetworkName::kMaxSize + 1); return SetNetworkName(data); } otError Mac::SetNetworkName(const NetworkName::Data &aName) { otError error = mNetworkName.Set(aName); if (error == OT_ERROR_ALREADY) { Get<Notifier>().SignalIfFirst(OT_CHANGED_THREAD_NETWORK_NAME); error = OT_ERROR_NONE; ExitNow(); } SuccessOrExit(error); Get<Notifier>().Signal(OT_CHANGED_THREAD_NETWORK_NAME); exit: return error; } void Mac::SetPanId(PanId aPanId) { SuccessOrExit(Get<Notifier>().Update(mPanId, aPanId, OT_CHANGED_THREAD_PANID)); mSubMac.SetPanId(mPanId); exit: return; } void Mac::SetExtendedPanId(const ExtendedPanId &aExtendedPanId) { Get<Notifier>().Update(mExtendedPanId, aExtendedPanId, OT_CHANGED_THREAD_EXT_PANID); } otError Mac::RequestDirectFrameTransmission(void) { otError error = OT_ERROR_NONE; VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); VerifyOrExit(!mPendingTransmitDataDirect && (mOperation != kOperationTransmitDataDirect), error = OT_ERROR_ALREADY); StartOperation(kOperationTransmitDataDirect); exit: return error; } #if OPENTHREAD_FTD otError Mac::RequestIndirectFrameTransmission(void) { otError error = OT_ERROR_NONE; VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); VerifyOrExit(!mPendingTransmitDataIndirect && (mOperation != kOperationTransmitDataIndirect), error = OT_ERROR_ALREADY); StartOperation(kOperationTransmitDataIndirect); exit: return error; } #endif otError Mac::RequestOutOfBandFrameTransmission(otRadioFrame *aOobFrame) { otError error = OT_ERROR_NONE; VerifyOrExit(aOobFrame != NULL, error = OT_ERROR_INVALID_ARGS); VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); VerifyOrExit(!mPendingTransmitOobFrame && (mOperation != kOperationTransmitOutOfBandFrame), error = OT_ERROR_ALREADY); mOobFrame = static_cast<TxFrame *>(aOobFrame); StartOperation(kOperationTransmitOutOfBandFrame); exit: return error; } otError Mac::RequestDataPollTransmission(void) { otError error = OT_ERROR_NONE; VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); VerifyOrExit(!mPendingTransmitPoll && (mOperation != kOperationTransmitPoll), error = OT_ERROR_ALREADY); // We ensure data frame and data poll tx requests are handled in the // order they are requested. So if we have a pending direct data frame // tx request, it should be sent before the poll frame. mShouldTxPollBeforeData = !mPendingTransmitDataDirect; StartOperation(kOperationTransmitPoll); exit: return error; } void Mac::UpdateIdleMode(void) { bool shouldSleep = !mRxOnWhenIdle && !mPromiscuous; VerifyOrExit(mOperation == kOperationIdle); #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS if (mShouldDelaySleep) { mTimer.Start(kSleepDelay); mShouldDelaySleep = false; mDelayingSleep = true; otLogDebgMac("Idle mode: Sleep delayed"); } if (mDelayingSleep) { shouldSleep = false; } #endif if (shouldSleep) { mSubMac.Sleep(); otLogDebgMac("Idle mode: Radio sleeping"); } else { mSubMac.Receive(mRadioChannel); otLogDebgMac("Idle mode: Radio receiving on channel %d", mRadioChannel); } exit: return; } void Mac::StartOperation(Operation aOperation) { if (aOperation != kOperationIdle) { otLogDebgMac("Request to start operation \"%s\"", OperationToString(aOperation)); #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS if (mDelayingSleep) { otLogDebgMac("Canceling sleep delay"); mTimer.Stop(); mDelayingSleep = false; mShouldDelaySleep = false; } #endif } switch (aOperation) { case kOperationIdle: break; case kOperationActiveScan: mPendingActiveScan = true; break; case kOperationEnergyScan: mPendingEnergyScan = true; break; case kOperationTransmitBeacon: mPendingTransmitBeacon = true; break; case kOperationTransmitDataDirect: mPendingTransmitDataDirect = true; break; #if OPENTHREAD_FTD case kOperationTransmitDataIndirect: mPendingTransmitDataIndirect = true; break; #endif case kOperationTransmitPoll: mPendingTransmitPoll = true; break; case kOperationWaitingForData: mPendingWaitingForData = true; break; case kOperationTransmitOutOfBandFrame: mPendingTransmitOobFrame = true; break; } if (mOperation == kOperationIdle) { mOperationTask.Post(); } } void Mac::HandleOperationTask(Tasklet &aTasklet) { aTasklet.GetOwner<Mac>().PerformNextOperation(); } void Mac::PerformNextOperation(void) { VerifyOrExit(mOperation == kOperationIdle); if (!mEnabled) { mPendingWaitingForData = false; mPendingTransmitOobFrame = false; mPendingActiveScan = false; mPendingEnergyScan = false; mPendingTransmitBeacon = false; mPendingTransmitDataDirect = false; #if OPENTHREAD_FTD mPendingTransmitDataIndirect = false; #endif mPendingTransmitPoll = false; mTimer.Stop(); #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS mDelayingSleep = false; mShouldDelaySleep = false; #endif ExitNow(); } // `WaitingForData` should be checked before any other pending // operations since radio should remain in receive mode after // a data poll ack indicating a pending frame from parent. if (mPendingWaitingForData) { mPendingWaitingForData = false; mOperation = kOperationWaitingForData; } else if (mPendingTransmitOobFrame) { mPendingTransmitOobFrame = false; mOperation = kOperationTransmitOutOfBandFrame; } else if (mPendingActiveScan) { mPendingActiveScan = false; mOperation = kOperationActiveScan; } else if (mPendingEnergyScan) { mPendingEnergyScan = false; mOperation = kOperationEnergyScan; } else if (mPendingTransmitBeacon) { mPendingTransmitBeacon = false; mOperation = kOperationTransmitBeacon; } #if OPENTHREAD_FTD else if (mPendingTransmitDataIndirect) { mPendingTransmitDataIndirect = false; mOperation = kOperationTransmitDataIndirect; } #endif else if (mPendingTransmitPoll && (!mPendingTransmitDataDirect || mShouldTxPollBeforeData)) { mPendingTransmitPoll = false; mOperation = kOperationTransmitPoll; } else if (mPendingTransmitDataDirect) { mPendingTransmitDataDirect = false; mOperation = kOperationTransmitDataDirect; if (mPendingTransmitPoll) { // Ensure that a pending "transmit poll" operation request // is prioritized over any future "transmit data" requests. mShouldTxPollBeforeData = true; } } if (mOperation != kOperationIdle) { otLogDebgMac("Starting operation \"%s\"", OperationToString(mOperation)); } switch (mOperation) { case kOperationIdle: UpdateIdleMode(); break; case kOperationActiveScan: PerformActiveScan(); break; case kOperationEnergyScan: PerformEnergyScan(); break; case kOperationTransmitBeacon: case kOperationTransmitDataDirect: #if OPENTHREAD_FTD case kOperationTransmitDataIndirect: #endif case kOperationTransmitPoll: case kOperationTransmitOutOfBandFrame: BeginTransmit(); break; case kOperationWaitingForData: mSubMac.Receive(mRadioChannel); break; } exit: return; } void Mac::FinishOperation(void) { otLogDebgMac("Finishing operation \"%s\"", OperationToString(mOperation)); mOperation = kOperationIdle; } otError Mac::PrepareDataRequest(TxFrame &aFrame) { otError error = OT_ERROR_NONE; Address src, dst; uint16_t fcf; SuccessOrExit(error = Get<DataPollSender>().GetPollDestinationAddress(dst)); VerifyOrExit(!dst.IsNone(), error = OT_ERROR_ABORT); fcf = Frame::kFcfFrameMacCmd | Frame::kFcfPanidCompression | Frame::kFcfFrameVersion2006 | Frame::kFcfAckRequest | Frame::kFcfSecurityEnabled; if (dst.IsExtended()) { fcf |= Frame::kFcfDstAddrExt | Frame::kFcfSrcAddrExt; src.SetExtended(GetExtAddress()); } else { fcf |= Frame::kFcfDstAddrShort | Frame::kFcfSrcAddrShort; src.SetShort(GetShortAddress()); } aFrame.InitMacHeader(fcf, Frame::kKeyIdMode1 | Frame::kSecEncMic32); aFrame.SetDstPanId(GetPanId()); aFrame.SetSrcAddr(src); aFrame.SetDstAddr(dst); aFrame.SetCommandId(Frame::kMacCmdDataRequest); exit: return error; } void Mac::PrepareBeaconRequest(TxFrame &aFrame) { uint16_t fcf = Frame::kFcfFrameMacCmd | Frame::kFcfDstAddrShort | Frame::kFcfSrcAddrNone; aFrame.InitMacHeader(fcf, Frame::kSecNone); aFrame.SetDstPanId(kShortAddrBroadcast); aFrame.SetDstAddr(kShortAddrBroadcast); aFrame.SetCommandId(Frame::kMacCmdBeaconRequest); otLogInfoMac("Sending Beacon Request"); } void Mac::PrepareBeacon(TxFrame &aFrame) { uint8_t beaconLength; uint16_t fcf; Beacon * beacon = NULL; BeaconPayload *beaconPayload = NULL; fcf = Frame::kFcfFrameBeacon | Frame::kFcfDstAddrNone | Frame::kFcfSrcAddrExt; aFrame.InitMacHeader(fcf, Frame::kSecNone); aFrame.SetSrcPanId(mPanId); aFrame.SetSrcAddr(GetExtAddress()); beacon = reinterpret_cast<Beacon *>(aFrame.GetPayload()); beacon->Init(); beaconLength = sizeof(*beacon); beaconPayload = reinterpret_cast<BeaconPayload *>(beacon->GetPayload()); if (Get<KeyManager>().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_BEACONS) { beaconPayload->Init(); if (IsJoinable()) { beaconPayload->SetJoiningPermitted(); } else { beaconPayload->ClearJoiningPermitted(); } beaconPayload->SetNetworkName(mNetworkName.GetAsData()); beaconPayload->SetExtendedPanId(mExtendedPanId); beaconLength += sizeof(*beaconPayload); } aFrame.SetPayloadLength(beaconLength); LogBeacon("Sending", *beaconPayload); } bool Mac::ShouldSendBeacon(void) const { bool shouldSend = false; VerifyOrExit(mEnabled); shouldSend = IsBeaconEnabled(); #if OPENTHREAD_CONFIG_MAC_BEACON_RSP_WHEN_JOINABLE_ENABLE if (!shouldSend) { // When `ENABLE_BEACON_RSP_WHEN_JOINABLE` feature is enabled, // the device should transmit IEEE 802.15.4 Beacons in response // to IEEE 802.15.4 Beacon Requests even while the device is not // router capable and detached (i.e., `IsBeaconEnabled()` is // false) but only if it is in joinable state (unsecure port // list is not empty). shouldSend = IsJoinable(); } #endif exit: return shouldSend; } bool Mac::IsJoinable(void) const { uint8_t numUnsecurePorts; Get<Ip6::Filter>().GetUnsecurePorts(numUnsecurePorts); return (numUnsecurePorts != 0); } void Mac::ProcessTransmitSecurity(TxFrame &aFrame, bool aProcessAesCcm) { KeyManager & keyManager = Get<KeyManager>(); uint8_t keyIdMode; const ExtAddress *extAddress = NULL; VerifyOrExit(aFrame.GetSecurityEnabled()); aFrame.GetKeyIdMode(keyIdMode); switch (keyIdMode) { case Frame::kKeyIdMode0: aFrame.SetAesKey(keyManager.GetKek().GetKey()); extAddress = &GetExtAddress(); if (!aFrame.IsARetransmission()) { aFrame.SetFrameCounter(keyManager.GetKekFrameCounter()); keyManager.IncrementKekFrameCounter(); } break; case Frame::kKeyIdMode1: aFrame.SetAesKey(keyManager.GetCurrentMacKey()); extAddress = &GetExtAddress(); // If the frame is marked as a retransmission, `MeshForwarder` which // prepared the frame should set the frame counter and key id to the // same values used in the earlier transmit attempt. For a new frame (not // a retransmission), we get a new frame counter and key id from the key // manager. if (!aFrame.IsARetransmission()) { aFrame.SetFrameCounter(keyManager.GetMacFrameCounter()); keyManager.IncrementMacFrameCounter(); aFrame.SetKeyId((keyManager.GetCurrentKeySequence() & 0x7f) + 1); } break; case Frame::kKeyIdMode2: { const uint8_t keySource[] = {0xff, 0xff, 0xff, 0xff}; aFrame.SetAesKey(sMode2Key); mKeyIdMode2FrameCounter++; aFrame.SetFrameCounter(mKeyIdMode2FrameCounter); aFrame.SetKeySource(keySource); aFrame.SetKeyId(0xff); extAddress = static_cast<const ExtAddress *>(&sMode2ExtAddress); break; } default: OT_ASSERT(false); break; } if (aProcessAesCcm) { aFrame.ProcessTransmitAesCcm(*extAddress); } exit: return; } void Mac::BeginTransmit(void) { otError error = OT_ERROR_NONE; bool applyTransmitSecurity = true; bool processTransmitAesCcm = true; TxFrame &sendFrame = mSubMac.GetTransmitFrame(); VerifyOrExit(mEnabled, error = OT_ERROR_ABORT); sendFrame.SetIsARetransmission(false); switch (mOperation) { case kOperationActiveScan: mSubMac.SetPanId(kPanIdBroadcast); sendFrame.SetChannel(mScanChannel); PrepareBeaconRequest(sendFrame); sendFrame.SetSequence(0); sendFrame.SetMaxCsmaBackoffs(kMaxCsmaBackoffsDirect); sendFrame.SetMaxFrameRetries(mMaxFrameRetriesDirect); break; case kOperationTransmitBeacon: sendFrame.SetChannel(mRadioChannel); PrepareBeacon(sendFrame); sendFrame.SetSequence(mBeaconSequence++); sendFrame.SetMaxCsmaBackoffs(kMaxCsmaBackoffsDirect); sendFrame.SetMaxFrameRetries(mMaxFrameRetriesDirect); break; case kOperationTransmitPoll: sendFrame.SetChannel(mRadioChannel); SuccessOrExit(error = PrepareDataRequest(sendFrame)); sendFrame.SetSequence(mDataSequence++); sendFrame.SetMaxCsmaBackoffs(kMaxCsmaBackoffsDirect); sendFrame.SetMaxFrameRetries(mMaxFrameRetriesDirect); break; case kOperationTransmitDataDirect: sendFrame.SetChannel(mRadioChannel); sendFrame.SetMaxCsmaBackoffs(kMaxCsmaBackoffsDirect); sendFrame.SetMaxFrameRetries(mMaxFrameRetriesDirect); SuccessOrExit(error = Get<MeshForwarder>().HandleFrameRequest(sendFrame)); sendFrame.SetSequence(mDataSequence++); break; #if OPENTHREAD_FTD case kOperationTransmitDataIndirect: sendFrame.SetChannel(mRadioChannel); sendFrame.SetMaxCsmaBackoffs(kMaxCsmaBackoffsIndirect); sendFrame.SetMaxFrameRetries(mMaxFrameRetriesIndirect); SuccessOrExit(error = Get<DataPollHandler>().HandleFrameRequest(sendFrame)); // If the frame is marked as a retransmission, then data sequence number is already set. if (!sendFrame.IsARetransmission()) { sendFrame.SetSequence(mDataSequence++); } break; #endif case kOperationTransmitOutOfBandFrame: sendFrame.CopyFrom(*mOobFrame); applyTransmitSecurity = false; break; default: OT_ASSERT(false); break; } #if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE { uint8_t timeIeOffset = GetTimeIeOffset(sendFrame); sendFrame.SetTimeIeOffset(timeIeOffset); if (timeIeOffset != 0) { // Transmit security will be processed after time IE content is updated. processTransmitAesCcm = false; sendFrame.SetTimeSyncSeq(Get<TimeSync>().GetTimeSyncSeq()); sendFrame.SetNetworkTimeOffset(Get<TimeSync>().GetNetworkTimeOffset()); } } #endif if (applyTransmitSecurity) { ProcessTransmitSecurity(sendFrame, processTransmitAesCcm); } mBroadcastTransmitCount = 0; #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS if (!mRxOnWhenIdle && !mPromiscuous) { mShouldDelaySleep = sendFrame.GetFramePending(); otLogDebgMac("Delay sleep for pending tx"); } #endif error = mSubMac.Send(); exit: if (error != OT_ERROR_NONE) { // If the sendFrame could not be prepared and the tx is being // aborted, we set the frame length to zero to mark it as empty. // The empty frame helps differentiate between an aborted tx due // to OpenThread itself not being able to prepare the frame, versus // the radio platform aborting the tx operation. sendFrame.SetLength(0); HandleTransmitDone(sendFrame, NULL, OT_ERROR_ABORT); } } void Mac::RecordCcaStatus(bool aCcaSuccess, uint8_t aChannel) { if (!aCcaSuccess) { mCounters.mTxErrCca++; } // Only track the CCA success rate for frame transmissions // on the PAN channel. if (aChannel == mPanChannel) { if (mCcaSampleCount < kMaxCcaSampleCount) { mCcaSampleCount++; } mCcaSuccessRateTracker.AddSample(aCcaSuccess, mCcaSampleCount); } } void Mac::RecordFrameTransmitStatus(const TxFrame &aFrame, const RxFrame *aAckFrame, otError aError, uint8_t aRetryCount, bool aWillRetx) { bool ackRequested = aFrame.GetAckRequest(); Address dstAddr; Neighbor *neighbor; VerifyOrExit(!aFrame.IsEmpty()); aFrame.GetDstAddr(dstAddr); neighbor = Get<Mle::MleRouter>().GetNeighbor(dstAddr); // Record frame transmission success/failure state (for a neighbor). if ((neighbor != NULL) && ackRequested) { bool frameTxSuccess = true; // CCA or abort errors are excluded from frame tx error // rate tracking, since when they occur, the frame is // not actually sent over the air. switch (aError) { case OT_ERROR_NO_ACK: frameTxSuccess = false; // Fall through case OT_ERROR_NONE: neighbor->GetLinkInfo().AddFrameTxStatus(frameTxSuccess); break; default: break; } } // Log frame transmission failure. if (aError != OT_ERROR_NONE) { LogFrameTxFailure(aFrame, aError, aRetryCount, aWillRetx); otDumpDebgMac("TX ERR", aFrame.GetHeader(), 16); if (aWillRetx) { mCounters.mTxRetry++; // Since this failed transmission will be retried by `SubMac` layer // there is no need to update any other MAC counter. MAC counters // are updated on the final transmission attempt. ExitNow(); } } // Update neighbor's RSSI link info from the received Ack. if ((aError == OT_ERROR_NONE) && ackRequested && (aAckFrame != NULL) && (neighbor != NULL)) { neighbor->GetLinkInfo().AddRss(aAckFrame->GetRssi()); } // Update MAC counters. mCounters.mTxTotal++; if (aError == OT_ERROR_ABORT) { mCounters.mTxErrAbort++; } if (aError == OT_ERROR_CHANNEL_ACCESS_FAILURE) { mCounters.mTxErrBusyChannel++; } if (ackRequested) { mCounters.mTxAckRequested++; if (aError == OT_ERROR_NONE) { mCounters.mTxAcked++; } } else { mCounters.mTxNoAckRequested++; } if (dstAddr.IsBroadcast()) { mCounters.mTxBroadcast++; } else { mCounters.mTxUnicast++; } exit: return; } void Mac::HandleTransmitDone(TxFrame &aFrame, RxFrame *aAckFrame, otError aError) { if (!aFrame.IsEmpty()) { Address dstAddr; // Determine whether to re-transmit a broadcast frame. aFrame.GetDstAddr(dstAddr); if (dstAddr.IsBroadcast()) { mBroadcastTransmitCount++; if (mBroadcastTransmitCount < kTxNumBcast) { mSubMac.Send(); ExitNow(); } mBroadcastTransmitCount = 0; } } // Determine next action based on current operation. switch (mOperation) { case kOperationActiveScan: mCounters.mTxBeaconRequest++; mTimer.Start(mScanDuration); break; case kOperationTransmitBeacon: mCounters.mTxBeacon++; FinishOperation(); PerformNextOperation(); break; case kOperationTransmitPoll: OT_ASSERT(aFrame.IsEmpty() || aFrame.GetAckRequest()); if ((aError == OT_ERROR_NONE) && (aAckFrame != NULL)) { bool framePending = aAckFrame->GetFramePending(); if (mEnabled && framePending) { mTimer.Start(kDataPollTimeout); StartOperation(kOperationWaitingForData); } otLogInfoMac("Sent data poll, fp:%s", framePending ? "yes" : "no"); } mCounters.mTxDataPoll++; FinishOperation(); Get<DataPollSender>().HandlePollSent(aFrame, aError); PerformNextOperation(); break; case kOperationTransmitDataDirect: mCounters.mTxData++; if (aError != OT_ERROR_NONE) { mCounters.mTxDirectMaxRetryExpiry++; } #if OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_ENABLE else if (mSubMac.GetTransmitRetries() < OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_MAX_SIZE_COUNT_DIRECT) { mRetryHistogram.mTxDirectRetrySuccess[mSubMac.GetTransmitRetries()]++; } #endif otDumpDebgMac("TX", aFrame.GetHeader(), aFrame.GetLength()); FinishOperation(); Get<MeshForwarder>().HandleSentFrame(aFrame, aError); #if OPENTHREAD_CONFIG_THREAD_VERSION >= OT_THREAD_VERSION_1_2 if (aError == OT_ERROR_NONE && Get<Mle::Mle>().GetParent().IsEnhancedKeepAliveSupported() && aFrame.GetSecurityEnabled() && aAckFrame != NULL) { Get<DataPollSender>().ProcessFrame(*aAckFrame); } #endif PerformNextOperation(); break; #if OPENTHREAD_FTD case kOperationTransmitDataIndirect: mCounters.mTxData++; if (aError != OT_ERROR_NONE) { mCounters.mTxIndirectMaxRetryExpiry++; } #if OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_ENABLE else if (mSubMac.GetTransmitRetries() < OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_MAX_SIZE_COUNT_INDIRECT) { mRetryHistogram.mTxIndirectRetrySuccess[mSubMac.GetTransmitRetries()]++; } #endif otDumpDebgMac("TX", aFrame.GetHeader(), aFrame.GetLength()); FinishOperation(); Get<DataPollHandler>().HandleSentFrame(aFrame, aError); PerformNextOperation(); break; #endif case kOperationTransmitOutOfBandFrame: FinishOperation(); PerformNextOperation(); break; default: OT_ASSERT(false); break; } exit: return; } void Mac::HandleTimer(Timer &aTimer) { aTimer.GetOwner<Mac>().HandleTimer(); } void Mac::HandleTimer(void) { switch (mOperation) { case kOperationActiveScan: PerformActiveScan(); break; case kOperationWaitingForData: otLogDebgMac("Data poll timeout"); FinishOperation(); Get<DataPollSender>().HandlePollTimeout(); PerformNextOperation(); break; #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS case kOperationIdle: if (mDelayingSleep) { otLogDebgMac("Sleep delay timeout expired"); mDelayingSleep = false; UpdateIdleMode(); } break; #endif default: OT_ASSERT(false); break; } } otError Mac::ProcessReceiveSecurity(RxFrame &aFrame, const Address &aSrcAddr, Neighbor *aNeighbor) { KeyManager & keyManager = Get<KeyManager>(); otError error = OT_ERROR_SECURITY; uint8_t securityLevel; uint8_t keyIdMode; uint32_t frameCounter; uint8_t nonce[KeyManager::kNonceSize]; uint8_t tag[Frame::kMaxMicSize]; uint8_t tagLength; uint8_t keyid; uint32_t keySequence = 0; const uint8_t * macKey; const ExtAddress *extAddress; Crypto::AesCcm aesCcm; VerifyOrExit(aFrame.GetSecurityEnabled(), error = OT_ERROR_NONE); aFrame.GetSecurityLevel(securityLevel); aFrame.GetFrameCounter(frameCounter); otLogDebgMac("Rx security - frame counter %u", frameCounter); aFrame.GetKeyIdMode(keyIdMode); switch (keyIdMode) { case Frame::kKeyIdMode0: macKey = keyManager.GetKek().GetKey(); VerifyOrExit(macKey != NULL); extAddress = &aSrcAddr.GetExtended(); break; case Frame::kKeyIdMode1: VerifyOrExit(aNeighbor != NULL); aFrame.GetKeyId(keyid); keyid--; if (keyid == (keyManager.GetCurrentKeySequence() & 0x7f)) { keySequence = keyManager.GetCurrentKeySequence(); macKey = keyManager.GetCurrentMacKey(); } else if (keyid == ((keyManager.GetCurrentKeySequence() - 1) & 0x7f)) { keySequence = keyManager.GetCurrentKeySequence() - 1; macKey = keyManager.GetTemporaryMacKey(keySequence); } else if (keyid == ((keyManager.GetCurrentKeySequence() + 1) & 0x7f)) { keySequence = keyManager.GetCurrentKeySequence() + 1; macKey = keyManager.GetTemporaryMacKey(keySequence); } else { ExitNow(); } // If the frame is from a neighbor not in valid state (e.g., it is from a child being // restored), skip the key sequence and frame counter checks but continue to verify // the tag/MIC. Such a frame is later filtered in `RxDoneTask` which only allows MAC // Data Request frames from a child being restored. if (aNeighbor->IsStateValid()) { VerifyOrExit(keySequence >= aNeighbor->GetKeySequence()); if (keySequence == aNeighbor->GetKeySequence()) { // If frame counter is one off, then frame is a duplicate. VerifyOrExit((frameCounter + 1) != aNeighbor->GetLinkFrameCounter(), error = OT_ERROR_DUPLICATED); VerifyOrExit(frameCounter >= aNeighbor->GetLinkFrameCounter()); } } extAddress = &aSrcAddr.GetExtended(); break; case Frame::kKeyIdMode2: macKey = sMode2Key; extAddress = static_cast<const ExtAddress *>(&sMode2ExtAddress); break; default: ExitNow(); break; } KeyManager::GenerateNonce(*extAddress, frameCounter, securityLevel, nonce); tagLength = aFrame.GetFooterLength() - Frame::kFcsSize; aesCcm.SetKey(macKey, 16); SuccessOrExit(aesCcm.Init(aFrame.GetHeaderLength(), aFrame.GetPayloadLength(), tagLength, nonce, sizeof(nonce))); aesCcm.Header(aFrame.GetHeader(), aFrame.GetHeaderLength()); #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION aesCcm.Payload(aFrame.GetPayload(), aFrame.GetPayload(), aFrame.GetPayloadLength(), false); #else // For fuzz tests, execute AES but do not alter the payload uint8_t fuzz[OT_RADIO_FRAME_MAX_SIZE]; aesCcm.Payload(fuzz, aFrame.GetPayload(), aFrame.GetPayloadLength(), false); #endif aesCcm.Finalize(tag, &tagLength); #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION VerifyOrExit(memcmp(tag, aFrame.GetFooter(), tagLength) == 0); #endif if ((keyIdMode == Frame::kKeyIdMode1) && aNeighbor->IsStateValid()) { if (aNeighbor->GetKeySequence() != keySequence) { aNeighbor->SetKeySequence(keySequence); aNeighbor->SetMleFrameCounter(0); } aNeighbor->SetLinkFrameCounter(frameCounter + 1); if (keySequence > keyManager.GetCurrentKeySequence()) { keyManager.SetCurrentKeySequence(keySequence); } } error = OT_ERROR_NONE; exit: return error; } void Mac::HandleReceivedFrame(RxFrame *aFrame, otError aError) { Address srcaddr; Address dstaddr; PanId panid; Neighbor *neighbor; otError error = aError; mCounters.mRxTotal++; SuccessOrExit(error); VerifyOrExit(aFrame != NULL, error = OT_ERROR_NO_FRAME_RECEIVED); VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); // Ensure we have a valid frame before attempting to read any contents of // the buffer received from the radio. SuccessOrExit(error = aFrame->ValidatePsdu()); aFrame->GetSrcAddr(srcaddr); aFrame->GetDstAddr(dstaddr); neighbor = Get<Mle::MleRouter>().GetNeighbor(srcaddr); // Destination Address Filtering switch (dstaddr.GetType()) { case Address::kTypeNone: break; case Address::kTypeShort: aFrame->GetDstPanId(panid); VerifyOrExit((panid == kShortAddrBroadcast || panid == mPanId) && ((mRxOnWhenIdle && dstaddr.IsBroadcast()) || dstaddr.GetShort() == GetShortAddress()), error = OT_ERROR_DESTINATION_ADDRESS_FILTERED); // Allow multicasts from neighbor routers if FTD if (neighbor == NULL && dstaddr.IsBroadcast() && Get<Mle::MleRouter>().IsFullThreadDevice()) { neighbor = Get<Mle::MleRouter>().GetRxOnlyNeighborRouter(srcaddr); } break; case Address::kTypeExtended: aFrame->GetDstPanId(panid); VerifyOrExit(panid == mPanId && dstaddr.GetExtended() == GetExtAddress(), error = OT_ERROR_DESTINATION_ADDRESS_FILTERED); break; } // Source Address Filtering switch (srcaddr.GetType()) { case Address::kTypeNone: break; case Address::kTypeShort: otLogDebgMac("Received frame from short address 0x%04x", srcaddr.GetShort()); VerifyOrExit(neighbor != NULL, error = OT_ERROR_UNKNOWN_NEIGHBOR); srcaddr.SetExtended(neighbor->GetExtAddress()); // Fall through case Address::kTypeExtended: // Duplicate Address Protection VerifyOrExit(srcaddr.GetExtended() != GetExtAddress(), error = OT_ERROR_INVALID_SOURCE_ADDRESS); #if OPENTHREAD_CONFIG_MAC_FILTER_ENABLE { int8_t fixedRss; SuccessOrExit(error = mFilter.Apply(srcaddr.GetExtended(), fixedRss)); if (fixedRss != Filter::kFixedRssDisabled) { aFrame->SetRssi(fixedRss); // Clear any previous link info to ensure the fixed RSSI // value takes effect quickly. if (neighbor != NULL) { neighbor->GetLinkInfo().Clear(); } } } #endif break; } if (dstaddr.IsBroadcast()) { mCounters.mRxBroadcast++; } else { mCounters.mRxUnicast++; } error = ProcessReceiveSecurity(*aFrame, srcaddr, neighbor); switch (error) { case OT_ERROR_DUPLICATED: // Allow a duplicate received frame pass, only if the // current operation is `kOperationWaitingForData` (i.e., // the sleepy device is waiting to receive a frame after // a data poll ack from parent indicating there is a // pending frame for it). This ensures that the sleepy // device goes to sleep faster and avoids a data poll // timeout. // // Note that `error` is checked again later after the // operation `kOperationWaitingForData` is processed // so the duplicate frame will not be passed to next // layer (`MeshForwarder`). VerifyOrExit(mOperation == kOperationWaitingForData); // Fall through case OT_ERROR_NONE: break; default: ExitNow(); } Get<DataPollSender>().ProcessFrame(*aFrame); if (neighbor != NULL) { neighbor->GetLinkInfo().AddRss(aFrame->GetRssi()); if (aFrame->GetSecurityEnabled()) { switch (neighbor->GetState()) { case Neighbor::kStateValid: break; case Neighbor::kStateRestored: case Neighbor::kStateChildUpdateRequest: // Only accept a "MAC Data Request" frame from a child being restored. VerifyOrExit(aFrame->IsDataRequestCommand(), error = OT_ERROR_DROP); break; default: ExitNow(error = OT_ERROR_UNKNOWN_NEIGHBOR); } #if OPENTHREAD_CONFIG_THREAD_VERSION >= OT_THREAD_VERSION_1_2 && OPENTHREAD_FTD // From Thread 1.2, MAC Data Frame can also act as keep-alive message if child supports if (aFrame->GetType() == Frame::kFcfFrameData && !neighbor->IsRxOnWhenIdle() && neighbor->IsEnhancedKeepAliveSupported()) { neighbor->SetLastHeard(TimerMilli::GetNow()); } #endif } } switch (mOperation) { case kOperationActiveScan: if (aFrame->GetType() == Frame::kFcfFrameBeacon) { mCounters.mRxBeacon++; ReportActiveScanResult(aFrame); ExitNow(); } // Fall through case kOperationEnergyScan: // We can possibly receive a data frame while either active or // energy scan is ongoing. We continue to process the frame only // if the current scan channel matches `mPanChannel`. VerifyOrExit(mScanChannel == mPanChannel, mCounters.mRxOther++); break; case kOperationWaitingForData: if (!dstaddr.IsNone()) { mTimer.Stop(); #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS if (!mRxOnWhenIdle && !mPromiscuous && aFrame->GetFramePending()) { mShouldDelaySleep = true; otLogDebgMac("Delay sleep for pending rx"); } #endif FinishOperation(); PerformNextOperation(); } SuccessOrExit(error); break; default: break; } switch (aFrame->GetType()) { case Frame::kFcfFrameMacCmd: if (HandleMacCommand(*aFrame)) // returns `true` when handled { ExitNow(error = OT_ERROR_NONE); } break; case Frame::kFcfFrameBeacon: mCounters.mRxBeacon++; break; case Frame::kFcfFrameData: mCounters.mRxData++; break; default: mCounters.mRxOther++; ExitNow(); } otDumpDebgMac("RX", aFrame->GetHeader(), aFrame->GetLength()); Get<MeshForwarder>().HandleReceivedFrame(*aFrame); exit: if (error != OT_ERROR_NONE) { LogFrameRxFailure(aFrame, error); switch (error) { case OT_ERROR_SECURITY: mCounters.mRxErrSec++; break; case OT_ERROR_FCS: mCounters.mRxErrFcs++; break; case OT_ERROR_NO_FRAME_RECEIVED: mCounters.mRxErrNoFrame++; break; case OT_ERROR_UNKNOWN_NEIGHBOR: mCounters.mRxErrUnknownNeighbor++; break; case OT_ERROR_INVALID_SOURCE_ADDRESS: mCounters.mRxErrInvalidSrcAddr++; break; case OT_ERROR_ADDRESS_FILTERED: mCounters.mRxAddressFiltered++; break; case OT_ERROR_DESTINATION_ADDRESS_FILTERED: mCounters.mRxDestAddrFiltered++; break; case OT_ERROR_DUPLICATED: mCounters.mRxDuplicated++; break; default: mCounters.mRxErrOther++; break; } } } bool Mac::HandleMacCommand(RxFrame &aFrame) { bool didHandle = false; uint8_t commandId; aFrame.GetCommandId(commandId); switch (commandId) { case Frame::kMacCmdBeaconRequest: mCounters.mRxBeaconRequest++; otLogInfoMac("Received Beacon Request"); if (ShouldSendBeacon()) { StartOperation(kOperationTransmitBeacon); } didHandle = true; break; case Frame::kMacCmdDataRequest: mCounters.mRxDataPoll++; #if OPENTHREAD_FTD Get<DataPollHandler>().HandleDataPoll(aFrame); didHandle = true; #endif break; default: mCounters.mRxOther++; break; } return didHandle; } void Mac::SetPromiscuous(bool aPromiscuous) { mPromiscuous = aPromiscuous; Get<Radio>().SetPromiscuous(aPromiscuous); #if OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS mDelayingSleep = false; mShouldDelaySleep = false; #endif mSubMac.SetRxOnWhenBackoff(mRxOnWhenIdle || mPromiscuous); UpdateIdleMode(); } #if OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_ENABLE const uint32_t *Mac::GetDirectRetrySuccessHistogram(uint8_t &aNumberOfEntries) { if (mMaxFrameRetriesDirect >= OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_MAX_SIZE_COUNT_DIRECT) { aNumberOfEntries = OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_MAX_SIZE_COUNT_DIRECT; } else { aNumberOfEntries = mMaxFrameRetriesDirect + 1; } return mRetryHistogram.mTxDirectRetrySuccess; } #if OPENTHREAD_FTD const uint32_t *Mac::GetIndirectRetrySuccessHistogram(uint8_t &aNumberOfEntries) { if (mMaxFrameRetriesIndirect >= OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_MAX_SIZE_COUNT_INDIRECT) { aNumberOfEntries = OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_MAX_SIZE_COUNT_INDIRECT; } else { aNumberOfEntries = mMaxFrameRetriesIndirect + 1; } return mRetryHistogram.mTxIndirectRetrySuccess; } #endif void Mac::ResetRetrySuccessHistogram() { memset(&mRetryHistogram, 0, sizeof(mRetryHistogram)); } #endif // OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_ENABLE // LCOV_EXCL_START #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) const char *Mac::OperationToString(Operation aOperation) { const char *retval = ""; switch (aOperation) { case kOperationIdle: retval = "Idle"; break; case kOperationActiveScan: retval = "ActiveScan"; break; case kOperationEnergyScan: retval = "EnergyScan"; break; case kOperationTransmitBeacon: retval = "TransmitBeacon"; break; case kOperationTransmitDataDirect: retval = "TransmitDataDirect"; break; #if OPENTHREAD_FTD case kOperationTransmitDataIndirect: retval = "TransmitDataIndirect"; break; #endif case kOperationTransmitPoll: retval = "TransmitPoll"; break; case kOperationWaitingForData: retval = "WaitingForData"; break; case kOperationTransmitOutOfBandFrame: retval = "TransmitOobFrame"; break; } return retval; } void Mac::LogFrameRxFailure(const RxFrame *aFrame, otError aError) const { otLogLevel logLevel; switch (aError) { case OT_ERROR_ABORT: case OT_ERROR_NO_FRAME_RECEIVED: case OT_ERROR_DESTINATION_ADDRESS_FILTERED: logLevel = OT_LOG_LEVEL_DEBG; break; default: logLevel = OT_LOG_LEVEL_INFO; break; } if (aFrame == NULL) { otLogMac(logLevel, "Frame rx failed, error:%s", otThreadErrorToString(aError)); } else { otLogMac(logLevel, "Frame rx failed, error:%s, %s", otThreadErrorToString(aError), aFrame->ToInfoString().AsCString()); } } void Mac::LogFrameTxFailure(const TxFrame &aFrame, otError aError, uint8_t aRetryCount, bool aWillRetx) const { uint8_t maxAttempts = aFrame.GetMaxFrameRetries() + 1; uint8_t curAttempt = aWillRetx ? (aRetryCount + 1) : maxAttempts; otLogInfoMac("Frame tx attempt %d/%d failed, error:%s, %s", curAttempt, maxAttempts, otThreadErrorToString(aError), aFrame.ToInfoString().AsCString()); } void Mac::LogBeacon(const char *aActionText, const BeaconPayload &aBeaconPayload) const { otLogInfoMac("%s Beacon, %s", aActionText, aBeaconPayload.ToInfoString().AsCString()); } #else // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) void Mac::LogFrameRxFailure(const RxFrame *, otError) const { } void Mac::LogBeacon(const char *, const BeaconPayload &) const { } void Mac::LogFrameTxFailure(const TxFrame &, otError, uint8_t, bool) const { } #endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) // LCOV_EXCL_STOP #if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE uint8_t Mac::GetTimeIeOffset(const Frame &aFrame) { uint8_t offset = 0; const uint8_t *base = aFrame.GetPsdu(); const uint8_t *cur = NULL; cur = reinterpret_cast<const uint8_t *>(aFrame.GetTimeIe()); VerifyOrExit(cur != NULL); cur += sizeof(VendorIeHeader); offset = static_cast<uint8_t>(cur - base); exit: return offset; } #endif } // namespace Mac } // namespace ot
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r14 push %r8 push %rcx push %rdi push %rsi // REPMOV lea addresses_normal+0x185e2, %rsi lea addresses_normal+0xc9b4, %rdi nop nop nop nop add $31824, %r11 mov $105, %rcx rep movsw nop nop nop nop nop cmp %rdi, %rdi // Faulty Load lea addresses_normal+0xc9b4, %r11 inc %r14 mov (%r11), %r13w lea oracles, %rsi and $0xff, %r13 shlq $12, %r13 mov (%rsi,%r13,1), %r13 pop %rsi pop %rdi pop %rcx pop %r8 pop %r14 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_normal'}, 'dst': {'same': True, 'congruent': 0, 'type': 'addresses_normal'}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} <gen_prepare_buffer> {'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 */
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; void append(ListNode **head, int val) { if ((*head) == nullptr) { (*head) = new ListNode(0); (*head)->val = val; (*head)->next = nullptr; return; } ListNode *pnode = (*head); while ((*head)->next) { (*head) = (*head)->next; } (*head)->next = new ListNode(0); (*head) = (*head)->next; (*head)->val = val; (*head)->next = nullptr; (*head) = pnode; } void print_node(ListNode *head) { while (head) { cout << head->val << " "; head = head->next; } cout << endl; } class Solution { public: void deleteNode(ListNode *node, ListNode *head) { ListNode *deleted_node = node->next; node->next = node->next->next; deleted_node->next = nullptr; delete deleted_node; } }; int main(int argc, char const *argv[]) { ListNode *head = nullptr; Solution *s = new Solution(); append(&head, 1); append(&head, 2); append(&head, 3); append(&head, 4); append(&head, 5); append(&head, 6); s->deleteNode(head->next->next); print_node(head); return 0; }
; void *bit_play_tritone_di(void *song) SECTION code_clib SECTION code_sound_bit PUBLIC _bit_play_tritone_di EXTERN _bit_play_tritone_di_fastcall _bit_play_tritone_di: pop af pop hl push hl push af jp _bit_play_tritone_di_fastcall
assume cs:code,ds:data data segment x db 10h,20h,30h,40h,50h,60h,70h n db $-x; key db 20h pass db "Element found at position:$" fail db "Element not found$" line db 0ah,0dh,"$" data ends code segment digit_2 PROC push bx push cx push dx mov bl,al mov cl,4 shr al,cl mov dl,al cmp dl, 9 jle add_30 add dl,7 add_30: add dl,30h mov ah,02 int 21h AND bl,0fh mov dl,bl cmp dl, 9 jle add_30_2 add dl,7 add_30_2: add dl,30h mov ah,02 int 21h pop dx pop cx pop bx ret digit_2 ENDP start: mov ax,data mov ds, ax ;cl=low,ch=high;dh=mid mov cl,0 mov ch,n lea bx, x;for use with xlat next: cmp cl,ch ja after_loop; mov dh, cl add dh,ch; dh = cl+ch shr dh,1; dh = mid mov al,dh xlat cmp al,key je found; jb change_low; a[mid]<key mov ch,dh; change_high dec ch jmp next; repeat change_low: mov cl,dh inc cl jmp next; repeat after_loop: lea dx,fail mov ah,9 int 21h jmp eprog found: mov ch,dh lea dx,pass mov ah,9 int 21h pop dx mov al,ch call digit_2 eprog: mov ah,4ch int 21h code ends end start
; A313259: Coordination sequence Gal.6.204.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; Submitted by Simon Strandgaard ; 1,4,9,15,20,25,31,36,41,47,52,56,60,65,71,76,81,87,92,97,103,108,112,116,121,127,132,137,143,148,153,159,164,168,172,177,183,188,193,199 mul $0,2 sub $2,$0 seq $0,315034 ; Coordination sequence Gal.6.323.2 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. mul $0,2 add $2,$1 mov $1,2 add $1,$0 mul $1,2 div $1,3 sub $1,1 mul $2,2 add $1,$2 add $1,$2 mov $0,$1
; A194698: a(n) = floor((n - 1)/12) - floor((n^2 - 1)/(24*n)). ; 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4 add $0,12 div $0,24
; Main driver for the Z80 tester. ; ; Copyright (C) 2012-2022 Patrik Rak (patrik@raxoft.cz) ; ; This source code is released under the MIT license, see included license.txt. org 0 halt ds 255 jp $8000 ds $7EFD main: di ; disable interrupts push iy ; preserve stuff needed by BASIC exx push hl call printinit ; init printing module call print ; print the header db "Z80 " testname db " test" db " - 2012 RAXOFT",13,13,0 ld bc,0 ; setup for test loop ld hl,testtable jr .entry .loop push hl ; call the test wrapper push bc call .test pop bc pop hl add a,b ; accumulate failures ld b,a inc c ; count number of tests .entry ld e,(hl) ; fetch test address inc hl ld d,(hl) inc hl ld a,d ; loop until we are done or e jr nz,.loop call print ; print result intro db 13,"Result: ",0 ld a,b ; no failures means success or a jr z,.ok call printdeca ; print number of failed tests call print db " of ",0 ld a,c call printdeca call print db " tests failed.",13,0 jr .done .ok call print ; print success message db "all tests passed.",13,0 .done pop hl ; return to BASIC exx pop iy ei halt ret .test push bc ; preserve number of failures ld a,c ; print test number call printdeca ld a,' ' call printchr ld hl,1+3*vecsize+4 ; print test name add hl,de call printhl pop bc ; restore number of failures ld a,(hl) ; see if some special check is needed cp 1 jr z,.incheck jr nc,.pass .failcheck or b ; some prior failure means do the test jr nz,.pass call print ; print that the test was skipped db "Skipped",13,0 ret ; return success .incheck xor a ; expected IN value means do the test in a,(0xfe) cp 0xbf ; %10111111 - just MIC bit is zero jr z,.pass ld e,a call print ; print the IN mismatch message db " FAILED",13 db "IN FE:",0 ld a,e call printhexa call print db "Expected:BF",13,0 inc a ; return failure ret .pass ld hl,1+3*vecsize ; store expected CRC address add hl,de push hl ex de,hl ; run the test with test vector at HL call test ld hl,data+3 ; store computed CRC ld (hl),e dec hl ld (hl),d dec hl ld (hl),c dec hl ld (hl),b pop de ; get expected CRC address ld b,4 ; compare CRCs call .cmp jr nz,.mismatch ; check for mismatch call print ; print success db " OK",13,0 ret ; return success .mismatch call print ; print mismatched and expected CRC db " FAILED",13 db "CRC:",0 call printcrc call print db " Expected:",0 ex de,hl call printcrc ld a,13 call printchr ld a,1 ; return failure ret .cmp push hl ; compare B bytes at HL and DE push de .cmploop ld a,(de) xor (hl) jr nz,.exit inc de inc hl djnz .cmploop .exit pop de pop hl ret include print.asm align 256 include idea.asm include tests.asm ; EOF ;
#include "QtGuiTester.h" QtGuiTester::QtGuiTester(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(exit())); } void QtGuiTester::exit() { QApplication::exit(); }
;--------------------------------------------------------- ; ; LZ4 block 68k depacker ; Written by Arnaud Carré ( @leonard_coder ) ; https://github.com/arnaud-carre/lz4-68k ; ; LZ4 technology by Yann Collet ( https://lz4.github.io/lz4/ ) ; ;--------------------------------------------------------- ; Normal version: 180 bytes ( 1.53 times faster than lz4_smallest.asm ) ; ; input: a0.l : packed buffer ; a1.l : output buffer ; d0.l : LZ4 packed block size (in bytes) ; ; output: none ; lz4_depack: lea 0(a0,d0.l),a4 ; packed buffer end moveq #0,d0 moveq #0,d2 moveq #0,d3 moveq #15,d4 bra.s .tokenLoop .lenOffset: move.b (a0)+,d1 ; read 16bits offset, little endian, unaligned move.b (a0)+,-(a7) move.w (a7)+,d3 move.b d1,d3 movea.l a1,a3 sub.l d3,a3 moveq #$f,d1 and.w d0,d1 cmp.b d4,d1 bne.s .small .readLen0: move.b (a0)+,d2 add.l d2,d1 not.b d2 beq.s .readLen0 addq.l #4,d1 .copy: move.b (a3)+,(a1)+ subq.l #1,d1 bne.s .copy bra .tokenLoop .small: add.w d1,d1 neg.w d1 jmp .copys(pc,d1.w) REPT 15 move.b (a3)+,(a1)+ ENDR .copys: move.b (a3)+,(a1)+ move.b (a3)+,(a1)+ move.b (a3)+,(a1)+ move.b (a3)+,(a1)+ .tokenLoop: move.b (a0)+,d0 move.l d0,d1 lsr.b #4,d1 beq.s .lenOffset cmp.b d4,d1 beq.s .readLen1 .litcopys: add.w d1,d1 neg.w d1 jmp .copys2(pc,d1.w) REPT 15 move.b (a0)+,(a1)+ ENDR .copys2: cmpa.l a0,a4 bne .lenOffset rts .readLen1: move.b (a0)+,d2 add.l d2,d1 not.b d2 beq.s .readLen1 .litcopy: move.b (a0)+,(a1)+ subq.l #1,d1 bne.s .litcopy ; end test is always done just after literals cmpa.l a0,a4 bne .lenOffset .over: rts ; end
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: ; ; ReadGdtr.Asm ; ; Abstract: ; ; AsmReadGdtr function ; ; Notes: ; ;------------------------------------------------------------------------------ SECTION .text ;------------------------------------------------------------------------------ ; VOID ; EFIAPI ; InternalX86ReadGdtr ( ; OUT IA32_DESCRIPTOR *Gdtr ; ); ;------------------------------------------------------------------------------ global ASM_PFX(InternalX86ReadGdtr) ASM_PFX(InternalX86ReadGdtr): mov eax, [esp + 4] sgdt [eax] ret
; A062158: a(n) = n^3 - n^2 + n - 1. ; -1,0,5,20,51,104,185,300,455,656,909,1220,1595,2040,2561,3164,3855,4640,5525,6516,7619,8840,10185,11660,13271,15024,16925,18980,21195,23576,26129,28860,31775,34880,38181,41684,45395,49320,53465,57836,62439,67280,72365,77700,83291,89144,95265,101660,108335,115296,122549,130100,137955,146120,154601,163404,172535,182000,191805,201956,212459,223320,234545,246140,258111,270464,283205,296340,309875,323816,338169,352940,368135,383760,399821,416324,433275,450680,468545,486876,505679,524960,544725 mov $1,$0 pow $0,2 add $0,1 sub $1,1 mul $0,$1
#include <cstdlib> #include <iostream> #include <array> #include <vector> #include <numeric> #include <mpl/mpl.hpp> template<typename I> void print_range(const char *const str, I i1, I i2) { std::cout << str; while (i1 != i2) { std::cout << (*i1); ++i1; std::cout << ((i1 != i2) ? ' ' : '\n'); } } int main() { const mpl::communicator &comm_world = mpl::environment::comm_world(); // run the program with two or more processes if (comm_world.size() < 2) return EXIT_FAILURE; const int n = 12; std::vector<int> v1(n), v2(n), v3(n), v4(n); mpl::contiguous_layout<int> l(n); // process 0 sends if (comm_world.rank() == 0) { // see MPI Standard for the semantics of standard send, buffered send, // synchronous send and ready send double x = 1.23456; mpl::irequest r(comm_world.isend(x, 1)); // send x to rank 1 via standard send r.wait(); // wait until send has finished ++x; { // create a buffer for buffered send, // memory will be freed on leaving the scope int size = {comm_world.bsend_size<decltype(x)>()}; mpl::bsend_buffer<> buff(size); r = comm_world.ibsend(x, 1); // send x to rank 1 via buffered send r.wait(); // wait until send has finished } ++x; r = comm_world.issend(x, 1); // send x to rank 1 via synchronous send r.wait(); // wait until send has finished ++x; r = comm_world.irsend(x, 1); // send x to rank 1 via ready send r.wait(); // wait until send has finished std::iota(v1.begin(), v1.end(), 0); std::iota(v2.begin(), v2.end(), 1); std::iota(v3.begin(), v3.end(), 2); std::iota(v4.begin(), v4.end(), 3); { // create a buffer for buffered send, // memory will be freed on leaving the scope int size = {comm_world.bsend_size(l)}; mpl::bsend_buffer<> buff(size); mpl::irequest_pool r; r.push(comm_world.isend(v1.data(), l, 1)); // send x to rank 1 via standard send r.push(comm_world.ibsend(v2.data(), l, 1)); // send x to rank 1 via buffered send r.push(comm_world.issend(v3.data(), l, 1)); // send x to rank 1 via synchronous send r.push(comm_world.irsend(v4.data(), l, 1)); // send x to rank 1 via ready send r.waitall(); // wait until all sends have finished } { mpl::irequest_pool r; r.push(comm_world.isend(v1.data(), l, 1)); // send v1 to rank 1 via standard send r.push(comm_world.ibsend(v2.data(), l, 1)); // send v2 to rank 1 via buffered send r.push(comm_world.issend(v3.data(), l, 1)); // send v3 to rank 1 via synchronous send r.push(comm_world.irsend(v4.data(), l, 1)); // send v4 to rank 1 via ready send std::array<mpl::irequest_pool::size_type, 4> finished; // memory to store indices of finished send operations while (true) { auto i = r.waitsome(finished.begin()); // wait until one ore more sends have finished if (i == finished.begin()) // there have been no pending sends break; // print indices of finished sends std::cout << "send finished : "; std::for_each(finished.begin(), i, [](mpl::irequest_pool::size_type j) { std::cout << j << ' '; }); std::cout << "\n"; } } } // process 1 receives if (comm_world.rank() == 1) { double x; mpl::irequest r(comm_world.irecv(x, 0)); // receive x from rank 0 r.wait(); // wait until receive has finished std::cout << "x = " << x << '\n'; r = comm_world.irecv(x, 0); // receive x from rank 0 r.wait(); // wait until receive has finished std::cout << "x = " << x << '\n'; r = comm_world.irecv(x, 0); // receive x from rank 0 r.wait(); // wait until receive has finished std::cout << "x = " << x << '\n'; r = comm_world.irecv(x, 0); // receive x from rank 0 r.wait(); // wait until receive has finished std::cout << "x = " << x << '\n'; { mpl::irequest_pool r; r.push(comm_world.irecv(v1.data(), l, 0)); // receive v1 from rank 0 r.push(comm_world.irecv(v2.data(), l, 0)); // receive v2 from rank 0 r.push(comm_world.irecv(v3.data(), l, 0)); // receive v3 from rank 0 r.push(comm_world.irecv(v4.data(), l, 0)); // receive v4 from rank 0 r.waitall(); // wait until all receives have finished print_range("v = ", v1.begin(), v1.end()); print_range("v = ", v2.begin(), v2.end()); print_range("v = ", v3.begin(), v3.end()); print_range("v = ", v4.begin(), v4.end()); } { mpl::irequest_pool r; r.push(comm_world.irecv(v1.data(), l, 0)); // receive v1 from rank 0 r.push(comm_world.irecv(v2.data(), l, 0)); // receive v2 from rank 0 r.push(comm_world.irecv(v3.data(), l, 0)); // receive v3 from rank 0 r.push(comm_world.irecv(v4.data(), l, 0)); // receive v4 from rank 0 while (true) { std::array<mpl::irequest_pool::size_type, 4> finished; // memory to store indices of finished recv operations auto i = r.waitsome(finished.begin()); // wait until one ore more receives have finished if (i == finished.begin()) // there have been no pending receives break; // print indices of finished receives std::cout << "recv finished : "; std::for_each(finished.begin(), i, [](mpl::irequest_pool::size_type j) { std::cout << j << ' '; }); std::cout << '\n'; } print_range("v = ", v1.begin(), v1.end()); print_range("v = ", v2.begin(), v2.end()); print_range("v = ", v3.begin(), v3.end()); print_range("v = ", v4.begin(), v4.end()); } } return EXIT_SUCCESS; }
// 8 BIT MULTIPLICATION: PRODUCT 16-BIT # ORG 2000H # BEGIN 2000H LHLD 2501 XCHG LDA 2503 LXI H,0000 MVI C,08 LOOP: DAD H RAL JNC AHEAD DAD D AHEAD: DCR C JNZ LOOP SHLD 2504 HLT # ORG 2501H // LSB OF MULTIPLICAND, MSB OF MULTIPLICAND,MULTIPLIER # DB 84H,00H,56H // ANSWER // AT ADDRESS 2504 - 58H, LSBs OF PRODUCT // AT ADDRESS 2505 - 2CH, MSB sOF PRODUCT
; link in extensions  1988 Tony Tebby Qjump section procs xdef ut_procdef xref ut_reassert include 'dev8_keys_qlv' ;+++ ; Links and re-asserts the procedures pointd to by a1. ; ; d2 s ; a1 c s pointer to procedure table ;--- ut_procdef movem.l a1/a2,-(sp) move.w sb.inipr,a2 jsr (a2) movem.l (sp)+,a1/a2 ; ut_reassert here !!! end
; A213772: Principal diagonal of the convolution array A213771. ; 1,11,42,106,215,381,616,932,1341,1855,2486,3246,4147,5201,6420,7816,9401,11187,13186,15410,17871,20581,23552,26796,30325,34151,38286,42742,47531,52665,58156,64016,70257,76891,83930,91386,99271,107597,116376,125620,135341,145551,156262,167486,179235,191521,204356,217752,231721,246275,261426,277186,293567,310581,328240,346556,365541,385207,405566,426630,448411,470921,494172,518176,542945,568491,594826,621962,649911,678685,708296,738756,770077,802271,835350,869326,904211,940017,976756,1014440 mul $0,4 mov $1,$0 add $1,3 pow $1,3 add $1,$0 mov $0,$1 div $0,32 add $0,1
SECTION code_clib SECTION code_fp_math48 PUBLIC asm_dfix8 EXTERN am48_dfix8 defc asm_dfix8 = am48_dfix8
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. #include "CorePrivatePCH.h" namespace UE4Delegates_Private { uint64 GNextID = 1; } uint64 FDelegateHandle::GenerateNewID() { // Just increment a counter to generate an ID. // On the next-to-impossible event that we wrap round to 0, reset back to 1, because we reserve 0 for null delegates. uint64 Result = UE4Delegates_Private::GNextID++; if (UE4Delegates_Private::GNextID == 0) { UE4Delegates_Private::GNextID = 1; } return Result; }
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "objectinspectormodel_p.h" #include <qlayout_widget_p.h> #include <layout_p.h> #include <qdesigner_propertycommand_p.h> #include <qdesigner_utils_p.h> #include <iconloader_p.h> #include <QtDesigner/QDesignerFormEditorInterface> #include <QtDesigner/QDesignerFormWindowInterface> #include <QtDesigner/QDesignerWidgetDataBaseInterface> #include <QtDesigner/QDesignerContainerExtension> #include <QtDesigner/QDesignerMetaDataBaseInterface> #include <QtDesigner/QExtensionManager> #include <QtWidgets/QLayout> #include <QtWidgets/QAction> #include <QtWidgets/QLayoutItem> #include <QtWidgets/QMenu> #include <QtWidgets/QButtonGroup> #include <QtCore/QSet> #include <QtCore/QDebug> #include <QtCore/QCoreApplication> #include <algorithm> QT_BEGIN_NAMESPACE namespace { enum { DataRole = 1000 }; } static inline QObject *objectOfItem(const QStandardItem *item) { return qvariant_cast<QObject *>(item->data(DataRole)); } static bool sortEntry(const QObject *a, const QObject *b) { return a->objectName() < b->objectName(); } static bool sameIcon(const QIcon &i1, const QIcon &i2) { if (i1.isNull() && i2.isNull()) return true; if (i1.isNull() != i2.isNull()) return false; return i1.cacheKey() == i2.cacheKey(); } static inline bool isNameColumnEditable(const QObject *) { return true; } static qdesigner_internal::ObjectData::StandardItemList createModelRow(const QObject *o) { qdesigner_internal::ObjectData::StandardItemList rc; const Qt::ItemFlags baseFlags = Qt::ItemIsSelectable|Qt::ItemIsDropEnabled|Qt::ItemIsEnabled; for (int i = 0; i < qdesigner_internal::ObjectInspectorModel::NumColumns; i++) { QStandardItem *item = new QStandardItem; Qt::ItemFlags flags = baseFlags; if (i == qdesigner_internal::ObjectInspectorModel::ObjectNameColumn && isNameColumnEditable(o)) flags |= Qt::ItemIsEditable; item->setFlags(flags); rc += item; } return rc; } static inline bool isQLayoutWidget(const QObject *o) { return o->metaObject() == &QLayoutWidget::staticMetaObject; } namespace qdesigner_internal { // context kept while building a model, just there to reduce string allocations struct ModelRecursionContext { explicit ModelRecursionContext(QDesignerFormEditorInterface *core, const QString &sepName); const QString designerPrefix; const QString separator; QDesignerFormEditorInterface *core; const QDesignerWidgetDataBaseInterface *db; const QDesignerMetaDataBaseInterface *mdb; }; ModelRecursionContext::ModelRecursionContext(QDesignerFormEditorInterface *c, const QString &sepName) : designerPrefix(QStringLiteral("QDesigner")), separator(sepName), core(c), db(c->widgetDataBase()), mdb(c->metaDataBase()) { } // ------------ ObjectData/ ObjectModel: // Whenever the selection changes, ObjectInspector::setFormWindow is // called. To avoid rebuilding the tree every time (loosing expanded state) // a model is first built from the object tree by recursion. // As a tree is difficult to represent, a flat list of entries (ObjectData) // containing object and parent object is used. // ObjectData has an overloaded operator== that compares the object pointers. // Structural changes which cause a rebuild can be detected by // comparing the lists of ObjectData. If it is the same, only the item data (class name [changed by promotion], // object name and icon) are checked and the existing items are updated. ObjectData::ObjectData() : m_parent(0), m_object(0), m_type(Object), m_managedLayoutType(LayoutInfo::NoLayout) { } ObjectData::ObjectData(QObject *parent, QObject *object, const ModelRecursionContext &ctx) : m_parent(parent), m_object(object), m_type(Object), m_className(QLatin1String(object->metaObject()->className())), m_objectName(object->objectName()), m_managedLayoutType(LayoutInfo::NoLayout) { // 1) set entry if (object->isWidgetType()) { initWidget(static_cast<QWidget*>(object), ctx); } else { initObject(ctx); } if (m_className.startsWith(ctx.designerPrefix)) m_className.remove(1, ctx.designerPrefix.size() - 1); } void ObjectData::initObject(const ModelRecursionContext &ctx) { // Check objects: Action? if (const QAction *act = qobject_cast<const QAction*>(m_object)) { if (act->isSeparator()) { // separator is reserved m_objectName = ctx.separator; m_type = SeparatorAction; } else { m_type = Action; } m_classIcon = act->icon(); } else { m_type = Object; } } void ObjectData::initWidget(QWidget *w, const ModelRecursionContext &ctx) { // Check for extension container, QLayoutwidget, or normal container bool isContainer = false; if (const QDesignerWidgetDataBaseItemInterface *widgetItem = ctx.db->item(ctx.db->indexOfObject(w, true))) { m_classIcon = widgetItem->icon(); m_className = widgetItem->name(); isContainer = widgetItem->isContainer(); } // We might encounter temporary states with no layouts when re-layouting. // Just default to Widget handling for the moment. if (isQLayoutWidget(w)) { if (const QLayout *layout = w->layout()) { m_type = LayoutWidget; m_managedLayoutType = LayoutInfo::layoutType(ctx.core, layout); m_className = QLatin1String(layout->metaObject()->className()); m_objectName = layout->objectName(); } return; } if (qt_extension<QDesignerContainerExtension*>(ctx.core->extensionManager(), w)) { m_type = ExtensionContainer; return; } if (isContainer) { m_type = LayoutableContainer; m_managedLayoutType = LayoutInfo::managedLayoutType(ctx.core, w); return; } m_type = ChildWidget; } bool ObjectData::equals(const ObjectData & me) const { return m_parent == me.m_parent && m_object == me.m_object; } unsigned ObjectData::compare(const ObjectData & rhs) const { unsigned rc = 0; if (m_className != rhs.m_className) rc |= ClassNameChanged; if (m_objectName != rhs.m_objectName) rc |= ObjectNameChanged; if (!sameIcon(m_classIcon, rhs.m_classIcon)) rc |= ClassIconChanged; if (m_type != rhs.m_type) rc |= TypeChanged; if (m_managedLayoutType != rhs.m_managedLayoutType) rc |= LayoutTypeChanged; return rc; } void ObjectData::setItemsDisplayData(const StandardItemList &row, const ObjectInspectorIcons &icons, unsigned mask) const { if (mask & ObjectNameChanged) row[ObjectInspectorModel::ObjectNameColumn]->setText(m_objectName); if (mask & ClassNameChanged) { row[ObjectInspectorModel::ClassNameColumn]->setText(m_className); row[ObjectInspectorModel::ClassNameColumn]->setToolTip(m_className); } // Set a layout icon only for containers. Note that QLayoutWidget don't have // real class icons if (mask & (ClassIconChanged|TypeChanged|LayoutTypeChanged)) { switch (m_type) { case LayoutWidget: row[ObjectInspectorModel::ObjectNameColumn]->setIcon(icons.layoutIcons[m_managedLayoutType]); row[ObjectInspectorModel::ClassNameColumn]->setIcon(icons.layoutIcons[m_managedLayoutType]); break; case LayoutableContainer: row[ObjectInspectorModel::ObjectNameColumn]->setIcon(icons.layoutIcons[m_managedLayoutType]); row[ObjectInspectorModel::ClassNameColumn]->setIcon(m_classIcon); break; default: row[ObjectInspectorModel::ObjectNameColumn]->setIcon(QIcon()); row[ObjectInspectorModel::ClassNameColumn]->setIcon(m_classIcon); break; } } } void ObjectData::setItems(const StandardItemList &row, const ObjectInspectorIcons &icons) const { const QVariant object = QVariant::fromValue(m_object); row[ObjectInspectorModel::ObjectNameColumn]->setData(object, DataRole); row[ObjectInspectorModel::ClassNameColumn]->setData(object, DataRole); setItemsDisplayData(row, icons, ClassNameChanged|ObjectNameChanged|ClassIconChanged|TypeChanged|LayoutTypeChanged); } typedef QList<ObjectData> ObjectModel; // Recursive routine that creates the model by traversing the form window object tree. void createModelRecursion(const QDesignerFormWindowInterface *fwi, QObject *parent, QObject *object, ObjectModel &model, const ModelRecursionContext &ctx) { typedef QList<QButtonGroup *> ButtonGroupList; typedef QList<QAction *> ActionList; // 1) Create entry const ObjectData entry(parent, object, ctx); model.push_back(entry); // 2) recurse over widget children via container extension or children list const QDesignerContainerExtension *containerExtension = 0; if (entry.type() == ObjectData::ExtensionContainer) { containerExtension = qt_extension<QDesignerContainerExtension*>(fwi->core()->extensionManager(), object); Q_ASSERT(containerExtension); const int count = containerExtension->count(); for (int i=0; i < count; ++i) { QObject *page = containerExtension->widget(i); Q_ASSERT(page != 0); createModelRecursion(fwi, object, page, model, ctx); } } QObjectList children = object->children(); if (!children.empty()) { ButtonGroupList buttonGroups; std::sort(children.begin(), children.end(), sortEntry); const QObjectList::const_iterator cend = children.constEnd(); for (QObjectList::const_iterator it = children.constBegin(); it != cend; ++it) { // Managed child widgets unless we had a container extension if ((*it)->isWidgetType()) { if (!containerExtension) { QWidget *widget = qobject_cast<QWidget*>(*it); if (fwi->isManaged(widget)) createModelRecursion(fwi, object, widget, model, ctx); } } else { if (ctx.mdb->item(*it)) { if (QButtonGroup *bg = qobject_cast<QButtonGroup*>(*it)) buttonGroups.push_back(bg); } // Has MetaDataBase entry } } // Add button groups if (!buttonGroups.empty()) { const ButtonGroupList::const_iterator bgcend = buttonGroups.constEnd(); for (ButtonGroupList::const_iterator bgit = buttonGroups.constBegin(); bgit != bgcend; ++bgit) createModelRecursion(fwi, object, *bgit, model, ctx); } } // has children if (object->isWidgetType()) { // Add actions const ActionList actions = static_cast<QWidget*>(object)->actions(); if (!actions.empty()) { const ActionList::const_iterator cend = actions.constEnd(); for (ActionList::const_iterator it = actions.constBegin(); it != cend; ++it) if (ctx.mdb->item(*it)) { QAction *action = *it; QObject *obj = action; if (action->menu()) obj = action->menu(); createModelRecursion(fwi, object, obj, model, ctx); } } } } // ------------ ObjectInspectorModel ObjectInspectorModel::ObjectInspectorModel(QObject *parent) : QStandardItemModel(0, NumColumns, parent) { QStringList headers; headers += QCoreApplication::translate("ObjectInspectorModel", "Object"); headers += QCoreApplication::translate("ObjectInspectorModel", "Class"); Q_ASSERT(headers.size() == NumColumns); setColumnCount(NumColumns); setHorizontalHeaderLabels(headers); // Icons m_icons.layoutIcons[LayoutInfo::NoLayout] = createIconSet(QStringLiteral("editbreaklayout.png")); m_icons.layoutIcons[LayoutInfo::HSplitter] = createIconSet(QStringLiteral("edithlayoutsplit.png")); m_icons.layoutIcons[LayoutInfo::VSplitter] = createIconSet(QStringLiteral("editvlayoutsplit.png")); m_icons.layoutIcons[LayoutInfo::HBox] = createIconSet(QStringLiteral("edithlayout.png")); m_icons.layoutIcons[LayoutInfo::VBox] = createIconSet(QStringLiteral("editvlayout.png")); m_icons.layoutIcons[LayoutInfo::Grid] = createIconSet(QStringLiteral("editgrid.png")); m_icons.layoutIcons[LayoutInfo::Form] = createIconSet(QStringLiteral("editform.png")); } void ObjectInspectorModel::clearItems() { beginResetModel(); m_objectIndexMultiMap.clear(); m_model.clear(); endResetModel(); // force editors to be closed in views removeRow(0); } ObjectInspectorModel::UpdateResult ObjectInspectorModel::update(QDesignerFormWindowInterface *fw) { QWidget *mainContainer = fw ? fw->mainContainer() : static_cast<QWidget*>(0); if (!mainContainer) { clearItems(); m_formWindow = 0; return NoForm; } m_formWindow = fw; // Build new model and compare to previous one. If the structure is // identical, just update, else rebuild ObjectModel newModel; static const QString separator = QCoreApplication::translate("ObjectInspectorModel", "separator"); const ModelRecursionContext ctx(fw->core(), separator); createModelRecursion(fw, 0, mainContainer, newModel, ctx); if (newModel == m_model) { updateItemContents(m_model, newModel); return Updated; } rebuild(newModel); m_model = newModel; return Rebuilt; } QObject *ObjectInspectorModel::objectAt(const QModelIndex &index) const { if (index.isValid()) if (const QStandardItem *item = itemFromIndex(index)) return objectOfItem(item); return 0; } // Missing Qt API: get a row ObjectInspectorModel::StandardItemList ObjectInspectorModel::rowAt(QModelIndex index) const { StandardItemList rc; while (true) { rc += itemFromIndex(index); const int nextColumn = index.column() + 1; if (nextColumn >= NumColumns) break; index = index.sibling(index.row(), nextColumn); } return rc; } // Rebuild the tree in case the model has completely changed. void ObjectInspectorModel::rebuild(const ObjectModel &newModel) { clearItems(); if (newModel.empty()) return; const ObjectModel::const_iterator mcend = newModel.constEnd(); ObjectModel::const_iterator it = newModel.constBegin(); // Set up root element StandardItemList rootRow = createModelRow(it->object()); it->setItems(rootRow, m_icons); appendRow(rootRow); m_objectIndexMultiMap.insert(it->object(), indexFromItem(rootRow.front())); for (++it; it != mcend; ++it) { // Add to parent item, found via map const QModelIndex parentIndex = m_objectIndexMultiMap.value(it->parent(), QModelIndex()); Q_ASSERT(parentIndex.isValid()); QStandardItem *parentItem = itemFromIndex(parentIndex); StandardItemList row = createModelRow(it->object()); it->setItems(row, m_icons); parentItem->appendRow(row); m_objectIndexMultiMap.insert(it->object(), indexFromItem(row.front())); } } // Update item data in case the model has the same structure void ObjectInspectorModel::updateItemContents(ObjectModel &oldModel, const ObjectModel &newModel) { // Change text and icon. Keep a set of changed object // as for example actions might occur several times in the tree. typedef QSet<QObject *> QObjectSet; QObjectSet changedObjects; const int size = newModel.size(); Q_ASSERT(oldModel.size() == size); for (int i = 0; i < size; i++) { const ObjectData &newEntry = newModel[i]; ObjectData &entry = oldModel[i]; // Has some data changed? if (const unsigned changedMask = entry.compare(newEntry)) { entry = newEntry; QObject * o = entry.object(); if (!changedObjects.contains(o)) { changedObjects.insert(o); const QModelIndexList indexes = m_objectIndexMultiMap.values(o); for (const QModelIndex &index : indexes) entry.setItemsDisplayData(rowAt(index), m_icons, changedMask); } } } } QVariant ObjectInspectorModel::data(const QModelIndex &index, int role) const { const QVariant rc = QStandardItemModel::data(index, role); // Return <noname> if the string is empty for the display role // only (else, editing starts with <noname>). if (role == Qt::DisplayRole && rc.type() == QVariant::String) { const QString s = rc.toString(); if (s.isEmpty()) { static const QString noName = QCoreApplication::translate("ObjectInspectorModel", "<noname>"); return QVariant(noName); } } return rc; } bool ObjectInspectorModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role != Qt::EditRole || !m_formWindow) return false; QObject *object = objectAt(index); if (!object) return false; // Is this a layout widget? const QString nameProperty = isQLayoutWidget(object) ? QStringLiteral("layoutName") : QStringLiteral("objectName"); m_formWindow->commandHistory()->push(createTextPropertyCommand(nameProperty, value.toString(), object, m_formWindow)); return true; } } QT_END_NAMESPACE
//base56 encoding and decoding routines: //names are stored at $7e:2b00+, and each name is eight bytes long. //this is not long enough for "Salamander", "Ice Dragon", "Thunderhawk", and "Fahrenheit" //rather than attempting to migrate the names in both WRAM and SRAM, base56 is used. //this allows for the storage of 11 characters in 8 bytes of space, with the downside //that it limits the range of available characters to [A-Z][a-z][.- ] and a terminal marker. //it is very difficult to perform 64-bit multiplication and division, and so pre-generated //lookup tables are used to accelerate the process. the general idea is that multiplication //and division by 8 is trivial, and then multiplication and division by 7 can be done: 8*7=56 namespace base56 { seek(codeCursor) //encoded <= base56.encode(encoding) function encode { variable(16, input) //88-bit decoded string variable(16, output) //64-bit encoded string enter; ldb #$31 //allow 16-bit access to variables stz.w output+0; stz.w output+2; stz.w output+4; stz.w output+6 //initialize output ldx.w #10; ldy.w #0 loop: { phx; tya; xba; lsr #2; pha //S <= Y * 64 tya; xba; asl //A <= Y * 512 sub $01,s; sta $01,s //S <= A - S lda.w input,x; and #$00ff //A <= character[X] jsl encodeCharacter //A <= toBase56[X] asl #3; add $01,s; tax; pla //X <= S + A * 8 //output <= output * 56 + A lda.w output+0; add products+0,x; sta.w output+0 lda.w output+2; adc products+2,x; sta.w output+2 lda.w output+4; adc products+4,x; sta.w output+4 lda.w output+6; adc products+6,x; sta.w output+6 plx; iny; dex; bpl loop } //store string terminator lda #$ffff; sta.w output+8 leave; rtl function encodeCharacter { cmp.w #'-'; bne +; lda #$0035; rtl; + //encode '-' cmp.w #'.'; bne +; lda #$0036; rtl; + //encode '.' cmp.w #'$'; bne +; lda #$0037; rtl; + //encode terminal character.decode(); rtl //encode 'A-Z' and 'a-z' } } //decoded <= base56.decode(decoding) function decode { variable(16, input) //64-bit encoded string variable(16, output) //88-bit decoded string variable( 4, multiplier) //31-bit base7 enter; ldb #$31 //allow 16-bit access to variables //multiplier <= decoding >> 32 lda.w input+4; sta.w multiplier+0 lda.w input+6; sta.w multiplier+2 //copy low 3-bits of each character to output buffer lda.w input+0; asl #2; and #$0700; sta.w output+8-1 lda.w input+1; asl #1; and #$0700; sta.w output+5-1 lda.w input+3; asl #2; and #$0700; sta.w output+0-1 //output[-1] is input[15] (unused padding) sep #$20 lda.w input+0; pha; and #$07; sta.w output+10; pla; lsr #3; and #$07; sta.w output+9 lda.w input+1; lsr #1; pha; and #$07; sta.w output+ 7; pla; lsr #3; and #$07; sta.w output+6 lda.w input+2; lsr #2; pha; and #$07; sta.w output+ 4; pla; lsr #3; and #$07; sta.w output+3 lda.w input+3; pha; and #$07; sta.w output+ 2; pla; lsr #3; and #$07; sta.w output+1 //multiplier >>= 1 clc; ror.w multiplier+3; ror.w multiplier+2; ror.w multiplier+1; ror.w multiplier+0 //restore base7 upper 3-bits of each character for output buffer ldy.w #10 loop: { lda #$00 xba; lda.w multiplier+3; tax; lda quotients,x; sta.w multiplier+3; lda remainders,x xba; lda.w multiplier+2; tax; lda quotients,x; sta.w multiplier+2; lda remainders,x xba; lda.w multiplier+1; tax; lda quotients,x; sta.w multiplier+1; lda remainders,x xba; lda.w multiplier+0; tax; lda quotients,x; sta.w multiplier+0; lda remainders,x asl #3; ora.w output,y jsl decodeCharacter; sta.w output,y dey; bpl loop } //store string terminator lda #$ff; sta.w output+11 leave; rtl function decodeCharacter { cmp #$35; bne +; lda.b #'-'; rtl; + cmp #$36; bne +; lda.b #'.'; rtl; + cmp #$37; bne +; lda.b #'$'; rtl; + character.encode(); rtl } } codeCursor = pc() }
// Copyright (c) 2019 Shahrzad Shirzad // Copyright (c) 2019 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <phylanx/phylanx.hpp> #include <hpx/hpx_main.hpp> #include <hpx/testing.hpp> #include <cstdint> #include <string> #include <utility> /////////////////////////////////////////////////////////////////////////////// phylanx::execution_tree::primitive_argument_type compile_and_run( std::string const& codestr) { phylanx::execution_tree::compiler::function_list snippets; phylanx::execution_tree::compiler::environment env = phylanx::execution_tree::compiler::default_environment(); auto const& code = phylanx::execution_tree::compile(codestr, snippets, env); return code.run().arg_; } /////////////////////////////////////////////////////////////////////////////// void test_stack_operation_operation(std::string const& code, std::string const& expected_str) { HPX_TEST_EQ(compile_and_run(code), compile_and_run(expected_str)); } /////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { test_stack_operation_operation("stack(list([1., 2.]))", "[1., 2.]"); test_stack_operation_operation("stack(list([1., 2.]), 0)", "[1., 2.]"); test_stack_operation_operation("stack(list([1., 2.]), -1)", "[1., 2.]"); test_stack_operation_operation( "stack(list([[1., 2., 3.], [4., 5., 6.]]))", "[[1., 2., 3.],[4., 5., 6.]]"); test_stack_operation_operation( "stack(list([[1., 2., 3.], [4., 5., 6.]]), __arg(axis, 0))", "[[1., 2., 3.],[4., 5., 6.]]"); test_stack_operation_operation( "stack(list([[1., 2., 3.], [4., 5., 6.]]), __arg(axis, 1))", "[[1., 4.], [2., 5.], [3., 6.]]"); test_stack_operation_operation( "stack(list([[1., 2., 3.], [4., 5., 6.]]), __arg(axis, -1))", "[[1., 4.], [2., 5.], [3., 6.]]"); test_stack_operation_operation("stack(list(1., 2.))", "[1., 2.]"); test_stack_operation_operation("stack(list(1., 2.), 0)", "[1., 2.]"); test_stack_operation_operation( "stack(list([1., 2., 3.], [4., 5., 6.]))", "[[1., 2., 3.],[4., 5., 6.]]"); test_stack_operation_operation( "stack(list([1., 2., 3.], [4., 5., 6.]), __arg(axis, 0))", "[[1., 2., 3.],[4., 5., 6.]]"); test_stack_operation_operation( "stack(list([1., 2., 3.], [4., 5., 6.]), __arg(axis, 1))", "[[1., 4.], [2., 5.],[3., 6.]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.]], [[4., 5., 6.]]]))", "[[[1., 2., 3.]], [[4., 5., 6.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.]], [[4., 5., 6.]]]), 0)", "[[[1., 2., 3.]], [[4., 5., 6.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.]], [[4., 5., 6.]]]), -1)", "[[[1., 4.], [2., 5.],[3., 6.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.]], [[4., 5., 6.]]]), 2)", "[[[1., 4.], [2., 5.],[3., 6.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.]], [[4., 5., 6.]]]), 1)", "[[[1., 2., 3.], [4., 5., 6.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.], [4., 5., 6.]], " "[[7., 8., 9.], [10., 11., 12.]]]))", "[[[1., 2., 3.], [4., 5., 6.]], [[7., 8., 9.], [10., 11., 12.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.], [4., 5., 6.]], " "[[7., 8., 9.], [10., 11., 12.]]]), 0)", "[[[1., 2., 3.], [4., 5., 6.]], [[7., 8., 9.], [10., 11., 12.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.], [4., 5., 6.]], " "[[7., 8., 9.], [10., 11., 12.]]]), -1)", "[[[1., 7.], [2., 8.], [3., 9.]], [[4., 10.], [5., 11.], [6., 12.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.], [4., 5., 6.]], " "[[7., 8., 9.], [10., 11., 12.]]]), 2)", "[[[1., 7.], [2., 8.], [3., 9.]], [[4., 10.], [5., 11.], [6., 12.]]]"); test_stack_operation_operation( "stack(list([[[1., 2., 3.], [4., 5., 6.]], " "[[7., 8., 9.], [10., 11., 12.]]]), 1)", "[[[1., 2., 3.], [7., 8., 9.]], [[4., 5., 6.], [10., 11., 12.]]]"); test_stack_operation_operation( "stack(list([[1., 2., 3.]], [[4., 5., 6.]]))", "[[[1., 2., 3.]], [[4., 5., 6.]]]"); test_stack_operation_operation( "stack(list([[1., 2., 3.]], [[4., 5., 6.]]), 0)", "[[[1., 2., 3.]], [[4., 5., 6.]]]"); test_stack_operation_operation( "stack(list([[1., 2., 3.]], [[4., 5., 6.]]), 1)", "[[[1., 2., 3.], [4., 5., 6.]]]"); test_stack_operation_operation( "stack(list([[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]))", "[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]]"); test_stack_operation_operation( "stack(list([[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]), 0)", "[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]]"); test_stack_operation_operation( "stack(list([[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]), 1)", "[[[1., 2.], [5., 6.]], [[3., 4.], [7., 8.]]]"); test_stack_operation_operation( "stack(list([[1., 2.], [3., 4.], [5., 6.]], " "[[7., 8.], [9., 10.], [11., 12.]]))", "[[[1., 2.], [3., 4.], [5., 6.]], [[7., 8.], [9., 10.], [11., 12.]]]"); test_stack_operation_operation( "stack(list([[1., 2.], [3., 4.], [5., 6.]], " "[[7., 8.], [9., 10.], [11., 12.]]), __arg(axis, 0))", "[[[1., 2.], [3., 4.], [5., 6.]], [[7., 8.], [9., 10.], [11., 12.]]]"); test_stack_operation_operation( "stack(list([[1., 2.], [3., 4.], [5., 6.]], " "[[7., 8.], [9., 10.], [11., 12.]]), __arg(axis, 1))", "[[[1., 2.], [7., 8.]], [[3., 4.], [9., 10.]], " "[[5., 6.], [11., 12.]]]"); return hpx::util::report_errors(); }
; A315024: Coordination sequence Gal.6.196.5 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; Submitted by Jamie Morken(s3) ; 1,5,9,15,19,24,28,33,37,43,47,52,57,61,67,71,76,80,85,89,95,99,104,109,113,119,123,128,132,137,141,147,151,156,161,165,171,175,180,184,189,193,199,203,208,213,217,223,227,232 mov $1,$0 mul $0,13 add $0,5 div $0,11 mul $1,39 sub $1,6 div $1,11 add $1,1 add $0,$1
dnl Alpha mpn_invert_limb -- Invert a normalized limb. dnl Copyright (C) 1996, 2000 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of the GNU Library General Public License as published by dnl the Free Software Foundation; either version 2 of the License, or (at your dnl option) any later version. 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 Library General Public dnl License for more details. dnl You should have received a copy of the GNU Library General Public License dnl along with the GNU MP Library; see the file COPYING.LIB. If not, write to dnl the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, dnl MA 02111-1307, USA. dnl dnl This is based on sophie:/gmp-stuff/dbg-inv-limb.c. dnl The ideas are due to Peter L. Montgomery dnl dnl The table below uses 4096 bytes. The file mentioned above has an dnl alternative function that doesn't require the table, but it runs 50% dnl slower than this. include(`../config.m4') ASM_START() FLOAT64($C36,9223372036854775808.0) C 2^63 PROLOGUE_GP(mpn_invert_limb) lda r30,-16(r30) addq r16,r16,r1 bne r1,$73 lda r0,-1 br r31,$Lend $73: srl r16,1,r1 stq r1,0(r30) ldt f11,0(r30) cvtqt f11,f1 lda r1,$C36 ldt f10,0(r1) divt f10,f1,f10 lda r2,$invtab-4096 srl r16,52,r1 addq r1,r1,r1 addq r1,r2,r1 bic r1,6,r2 ldq r2,0(r2) bic r1,1,r1 extwl r2,r1,r2 sll r2,48,r0 umulh r16,r0,r1 addq r16,r1,r3 stq r3,0(r30) ldt f11,0(r30) cvtqt f11,f1 mult f1,f10,f1 cvttqc f1,f1 stt f1,0(r30) ldq r4,0(r30) subq r0,r4,r0 umulh r16,r0,r1 mulq r16,r0,r2 addq r16,r1,r3 bge r3,$Loop2 $Loop1: addq r2,r16,r2 cmpult r2,r16,r1 addq r3,r1,r3 addq r0,1,r0 blt r3,$Loop1 $Loop2: cmpult r2,r16,r1 subq r0,1,r0 subq r3,r1,r3 subq r2,r16,r2 bge r3,$Loop2 $Lend: lda r30,16(r30) ret r31,(r26),1 EPILOGUE(mpn_invert_limb) DATASTART(`$invtab',4) .word 0xffff,0xffc0,0xff80,0xff40,0xff00,0xfec0,0xfe81,0xfe41 .word 0xfe01,0xfdc2,0xfd83,0xfd43,0xfd04,0xfcc5,0xfc86,0xfc46 .word 0xfc07,0xfbc8,0xfb8a,0xfb4b,0xfb0c,0xfacd,0xfa8e,0xfa50 .word 0xfa11,0xf9d3,0xf994,0xf956,0xf918,0xf8d9,0xf89b,0xf85d .word 0xf81f,0xf7e1,0xf7a3,0xf765,0xf727,0xf6ea,0xf6ac,0xf66e .word 0xf631,0xf5f3,0xf5b6,0xf578,0xf53b,0xf4fd,0xf4c0,0xf483 .word 0xf446,0xf409,0xf3cc,0xf38f,0xf352,0xf315,0xf2d8,0xf29c .word 0xf25f,0xf222,0xf1e6,0xf1a9,0xf16d,0xf130,0xf0f4,0xf0b8 .word 0xf07c,0xf03f,0xf003,0xefc7,0xef8b,0xef4f,0xef14,0xeed8 .word 0xee9c,0xee60,0xee25,0xede9,0xedae,0xed72,0xed37,0xecfb .word 0xecc0,0xec85,0xec4a,0xec0e,0xebd3,0xeb98,0xeb5d,0xeb22 .word 0xeae8,0xeaad,0xea72,0xea37,0xe9fd,0xe9c2,0xe988,0xe94d .word 0xe913,0xe8d8,0xe89e,0xe864,0xe829,0xe7ef,0xe7b5,0xe77b .word 0xe741,0xe707,0xe6cd,0xe694,0xe65a,0xe620,0xe5e6,0xe5ad .word 0xe573,0xe53a,0xe500,0xe4c7,0xe48d,0xe454,0xe41b,0xe3e2 .word 0xe3a9,0xe370,0xe336,0xe2fd,0xe2c5,0xe28c,0xe253,0xe21a .word 0xe1e1,0xe1a9,0xe170,0xe138,0xe0ff,0xe0c7,0xe08e,0xe056 .word 0xe01e,0xdfe5,0xdfad,0xdf75,0xdf3d,0xdf05,0xdecd,0xde95 .word 0xde5d,0xde25,0xdded,0xddb6,0xdd7e,0xdd46,0xdd0f,0xdcd7 .word 0xdca0,0xdc68,0xdc31,0xdbf9,0xdbc2,0xdb8b,0xdb54,0xdb1d .word 0xdae6,0xdaae,0xda78,0xda41,0xda0a,0xd9d3,0xd99c,0xd965 .word 0xd92f,0xd8f8,0xd8c1,0xd88b,0xd854,0xd81e,0xd7e8,0xd7b1 .word 0xd77b,0xd745,0xd70e,0xd6d8,0xd6a2,0xd66c,0xd636,0xd600 .word 0xd5ca,0xd594,0xd55f,0xd529,0xd4f3,0xd4bd,0xd488,0xd452 .word 0xd41d,0xd3e7,0xd3b2,0xd37c,0xd347,0xd312,0xd2dd,0xd2a7 .word 0xd272,0xd23d,0xd208,0xd1d3,0xd19e,0xd169,0xd134,0xd100 .word 0xd0cb,0xd096,0xd061,0xd02d,0xcff8,0xcfc4,0xcf8f,0xcf5b .word 0xcf26,0xcef2,0xcebe,0xce89,0xce55,0xce21,0xcded,0xcdb9 .word 0xcd85,0xcd51,0xcd1d,0xcce9,0xccb5,0xcc81,0xcc4e,0xcc1a .word 0xcbe6,0xcbb3,0xcb7f,0xcb4c,0xcb18,0xcae5,0xcab1,0xca7e .word 0xca4b,0xca17,0xc9e4,0xc9b1,0xc97e,0xc94b,0xc918,0xc8e5 .word 0xc8b2,0xc87f,0xc84c,0xc819,0xc7e7,0xc7b4,0xc781,0xc74f .word 0xc71c,0xc6e9,0xc6b7,0xc684,0xc652,0xc620,0xc5ed,0xc5bb .word 0xc589,0xc557,0xc524,0xc4f2,0xc4c0,0xc48e,0xc45c,0xc42a .word 0xc3f8,0xc3c7,0xc395,0xc363,0xc331,0xc300,0xc2ce,0xc29c .word 0xc26b,0xc239,0xc208,0xc1d6,0xc1a5,0xc174,0xc142,0xc111 .word 0xc0e0,0xc0af,0xc07e,0xc04d,0xc01c,0xbfeb,0xbfba,0xbf89 .word 0xbf58,0xbf27,0xbef6,0xbec5,0xbe95,0xbe64,0xbe33,0xbe03 .word 0xbdd2,0xbda2,0xbd71,0xbd41,0xbd10,0xbce0,0xbcb0,0xbc80 .word 0xbc4f,0xbc1f,0xbbef,0xbbbf,0xbb8f,0xbb5f,0xbb2f,0xbaff .word 0xbacf,0xba9f,0xba6f,0xba40,0xba10,0xb9e0,0xb9b1,0xb981 .word 0xb951,0xb922,0xb8f2,0xb8c3,0xb894,0xb864,0xb835,0xb806 .word 0xb7d6,0xb7a7,0xb778,0xb749,0xb71a,0xb6eb,0xb6bc,0xb68d .word 0xb65e,0xb62f,0xb600,0xb5d1,0xb5a2,0xb574,0xb545,0xb516 .word 0xb4e8,0xb4b9,0xb48a,0xb45c,0xb42e,0xb3ff,0xb3d1,0xb3a2 .word 0xb374,0xb346,0xb318,0xb2e9,0xb2bb,0xb28d,0xb25f,0xb231 .word 0xb203,0xb1d5,0xb1a7,0xb179,0xb14b,0xb11d,0xb0f0,0xb0c2 .word 0xb094,0xb067,0xb039,0xb00b,0xafde,0xafb0,0xaf83,0xaf55 .word 0xaf28,0xaefb,0xaecd,0xaea0,0xae73,0xae45,0xae18,0xadeb .word 0xadbe,0xad91,0xad64,0xad37,0xad0a,0xacdd,0xacb0,0xac83 .word 0xac57,0xac2a,0xabfd,0xabd0,0xaba4,0xab77,0xab4a,0xab1e .word 0xaaf1,0xaac5,0xaa98,0xaa6c,0xaa40,0xaa13,0xa9e7,0xa9bb .word 0xa98e,0xa962,0xa936,0xa90a,0xa8de,0xa8b2,0xa886,0xa85a .word 0xa82e,0xa802,0xa7d6,0xa7aa,0xa77e,0xa753,0xa727,0xa6fb .word 0xa6d0,0xa6a4,0xa678,0xa64d,0xa621,0xa5f6,0xa5ca,0xa59f .word 0xa574,0xa548,0xa51d,0xa4f2,0xa4c6,0xa49b,0xa470,0xa445 .word 0xa41a,0xa3ef,0xa3c4,0xa399,0xa36e,0xa343,0xa318,0xa2ed .word 0xa2c2,0xa297,0xa26d,0xa242,0xa217,0xa1ed,0xa1c2,0xa197 .word 0xa16d,0xa142,0xa118,0xa0ed,0xa0c3,0xa098,0xa06e,0xa044 .word 0xa01a,0x9fef,0x9fc5,0x9f9b,0x9f71,0x9f47,0x9f1c,0x9ef2 .word 0x9ec8,0x9e9e,0x9e74,0x9e4b,0x9e21,0x9df7,0x9dcd,0x9da3 .word 0x9d79,0x9d50,0x9d26,0x9cfc,0x9cd3,0x9ca9,0x9c80,0x9c56 .word 0x9c2d,0x9c03,0x9bda,0x9bb0,0x9b87,0x9b5e,0x9b34,0x9b0b .word 0x9ae2,0x9ab9,0x9a8f,0x9a66,0x9a3d,0x9a14,0x99eb,0x99c2 .word 0x9999,0x9970,0x9947,0x991e,0x98f6,0x98cd,0x98a4,0x987b .word 0x9852,0x982a,0x9801,0x97d8,0x97b0,0x9787,0x975f,0x9736 .word 0x970e,0x96e5,0x96bd,0x9695,0x966c,0x9644,0x961c,0x95f3 .word 0x95cb,0x95a3,0x957b,0x9553,0x952b,0x9503,0x94db,0x94b3 .word 0x948b,0x9463,0x943b,0x9413,0x93eb,0x93c3,0x939b,0x9374 .word 0x934c,0x9324,0x92fd,0x92d5,0x92ad,0x9286,0x925e,0x9237 .word 0x920f,0x91e8,0x91c0,0x9199,0x9172,0x914a,0x9123,0x90fc .word 0x90d4,0x90ad,0x9086,0x905f,0x9038,0x9011,0x8fea,0x8fc3 .word 0x8f9c,0x8f75,0x8f4e,0x8f27,0x8f00,0x8ed9,0x8eb2,0x8e8b .word 0x8e65,0x8e3e,0x8e17,0x8df1,0x8dca,0x8da3,0x8d7d,0x8d56 .word 0x8d30,0x8d09,0x8ce3,0x8cbc,0x8c96,0x8c6f,0x8c49,0x8c23 .word 0x8bfc,0x8bd6,0x8bb0,0x8b8a,0x8b64,0x8b3d,0x8b17,0x8af1 .word 0x8acb,0x8aa5,0x8a7f,0x8a59,0x8a33,0x8a0d,0x89e7,0x89c1 .word 0x899c,0x8976,0x8950,0x892a,0x8904,0x88df,0x88b9,0x8893 .word 0x886e,0x8848,0x8823,0x87fd,0x87d8,0x87b2,0x878d,0x8767 .word 0x8742,0x871d,0x86f7,0x86d2,0x86ad,0x8687,0x8662,0x863d .word 0x8618,0x85f3,0x85ce,0x85a9,0x8583,0x855e,0x8539,0x8514 .word 0x84f0,0x84cb,0x84a6,0x8481,0x845c,0x8437,0x8412,0x83ee .word 0x83c9,0x83a4,0x8380,0x835b,0x8336,0x8312,0x82ed,0x82c9 .word 0x82a4,0x8280,0x825b,0x8237,0x8212,0x81ee,0x81ca,0x81a5 .word 0x8181,0x815d,0x8138,0x8114,0x80f0,0x80cc,0x80a8,0x8084 .word 0x8060,0x803c,0x8018,0x7ff4,0x7fd0,0x7fac,0x7f88,0x7f64 .word 0x7f40,0x7f1c,0x7ef8,0x7ed4,0x7eb1,0x7e8d,0x7e69,0x7e45 .word 0x7e22,0x7dfe,0x7ddb,0x7db7,0x7d93,0x7d70,0x7d4c,0x7d29 .word 0x7d05,0x7ce2,0x7cbf,0x7c9b,0x7c78,0x7c55,0x7c31,0x7c0e .word 0x7beb,0x7bc7,0x7ba4,0x7b81,0x7b5e,0x7b3b,0x7b18,0x7af5 .word 0x7ad2,0x7aaf,0x7a8c,0x7a69,0x7a46,0x7a23,0x7a00,0x79dd .word 0x79ba,0x7997,0x7975,0x7952,0x792f,0x790c,0x78ea,0x78c7 .word 0x78a4,0x7882,0x785f,0x783c,0x781a,0x77f7,0x77d5,0x77b2 .word 0x7790,0x776e,0x774b,0x7729,0x7706,0x76e4,0x76c2,0x76a0 .word 0x767d,0x765b,0x7639,0x7617,0x75f5,0x75d2,0x75b0,0x758e .word 0x756c,0x754a,0x7528,0x7506,0x74e4,0x74c2,0x74a0,0x747e .word 0x745d,0x743b,0x7419,0x73f7,0x73d5,0x73b4,0x7392,0x7370 .word 0x734f,0x732d,0x730b,0x72ea,0x72c8,0x72a7,0x7285,0x7264 .word 0x7242,0x7221,0x71ff,0x71de,0x71bc,0x719b,0x717a,0x7158 .word 0x7137,0x7116,0x70f5,0x70d3,0x70b2,0x7091,0x7070,0x704f .word 0x702e,0x700c,0x6feb,0x6fca,0x6fa9,0x6f88,0x6f67,0x6f46 .word 0x6f26,0x6f05,0x6ee4,0x6ec3,0x6ea2,0x6e81,0x6e60,0x6e40 .word 0x6e1f,0x6dfe,0x6dde,0x6dbd,0x6d9c,0x6d7c,0x6d5b,0x6d3a .word 0x6d1a,0x6cf9,0x6cd9,0x6cb8,0x6c98,0x6c77,0x6c57,0x6c37 .word 0x6c16,0x6bf6,0x6bd6,0x6bb5,0x6b95,0x6b75,0x6b54,0x6b34 .word 0x6b14,0x6af4,0x6ad4,0x6ab4,0x6a94,0x6a73,0x6a53,0x6a33 .word 0x6a13,0x69f3,0x69d3,0x69b3,0x6993,0x6974,0x6954,0x6934 .word 0x6914,0x68f4,0x68d4,0x68b5,0x6895,0x6875,0x6855,0x6836 .word 0x6816,0x67f6,0x67d7,0x67b7,0x6798,0x6778,0x6758,0x6739 .word 0x6719,0x66fa,0x66db,0x66bb,0x669c,0x667c,0x665d,0x663e .word 0x661e,0x65ff,0x65e0,0x65c0,0x65a1,0x6582,0x6563,0x6544 .word 0x6524,0x6505,0x64e6,0x64c7,0x64a8,0x6489,0x646a,0x644b .word 0x642c,0x640d,0x63ee,0x63cf,0x63b0,0x6391,0x6373,0x6354 .word 0x6335,0x6316,0x62f7,0x62d9,0x62ba,0x629b,0x627c,0x625e .word 0x623f,0x6221,0x6202,0x61e3,0x61c5,0x61a6,0x6188,0x6169 .word 0x614b,0x612c,0x610e,0x60ef,0x60d1,0x60b3,0x6094,0x6076 .word 0x6058,0x6039,0x601b,0x5ffd,0x5fdf,0x5fc0,0x5fa2,0x5f84 .word 0x5f66,0x5f48,0x5f2a,0x5f0b,0x5eed,0x5ecf,0x5eb1,0x5e93 .word 0x5e75,0x5e57,0x5e39,0x5e1b,0x5dfd,0x5de0,0x5dc2,0x5da4 .word 0x5d86,0x5d68,0x5d4a,0x5d2d,0x5d0f,0x5cf1,0x5cd3,0x5cb6 .word 0x5c98,0x5c7a,0x5c5d,0x5c3f,0x5c21,0x5c04,0x5be6,0x5bc9 .word 0x5bab,0x5b8e,0x5b70,0x5b53,0x5b35,0x5b18,0x5afb,0x5add .word 0x5ac0,0x5aa2,0x5a85,0x5a68,0x5a4b,0x5a2d,0x5a10,0x59f3 .word 0x59d6,0x59b8,0x599b,0x597e,0x5961,0x5944,0x5927,0x590a .word 0x58ed,0x58d0,0x58b3,0x5896,0x5879,0x585c,0x583f,0x5822 .word 0x5805,0x57e8,0x57cb,0x57ae,0x5791,0x5775,0x5758,0x573b .word 0x571e,0x5702,0x56e5,0x56c8,0x56ac,0x568f,0x5672,0x5656 .word 0x5639,0x561c,0x5600,0x55e3,0x55c7,0x55aa,0x558e,0x5571 .word 0x5555,0x5538,0x551c,0x5500,0x54e3,0x54c7,0x54aa,0x548e .word 0x5472,0x5456,0x5439,0x541d,0x5401,0x53e5,0x53c8,0x53ac .word 0x5390,0x5374,0x5358,0x533c,0x5320,0x5304,0x52e8,0x52cb .word 0x52af,0x5293,0x5277,0x525c,0x5240,0x5224,0x5208,0x51ec .word 0x51d0,0x51b4,0x5198,0x517c,0x5161,0x5145,0x5129,0x510d .word 0x50f2,0x50d6,0x50ba,0x509f,0x5083,0x5067,0x504c,0x5030 .word 0x5015,0x4ff9,0x4fdd,0x4fc2,0x4fa6,0x4f8b,0x4f6f,0x4f54 .word 0x4f38,0x4f1d,0x4f02,0x4ee6,0x4ecb,0x4eb0,0x4e94,0x4e79 .word 0x4e5e,0x4e42,0x4e27,0x4e0c,0x4df0,0x4dd5,0x4dba,0x4d9f .word 0x4d84,0x4d69,0x4d4d,0x4d32,0x4d17,0x4cfc,0x4ce1,0x4cc6 .word 0x4cab,0x4c90,0x4c75,0x4c5a,0x4c3f,0x4c24,0x4c09,0x4bee .word 0x4bd3,0x4bb9,0x4b9e,0x4b83,0x4b68,0x4b4d,0x4b32,0x4b18 .word 0x4afd,0x4ae2,0x4ac7,0x4aad,0x4a92,0x4a77,0x4a5d,0x4a42 .word 0x4a27,0x4a0d,0x49f2,0x49d8,0x49bd,0x49a3,0x4988,0x496e .word 0x4953,0x4939,0x491e,0x4904,0x48e9,0x48cf,0x48b5,0x489a .word 0x4880,0x4865,0x484b,0x4831,0x4817,0x47fc,0x47e2,0x47c8 .word 0x47ae,0x4793,0x4779,0x475f,0x4745,0x472b,0x4711,0x46f6 .word 0x46dc,0x46c2,0x46a8,0x468e,0x4674,0x465a,0x4640,0x4626 .word 0x460c,0x45f2,0x45d8,0x45be,0x45a5,0x458b,0x4571,0x4557 .word 0x453d,0x4523,0x4509,0x44f0,0x44d6,0x44bc,0x44a2,0x4489 .word 0x446f,0x4455,0x443c,0x4422,0x4408,0x43ef,0x43d5,0x43bc .word 0x43a2,0x4388,0x436f,0x4355,0x433c,0x4322,0x4309,0x42ef .word 0x42d6,0x42bc,0x42a3,0x428a,0x4270,0x4257,0x423d,0x4224 .word 0x420b,0x41f2,0x41d8,0x41bf,0x41a6,0x418c,0x4173,0x415a .word 0x4141,0x4128,0x410e,0x40f5,0x40dc,0x40c3,0x40aa,0x4091 .word 0x4078,0x405f,0x4046,0x402d,0x4014,0x3ffb,0x3fe2,0x3fc9 .word 0x3fb0,0x3f97,0x3f7e,0x3f65,0x3f4c,0x3f33,0x3f1a,0x3f01 .word 0x3ee8,0x3ed0,0x3eb7,0x3e9e,0x3e85,0x3e6c,0x3e54,0x3e3b .word 0x3e22,0x3e0a,0x3df1,0x3dd8,0x3dc0,0x3da7,0x3d8e,0x3d76 .word 0x3d5d,0x3d45,0x3d2c,0x3d13,0x3cfb,0x3ce2,0x3cca,0x3cb1 .word 0x3c99,0x3c80,0x3c68,0x3c50,0x3c37,0x3c1f,0x3c06,0x3bee .word 0x3bd6,0x3bbd,0x3ba5,0x3b8d,0x3b74,0x3b5c,0x3b44,0x3b2b .word 0x3b13,0x3afb,0x3ae3,0x3acb,0x3ab2,0x3a9a,0x3a82,0x3a6a .word 0x3a52,0x3a3a,0x3a22,0x3a09,0x39f1,0x39d9,0x39c1,0x39a9 .word 0x3991,0x3979,0x3961,0x3949,0x3931,0x3919,0x3901,0x38ea .word 0x38d2,0x38ba,0x38a2,0x388a,0x3872,0x385a,0x3843,0x382b .word 0x3813,0x37fb,0x37e3,0x37cc,0x37b4,0x379c,0x3785,0x376d .word 0x3755,0x373e,0x3726,0x370e,0x36f7,0x36df,0x36c8,0x36b0 .word 0x3698,0x3681,0x3669,0x3652,0x363a,0x3623,0x360b,0x35f4 .word 0x35dc,0x35c5,0x35ae,0x3596,0x357f,0x3567,0x3550,0x3539 .word 0x3521,0x350a,0x34f3,0x34db,0x34c4,0x34ad,0x3496,0x347e .word 0x3467,0x3450,0x3439,0x3422,0x340a,0x33f3,0x33dc,0x33c5 .word 0x33ae,0x3397,0x3380,0x3368,0x3351,0x333a,0x3323,0x330c .word 0x32f5,0x32de,0x32c7,0x32b0,0x3299,0x3282,0x326c,0x3255 .word 0x323e,0x3227,0x3210,0x31f9,0x31e2,0x31cb,0x31b5,0x319e .word 0x3187,0x3170,0x3159,0x3143,0x312c,0x3115,0x30fe,0x30e8 .word 0x30d1,0x30ba,0x30a4,0x308d,0x3076,0x3060,0x3049,0x3033 .word 0x301c,0x3005,0x2fef,0x2fd8,0x2fc2,0x2fab,0x2f95,0x2f7e .word 0x2f68,0x2f51,0x2f3b,0x2f24,0x2f0e,0x2ef8,0x2ee1,0x2ecb .word 0x2eb4,0x2e9e,0x2e88,0x2e71,0x2e5b,0x2e45,0x2e2e,0x2e18 .word 0x2e02,0x2dec,0x2dd5,0x2dbf,0x2da9,0x2d93,0x2d7c,0x2d66 .word 0x2d50,0x2d3a,0x2d24,0x2d0e,0x2cf8,0x2ce1,0x2ccb,0x2cb5 .word 0x2c9f,0x2c89,0x2c73,0x2c5d,0x2c47,0x2c31,0x2c1b,0x2c05 .word 0x2bef,0x2bd9,0x2bc3,0x2bad,0x2b97,0x2b81,0x2b6c,0x2b56 .word 0x2b40,0x2b2a,0x2b14,0x2afe,0x2ae8,0x2ad3,0x2abd,0x2aa7 .word 0x2a91,0x2a7c,0x2a66,0x2a50,0x2a3a,0x2a25,0x2a0f,0x29f9 .word 0x29e4,0x29ce,0x29b8,0x29a3,0x298d,0x2977,0x2962,0x294c .word 0x2937,0x2921,0x290c,0x28f6,0x28e0,0x28cb,0x28b5,0x28a0 .word 0x288b,0x2875,0x2860,0x284a,0x2835,0x281f,0x280a,0x27f5 .word 0x27df,0x27ca,0x27b4,0x279f,0x278a,0x2774,0x275f,0x274a .word 0x2735,0x271f,0x270a,0x26f5,0x26e0,0x26ca,0x26b5,0x26a0 .word 0x268b,0x2676,0x2660,0x264b,0x2636,0x2621,0x260c,0x25f7 .word 0x25e2,0x25cd,0x25b8,0x25a2,0x258d,0x2578,0x2563,0x254e .word 0x2539,0x2524,0x250f,0x24fa,0x24e5,0x24d1,0x24bc,0x24a7 .word 0x2492,0x247d,0x2468,0x2453,0x243e,0x2429,0x2415,0x2400 .word 0x23eb,0x23d6,0x23c1,0x23ad,0x2398,0x2383,0x236e,0x235a .word 0x2345,0x2330,0x231c,0x2307,0x22f2,0x22dd,0x22c9,0x22b4 .word 0x22a0,0x228b,0x2276,0x2262,0x224d,0x2239,0x2224,0x2210 .word 0x21fb,0x21e6,0x21d2,0x21bd,0x21a9,0x2194,0x2180,0x216c .word 0x2157,0x2143,0x212e,0x211a,0x2105,0x20f1,0x20dd,0x20c8 .word 0x20b4,0x20a0,0x208b,0x2077,0x2063,0x204e,0x203a,0x2026 .word 0x2012,0x1ffd,0x1fe9,0x1fd5,0x1fc1,0x1fac,0x1f98,0x1f84 .word 0x1f70,0x1f5c,0x1f47,0x1f33,0x1f1f,0x1f0b,0x1ef7,0x1ee3 .word 0x1ecf,0x1ebb,0x1ea7,0x1e93,0x1e7f,0x1e6a,0x1e56,0x1e42 .word 0x1e2e,0x1e1a,0x1e06,0x1df3,0x1ddf,0x1dcb,0x1db7,0x1da3 .word 0x1d8f,0x1d7b,0x1d67,0x1d53,0x1d3f,0x1d2b,0x1d18,0x1d04 .word 0x1cf0,0x1cdc,0x1cc8,0x1cb5,0x1ca1,0x1c8d,0x1c79,0x1c65 .word 0x1c52,0x1c3e,0x1c2a,0x1c17,0x1c03,0x1bef,0x1bdb,0x1bc8 .word 0x1bb4,0x1ba0,0x1b8d,0x1b79,0x1b66,0x1b52,0x1b3e,0x1b2b .word 0x1b17,0x1b04,0x1af0,0x1add,0x1ac9,0x1ab6,0x1aa2,0x1a8f .word 0x1a7b,0x1a68,0x1a54,0x1a41,0x1a2d,0x1a1a,0x1a06,0x19f3 .word 0x19e0,0x19cc,0x19b9,0x19a5,0x1992,0x197f,0x196b,0x1958 .word 0x1945,0x1931,0x191e,0x190b,0x18f8,0x18e4,0x18d1,0x18be .word 0x18ab,0x1897,0x1884,0x1871,0x185e,0x184b,0x1837,0x1824 .word 0x1811,0x17fe,0x17eb,0x17d8,0x17c4,0x17b1,0x179e,0x178b .word 0x1778,0x1765,0x1752,0x173f,0x172c,0x1719,0x1706,0x16f3 .word 0x16e0,0x16cd,0x16ba,0x16a7,0x1694,0x1681,0x166e,0x165b .word 0x1648,0x1635,0x1623,0x1610,0x15fd,0x15ea,0x15d7,0x15c4 .word 0x15b1,0x159f,0x158c,0x1579,0x1566,0x1553,0x1541,0x152e .word 0x151b,0x1508,0x14f6,0x14e3,0x14d0,0x14bd,0x14ab,0x1498 .word 0x1485,0x1473,0x1460,0x144d,0x143b,0x1428,0x1416,0x1403 .word 0x13f0,0x13de,0x13cb,0x13b9,0x13a6,0x1394,0x1381,0x136f .word 0x135c,0x1349,0x1337,0x1325,0x1312,0x1300,0x12ed,0x12db .word 0x12c8,0x12b6,0x12a3,0x1291,0x127f,0x126c,0x125a,0x1247 .word 0x1235,0x1223,0x1210,0x11fe,0x11ec,0x11d9,0x11c7,0x11b5 .word 0x11a3,0x1190,0x117e,0x116c,0x1159,0x1147,0x1135,0x1123 .word 0x1111,0x10fe,0x10ec,0x10da,0x10c8,0x10b6,0x10a4,0x1091 .word 0x107f,0x106d,0x105b,0x1049,0x1037,0x1025,0x1013,0x1001 .word 0x0fef,0x0fdc,0x0fca,0x0fb8,0x0fa6,0x0f94,0x0f82,0x0f70 .word 0x0f5e,0x0f4c,0x0f3a,0x0f28,0x0f17,0x0f05,0x0ef3,0x0ee1 .word 0x0ecf,0x0ebd,0x0eab,0x0e99,0x0e87,0x0e75,0x0e64,0x0e52 .word 0x0e40,0x0e2e,0x0e1c,0x0e0a,0x0df9,0x0de7,0x0dd5,0x0dc3 .word 0x0db2,0x0da0,0x0d8e,0x0d7c,0x0d6b,0x0d59,0x0d47,0x0d35 .word 0x0d24,0x0d12,0x0d00,0x0cef,0x0cdd,0x0ccb,0x0cba,0x0ca8 .word 0x0c97,0x0c85,0x0c73,0x0c62,0x0c50,0x0c3f,0x0c2d,0x0c1c .word 0x0c0a,0x0bf8,0x0be7,0x0bd5,0x0bc4,0x0bb2,0x0ba1,0x0b8f .word 0x0b7e,0x0b6c,0x0b5b,0x0b4a,0x0b38,0x0b27,0x0b15,0x0b04 .word 0x0af2,0x0ae1,0x0ad0,0x0abe,0x0aad,0x0a9c,0x0a8a,0x0a79 .word 0x0a68,0x0a56,0x0a45,0x0a34,0x0a22,0x0a11,0x0a00,0x09ee .word 0x09dd,0x09cc,0x09bb,0x09a9,0x0998,0x0987,0x0976,0x0965 .word 0x0953,0x0942,0x0931,0x0920,0x090f,0x08fe,0x08ec,0x08db .word 0x08ca,0x08b9,0x08a8,0x0897,0x0886,0x0875,0x0864,0x0853 .word 0x0842,0x0831,0x081f,0x080e,0x07fd,0x07ec,0x07db,0x07ca .word 0x07b9,0x07a8,0x0798,0x0787,0x0776,0x0765,0x0754,0x0743 .word 0x0732,0x0721,0x0710,0x06ff,0x06ee,0x06dd,0x06cd,0x06bc .word 0x06ab,0x069a,0x0689,0x0678,0x0668,0x0657,0x0646,0x0635 .word 0x0624,0x0614,0x0603,0x05f2,0x05e1,0x05d1,0x05c0,0x05af .word 0x059e,0x058e,0x057d,0x056c,0x055c,0x054b,0x053a,0x052a .word 0x0519,0x0508,0x04f8,0x04e7,0x04d6,0x04c6,0x04b5,0x04a5 .word 0x0494,0x0484,0x0473,0x0462,0x0452,0x0441,0x0431,0x0420 .word 0x0410,0x03ff,0x03ef,0x03de,0x03ce,0x03bd,0x03ad,0x039c .word 0x038c,0x037b,0x036b,0x035b,0x034a,0x033a,0x0329,0x0319 .word 0x0309,0x02f8,0x02e8,0x02d7,0x02c7,0x02b7,0x02a6,0x0296 .word 0x0286,0x0275,0x0265,0x0255,0x0245,0x0234,0x0224,0x0214 .word 0x0204,0x01f3,0x01e3,0x01d3,0x01c3,0x01b2,0x01a2,0x0192 .word 0x0182,0x0172,0x0161,0x0151,0x0141,0x0131,0x0121,0x0111 .word 0x0101,0x00f0,0x00e0,0x00d0,0x00c0,0x00b0,0x00a0,0x0090 .word 0x0080,0x0070,0x0060,0x0050,0x0040,0x0030,0x0020,0x0010 DATAEND() ASM_END()
; ; r0 - scon ; r1 - sbuf ; r2 - transnit test ; r3 - receive test ; r4 - pcon ; ajmp start; org 03h ;external interrupt 0 reti; org 0bh ;t/c 0 interrupt setb p3.1 ; clr p3.1 ; reti; org 13h ;external interrupt 1 reti; org 1bh ;t/c 1 interrupt reti; org 23h ;serial interface interrupt clr scon.4 ; clr scon.0 ; clr scon.1 ; inc b ; reti; nop; nop; wait: mov a,b ; jz wait ; ret ; wait_txd: movx a, @r0 ; jnb acc.1, wait_txd ; ret ; nop; nop; test_txd: clr c ; movx a, @r1 ; subb a, r2 ; jnz error ; ret ; nop; nop; test_rxd: clr c ; mov a, sbuf ; subb a, r3 ; jnz error ; ret ; nop; nop; start: clr a; mov 7fh, a ; error 0 clr p3.7 ; clr p3.0 ; mov ie, #090h ; enable interrupts mov r0, #098h ; serial control address mov r1, #099h ; serial data buffer address mov dpl, #087h ; pcon mov dph, #000h ; ; ; testing mode 0 ; ; transmit ; mov scon, #000h ; mode 0 mov b,#000h ; mov a, #010h ; mov r2, #06ch ; mov sbuf, r2 ; transmit 6c movx @r0, a ; acall wait ; acall test_txd ; mov c, p3.0 ; jnc error ; ; ; receive ; setb ie.7 ; mov a, #000h ; movx @r0,a ; mov 7fh, #001h ; error 1 nop ; nop ; nop ; nop ; mov c, p3.0 ; jc error ; mov 7fh, #002h ; error 2 mov b,#000h ; mov a, #0d3h ; mov r3, a ; movx @r1, a ; mov scon, #010h ; acall wait ; acall test_rxd ; mov c, p3.0 ; jnc error ; mov p0, #00h ; ajmp mode1 ; error: mov p2, 7fh ; loop: nop ; ajmp loop ; ; ; mode 1 ; ; transmit ; mode1: mov b,#000h ; mov ie, #092h ; mov 7fh, #003h ; error 3 clr p3.1 ; mov a, #050h ; external mode 1 receive movx @r0, a ; mov scon, #040h ; mov th0, #0ech ; mov tl0, #0ech ; mov th1, #0ech ; mov tl1, #0ech ; mov tmod, #022h ; setb tcon.4 ; setb tcon.6 ; mov r2, #095h ; mov sbuf, r2 ; start transmition acall wait ; clr tcon.4 ; clr tcon.6 ; acall test_txd ; ; ; receive ; mov 7fh, #004h ; error 4 mov b, #000h ; mov a, #040h ; movx @r0, a ; mov scon, #050h ; mov a, #0a2h ; mov r3, a ; setb tcon.4 ; setb tcon.6 ; movx @r1, a ; acall wait ; acall wait_txd ; clr tcon.4 ; clr tcon.6 ; acall test_rxd ; mov 7fh, #005h ; error 5 mov c, scon.2 ; jnc error ; ; ; transmit / receive ; mov b,#000h ; mov ie, #082h ; mov 7fh, #006h ; error 6 mov a, #050h ; external mode 1 receive movx @r0, a ; mov scon, #050h ; setb tcon.4 ; setb tcon.6 ; mov r2, #097h ; mov sbuf, r2 ; start transmition mov a, #0d5h ; mov r3, a ; movx @r1, a ; loop0: mov c, scon.1 ; jnc loop0 ; mov c, scon.0 ; jnc loop0 ; clr tcon.4 ; clr tcon.6 ; clr c ; acall test_txd ; mov 7fh, #007h ; error 7 acall test_rxd ; clr scon.1 ; clr scon.0 ; mov p0, #01h ; ; ; mode 2 ; ; transmit ; mov b,#000h ; mov ie, #090h ; mov 7fh, #008h ; error 8 mov a, #090h ; external mode 2 receive movx @r0, a ; mov scon, #080h ; mov r2, #095h ; mov sbuf, r2 ; start transmition acall wait ; acall test_txd ; ; ; receive 1 ; mov 7fh, #009h ; error 9 mov b, #000h ; mov a, #088h ; movx @r0, a ; mov scon, #090h ; mov a, #0a2h ; mov r3, a ; movx @r1, a ; acall wait ; acall test_rxd ; mov 7fh, #00ah ; error a mov c, scon.2 ; jnc error1 ; ; ; receive 2 ; setb ie.7 ; mov 7fh, #00bh ; error b mov b, #000h ; mov a, #080h ; movx @r0, a ; mov scon, #0b0h ; mov a, #0b2h ; mov r3, a ; movx @r1, a ; loop1: nop ; nop ; dec a ; jnz loop1 ; acall test_rxd ; mov 7fh, #00ch ; error c mov a, b ; jnz error1 ; ; ; transmit / receive ; mov b,#000h ; mov ie, #000h ; mov 7fh, #00dh ; error d mov a, #090h ; external mode 2 receive movx @r0, a ; mov a, #080h ; movx @dptr, a ; mov pcon, a ; mov scon, #090h ; mov r2, #097h ; mov sbuf, r2 ; start transmition mov a, #0d5h ; mov r3, a ; movx @r1, a ; loop2: mov c, scon.1 ; jnc loop2 ; mov c, scon.0 ; jnc loop2 ; acall test_txd ; mov 7fh, #00eh ; error e acall test_rxd ; clr scon.1 ; clr scon.0 ; mov p0, #02h ; ajmp mode3 ; error1: ljmp error ; ; ; mode 3 ; ; transmit ; mode3: mov b,#000h ; mov ie, #092h ; mov 7fh, #00fh ; error f mov a, #0d0h ; external mode 3 receive movx @r0, a ; mov scon, #0c0h ; mov r2, #095h ; setb tcon.4 ; setb tcon.6 ; mov sbuf, r2 ; start transmition acall wait ; clr tcon.4 ; clr tcon.6 ; acall test_txd ; ; ; receive ; setb ie.7 ; mov 7fh, #010h ; error 10 mov b, #000h ; mov a, #0c0h ; movx @r0, a ; mov scon, #0d4h ; mov a, #0a2h ; mov r3, a ; movx @r1, a ; setb tcon.4 ; setb tcon.6 ; acall wait ; acall wait_txd ; clr tcon.4 ; clr tcon.6 ; acall test_rxd ; mov 7fh, #011h ; error 11 mov c, scon.2 ; jc error1 ; ; ; transmit / receive ; mov scon, #0d8h ; mov b,#000h ; mov ie, #082h ; mov 7fh, #012h ; error 12 mov a, #0d0h ; external mode 3 receive movx @r0, a ; mov r2, #097h ; setb tcon.4 ; setb tcon.6 ; mov sbuf, r2 ; start transmition mov a, #0d5h ; mov r3, a ; movx @r1, a ; loop3: mov c, scon.1 ; jnc loop3 ; mov c, scon.0 ; jnc loop3 ; clr tcon.4 ; clr tcon.6 ; acall test_txd ; mov 7fh, #013h ; error 13 acall test_rxd ; clr scon.1 ; clr scon.0 ; mov 7fh, #014h ; error 14 mov c, scon.2 ; jc error2 ; movx a, @r0 ; subb a, #0d7h ; done: mov p0, #03h ; ajmp done ; error2: ljmp error ; end
; A202330: Number of (n+1) X 4 binary arrays with consecutive windows of two bits considered as a binary number nondecreasing in every row and column. ; 36,82,162,289,478,746,1112,1597,2224,3018,4006,5217,6682,8434,10508,12941,15772,19042,22794,27073,31926,37402,43552,50429,58088,66586,75982,86337,97714,110178,123796,138637,154772,172274,191218,211681,233742 add $0,3 mov $2,$0 mov $3,1 lpb $0 sub $0,1 add $3,$2 add $1,$3 add $2,1 sub $3,$0 add $4,$1 lpe trn $1,$4 add $1,$4 add $1,2
#pragma once #include "../base_def.hpp" namespace lol { enum struct LolClashGameflowPhase { ChampSelect_e = 5, CheckedIntoTournament_e = 3, EndOfGame_e = 12, FailedToLaunch_e = 7, GameStart_e = 6, InProgress_e = 8, Lobby_e = 1, Matchmaking_e = 2, None_e = 0, PreEndOfGame_e = 11, ReadyCheck_e = 4, Reconnect_e = 9, TerminatedInError_e = 13, WaitingForStats_e = 10, }; inline void to_json(json& j, const LolClashGameflowPhase& v) { if(v == LolClashGameflowPhase::ChampSelect_e) { j = "ChampSelect"; return; } if(v == LolClashGameflowPhase::CheckedIntoTournament_e) { j = "CheckedIntoTournament"; return; } if(v == LolClashGameflowPhase::EndOfGame_e) { j = "EndOfGame"; return; } if(v == LolClashGameflowPhase::FailedToLaunch_e) { j = "FailedToLaunch"; return; } if(v == LolClashGameflowPhase::GameStart_e) { j = "GameStart"; return; } if(v == LolClashGameflowPhase::InProgress_e) { j = "InProgress"; return; } if(v == LolClashGameflowPhase::Lobby_e) { j = "Lobby"; return; } if(v == LolClashGameflowPhase::Matchmaking_e) { j = "Matchmaking"; return; } if(v == LolClashGameflowPhase::None_e) { j = "None"; return; } if(v == LolClashGameflowPhase::PreEndOfGame_e) { j = "PreEndOfGame"; return; } if(v == LolClashGameflowPhase::ReadyCheck_e) { j = "ReadyCheck"; return; } if(v == LolClashGameflowPhase::Reconnect_e) { j = "Reconnect"; return; } if(v == LolClashGameflowPhase::TerminatedInError_e) { j = "TerminatedInError"; return; } if(v == LolClashGameflowPhase::WaitingForStats_e) { j = "WaitingForStats"; return; } } inline void from_json(const json& j, LolClashGameflowPhase& v) { if(j.get<std::string>() == "ChampSelect") { v = LolClashGameflowPhase::ChampSelect_e; return; } if(j.get<std::string>() == "CheckedIntoTournament") { v = LolClashGameflowPhase::CheckedIntoTournament_e; return; } if(j.get<std::string>() == "EndOfGame") { v = LolClashGameflowPhase::EndOfGame_e; return; } if(j.get<std::string>() == "FailedToLaunch") { v = LolClashGameflowPhase::FailedToLaunch_e; return; } if(j.get<std::string>() == "GameStart") { v = LolClashGameflowPhase::GameStart_e; return; } if(j.get<std::string>() == "InProgress") { v = LolClashGameflowPhase::InProgress_e; return; } if(j.get<std::string>() == "Lobby") { v = LolClashGameflowPhase::Lobby_e; return; } if(j.get<std::string>() == "Matchmaking") { v = LolClashGameflowPhase::Matchmaking_e; return; } if(j.get<std::string>() == "None") { v = LolClashGameflowPhase::None_e; return; } if(j.get<std::string>() == "PreEndOfGame") { v = LolClashGameflowPhase::PreEndOfGame_e; return; } if(j.get<std::string>() == "ReadyCheck") { v = LolClashGameflowPhase::ReadyCheck_e; return; } if(j.get<std::string>() == "Reconnect") { v = LolClashGameflowPhase::Reconnect_e; return; } if(j.get<std::string>() == "TerminatedInError") { v = LolClashGameflowPhase::TerminatedInError_e; return; } if(j.get<std::string>() == "WaitingForStats") { v = LolClashGameflowPhase::WaitingForStats_e; return; } } }
; A086025: a(n) = Sum_{i=1..n} C(i+4,5)^2. ; 1,37,478,3614,19490,82994,296438,923702,2580071,6588075,15606084,34685508,72976852,146387476,281597860,521971876,936053677,1629533233,2761788434,4568378450,7391175350,11718183750,18235516650,27894475050,41997225075,62305185111,91174933032,131727226408,188055603304,265482004840,370867940264,512990908328,702997102937,954942874301,1286438997350,1719413525414,2281010887818,3004646934042,3931241843646,5110655219710,6603350273791,8482316802307,10835285658028,13767270646444,17403477235900 lpb $0 mov $2,$0 sub $0,1 add $2,1 seq $2,151974 ; a(n) = n*(n+1)*(n+2)*(n+3)*(n+4)/8. pow $2,2 add $1,$2 lpe div $1,225 add $1,1 mov $0,$1
_testit: file format elf32-i386 Disassembly of section .text: 00000000 <main>: } exit(); } int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 53 push %ebx e: 51 push %ecx if(argc!=3) f: 83 39 03 cmpl $0x3,(%ecx) { 12: 8b 59 04 mov 0x4(%ecx),%ebx if(argc!=3) 15: 0f 85 9d 00 00 00 jne b8 <main+0xb8> { printf(1,"Invalid command\n"); printf(1,"It should be of form testit num1 num2 where num1 is number of processes and num2 is 1 if you what I/O bound processes 2 if you want cpu bound proceses and 3 if you want to exectute given benchmark and 4 to execute mixed process and 5 to print an optimized process among other which dont which uses MLFQ efficiently.\n"); exit(); } number_of_processes=atoi(argv[1]); 1b: 83 ec 0c sub $0xc,%esp 1e: ff 73 04 pushl 0x4(%ebx) 21: e8 7a 07 00 00 call 7a0 <atoi> // printf(1,"%d\n",number_of_processes); if(number_of_processes==0) 26: 83 c4 10 add $0x10,%esp 29: 85 c0 test %eax,%eax number_of_processes=atoi(argv[1]); 2b: a3 e4 11 00 00 mov %eax,0x11e4 if(number_of_processes==0) 30: 0f 84 bc 00 00 00 je f2 <main+0xf2> { printf(1,"Should be a number in arg 1\n"); exit(); } if(atoi(argv[2])==1) 36: 83 ec 0c sub $0xc,%esp 39: ff 73 08 pushl 0x8(%ebx) 3c: e8 5f 07 00 00 call 7a0 <atoi> 41: 83 c4 10 add $0x10,%esp 44: 83 f8 01 cmp $0x1,%eax 47: 0f 84 a0 00 00 00 je ed <main+0xed> { io(); } else if(atoi(argv[2])==2) 4d: 83 ec 0c sub $0xc,%esp 50: ff 73 08 pushl 0x8(%ebx) 53: e8 48 07 00 00 call 7a0 <atoi> 58: 83 c4 10 add $0x10,%esp 5b: 83 f8 02 cmp $0x2,%eax 5e: 0f 84 84 00 00 00 je e8 <main+0xe8> { cpu(); } else if(atoi(argv[2])==3) 64: 83 ec 0c sub $0xc,%esp 67: ff 73 08 pushl 0x8(%ebx) 6a: e8 31 07 00 00 call 7a0 <atoi> 6f: 83 c4 10 add $0x10,%esp 72: 83 f8 03 cmp $0x3,%eax 75: 74 6c je e3 <main+0xe3> { benchmark(); } else if(atoi(argv[2])==4) 77: 83 ec 0c sub $0xc,%esp 7a: ff 73 08 pushl 0x8(%ebx) 7d: e8 1e 07 00 00 call 7a0 <atoi> 82: 83 c4 10 add $0x10,%esp 85: 83 f8 04 cmp $0x4,%eax 88: 74 54 je de <main+0xde> { mixed(); } else if(atoi(argv[2])==5) 8a: 83 ec 0c sub $0xc,%esp 8d: ff 73 08 pushl 0x8(%ebx) 90: e8 0b 07 00 00 call 7a0 <atoi> 95: 83 c4 10 add $0x10,%esp 98: 83 f8 05 cmp $0x5,%eax 9b: 74 3c je d9 <main+0xd9> { optimized(); } else { printf(1,"Second argument should be integer\n"); 9d: 83 ec 08 sub $0x8,%esp a0: 68 68 0e 00 00 push $0xe68 a5: 6a 01 push $0x1 a7: e8 c4 08 00 00 call 970 <printf> } } ac: 8d 65 f8 lea -0x8(%ebp),%esp af: 31 c0 xor %eax,%eax b1: 59 pop %ecx b2: 5b pop %ebx b3: 5d pop %ebp b4: 8d 61 fc lea -0x4(%ecx),%esp b7: c3 ret printf(1,"Invalid command\n"); b8: 52 push %edx b9: 52 push %edx ba: 68 d5 0c 00 00 push $0xcd5 bf: 6a 01 push $0x1 c1: e8 aa 08 00 00 call 970 <printf> printf(1,"It should be of form testit num1 num2 where num1 is number of processes and num2 is 1 if you what I/O bound processes 2 if you want cpu bound proceses and 3 if you want to exectute given benchmark and 4 to execute mixed process and 5 to print an optimized process among other which dont which uses MLFQ efficiently.\n"); c6: 59 pop %ecx c7: 5b pop %ebx c8: 68 28 0d 00 00 push $0xd28 cd: 6a 01 push $0x1 cf: e8 9c 08 00 00 call 970 <printf> exit(); d4: e8 39 07 00 00 call 812 <exit> optimized(); d9: e8 d2 03 00 00 call 4b0 <optimized> mixed(); de: e8 cd 02 00 00 call 3b0 <mixed> benchmark(); e3: e8 28 00 00 00 call 110 <benchmark> cpu(); e8: e8 e3 01 00 00 call 2d0 <cpu> io(); ed: e8 1e 01 00 00 call 210 <io> printf(1,"Should be a number in arg 1\n"); f2: 50 push %eax f3: 50 push %eax f4: 68 e6 0c 00 00 push $0xce6 f9: 6a 01 push $0x1 fb: e8 70 08 00 00 call 970 <printf> exit(); 100: e8 0d 07 00 00 call 812 <exit> 105: 66 90 xchg %ax,%ax 107: 66 90 xchg %ax,%ax 109: 66 90 xchg %ax,%ax 10b: 66 90 xchg %ax,%ax 10d: 66 90 xchg %ax,%ax 10f: 90 nop 00000110 <benchmark>: { 110: 55 push %ebp 111: 89 e5 mov %esp,%ebp 113: 53 push %ebx 114: 83 ec 14 sub $0x14,%esp for (int j = 0; j < number_of_processes; j++) 117: a1 e4 11 00 00 mov 0x11e4,%eax 11c: 85 c0 test %eax,%eax 11e: 7e 3b jle 15b <benchmark+0x4b> 120: 31 db xor %ebx,%ebx 122: eb 11 jmp 135 <benchmark+0x25> 124: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if (pid == 0) 128: 74 5f je 189 <benchmark+0x79> for (int j = 0; j < number_of_processes; j++) 12a: 83 c3 01 add $0x1,%ebx 12d: 39 1d e4 11 00 00 cmp %ebx,0x11e4 133: 7e 26 jle 15b <benchmark+0x4b> int pid = fork(); 135: e8 d0 06 00 00 call 80a <fork> if (pid < 0) 13a: 85 c0 test %eax,%eax 13c: 79 ea jns 128 <benchmark+0x18> printf(1, "Fork failed\n"); 13e: 83 ec 08 sub $0x8,%esp for (int j = 0; j < number_of_processes; j++) 141: 83 c3 01 add $0x1,%ebx printf(1, "Fork failed\n"); 144: 68 c8 0c 00 00 push $0xcc8 149: 6a 01 push $0x1 14b: e8 20 08 00 00 call 970 <printf> continue; 150: 83 c4 10 add $0x10,%esp for (int j = 0; j < number_of_processes; j++) 153: 39 1d e4 11 00 00 cmp %ebx,0x11e4 159: 7f da jg 135 <benchmark+0x25> for (int j = 0; j < number_of_processes+5; j++) 15b: 83 3d e4 11 00 00 fc cmpl $0xfffffffc,0x11e4 162: 7c 20 jl 184 <benchmark+0x74> 164: 31 db xor %ebx,%ebx 166: 8d 76 00 lea 0x0(%esi),%esi 169: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi wait(); 170: e8 a5 06 00 00 call 81a <wait> for (int j = 0; j < number_of_processes+5; j++) 175: a1 e4 11 00 00 mov 0x11e4,%eax 17a: 83 c3 01 add $0x1,%ebx 17d: 83 c0 04 add $0x4,%eax 180: 39 d8 cmp %ebx,%eax 182: 7d ec jge 170 <benchmark+0x60> exit(); 184: e8 89 06 00 00 call 812 <exit> for (volatile int k = 0; k < number_of_processes; k++) 189: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 190: 8b 45 f4 mov -0xc(%ebp),%eax 193: 3b 05 e4 11 00 00 cmp 0x11e4,%eax 199: 7c 29 jl 1c4 <benchmark+0xb4> 19b: eb 58 jmp 1f5 <benchmark+0xe5> 19d: 8d 76 00 lea 0x0(%esi),%esi sleep(200); //io time 1a0: 83 ec 0c sub $0xc,%esp 1a3: 68 c8 00 00 00 push $0xc8 1a8: e8 f5 06 00 00 call 8a2 <sleep> 1ad: 83 c4 10 add $0x10,%esp for (volatile int k = 0; k < number_of_processes; k++) 1b0: 8b 45 f4 mov -0xc(%ebp),%eax 1b3: 83 c0 01 add $0x1,%eax 1b6: 89 45 f4 mov %eax,-0xc(%ebp) 1b9: 8b 45 f4 mov -0xc(%ebp),%eax 1bc: 3b 05 e4 11 00 00 cmp 0x11e4,%eax 1c2: 7d 31 jge 1f5 <benchmark+0xe5> if (k <= j) 1c4: 8b 45 f4 mov -0xc(%ebp),%eax 1c7: 39 d8 cmp %ebx,%eax 1c9: 7e d5 jle 1a0 <benchmark+0x90> for (i = 0; i < 100000000; i++) 1cb: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 1d2: 8b 45 f0 mov -0x10(%ebp),%eax 1d5: 3d ff e0 f5 05 cmp $0x5f5e0ff,%eax 1da: 7f d4 jg 1b0 <benchmark+0xa0> 1dc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 1e0: 8b 45 f0 mov -0x10(%ebp),%eax 1e3: 83 c0 01 add $0x1,%eax 1e6: 89 45 f0 mov %eax,-0x10(%ebp) 1e9: 8b 45 f0 mov -0x10(%ebp),%eax 1ec: 3d ff e0 f5 05 cmp $0x5f5e0ff,%eax 1f1: 7e ed jle 1e0 <benchmark+0xd0> 1f3: eb bb jmp 1b0 <benchmark+0xa0> printf(1, "Process: %d with PID: %d Finished\n", j,getpid()); 1f5: e8 98 06 00 00 call 892 <getpid> 1fa: 50 push %eax 1fb: 53 push %ebx 1fc: 68 04 0d 00 00 push $0xd04 201: 6a 01 push $0x1 203: e8 68 07 00 00 call 970 <printf> exit(); 208: e8 05 06 00 00 call 812 <exit> 20d: 8d 76 00 lea 0x0(%esi),%esi 00000210 <io>: { 210: 55 push %ebp 211: 89 e5 mov %esp,%ebp 213: 53 push %ebx 214: 83 ec 14 sub $0x14,%esp for (j = 0; j < number_of_processes; j++) 217: a1 e4 11 00 00 mov 0x11e4,%eax 21c: 85 c0 test %eax,%eax 21e: 7e 3b jle 25b <io+0x4b> 220: 31 db xor %ebx,%ebx 222: eb 11 jmp 235 <io+0x25> 224: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if (pid == 0) 228: 74 5f je 289 <io+0x79> for (j = 0; j < number_of_processes; j++) 22a: 83 c3 01 add $0x1,%ebx 22d: 39 1d e4 11 00 00 cmp %ebx,0x11e4 233: 7e 26 jle 25b <io+0x4b> int pid = fork(); 235: e8 d0 05 00 00 call 80a <fork> if (pid < 0) 23a: 85 c0 test %eax,%eax 23c: 79 ea jns 228 <io+0x18> printf(1, "Fork failed\n"); 23e: 83 ec 08 sub $0x8,%esp for (j = 0; j < number_of_processes; j++) 241: 83 c3 01 add $0x1,%ebx printf(1, "Fork failed\n"); 244: 68 c8 0c 00 00 push $0xcc8 249: 6a 01 push $0x1 24b: e8 20 07 00 00 call 970 <printf> continue; 250: 83 c4 10 add $0x10,%esp for (j = 0; j < number_of_processes; j++) 253: 39 1d e4 11 00 00 cmp %ebx,0x11e4 259: 7f da jg 235 <io+0x25> for (j = 0; j < number_of_processes+5; j++) 25b: 83 3d e4 11 00 00 fc cmpl $0xfffffffc,0x11e4 262: 7c 20 jl 284 <io+0x74> 264: 31 db xor %ebx,%ebx 266: 8d 76 00 lea 0x0(%esi),%esi 269: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi wait(); 270: e8 a5 05 00 00 call 81a <wait> for (j = 0; j < number_of_processes+5; j++) 275: a1 e4 11 00 00 mov 0x11e4,%eax 27a: 83 c3 01 add $0x1,%ebx 27d: 83 c0 04 add $0x4,%eax 280: 39 d8 cmp %ebx,%eax 282: 7d ec jge 270 <io+0x60> exit(); 284: e8 89 05 00 00 call 812 <exit> for (volatile int k = 0; k < number_of_processes; k++) 289: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 290: 8b 45 f4 mov -0xc(%ebp),%eax 293: 39 05 e4 11 00 00 cmp %eax,0x11e4 299: 7e e9 jle 284 <io+0x74> 29b: 90 nop 29c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi sleep(300); //io time 2a0: 83 ec 0c sub $0xc,%esp 2a3: 68 2c 01 00 00 push $0x12c 2a8: e8 f5 05 00 00 call 8a2 <sleep> for (volatile int k = 0; k < number_of_processes; k++) 2ad: 8b 45 f4 mov -0xc(%ebp),%eax 2b0: 83 c4 10 add $0x10,%esp 2b3: 83 c0 01 add $0x1,%eax 2b6: 89 45 f4 mov %eax,-0xc(%ebp) 2b9: 8b 45 f4 mov -0xc(%ebp),%eax 2bc: 3b 05 e4 11 00 00 cmp 0x11e4,%eax 2c2: 7c dc jl 2a0 <io+0x90> 2c4: eb be jmp 284 <io+0x74> 2c6: 8d 76 00 lea 0x0(%esi),%esi 2c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000002d0 <cpu>: { 2d0: 55 push %ebp 2d1: 89 e5 mov %esp,%ebp 2d3: 53 push %ebx 2d4: 83 ec 14 sub $0x14,%esp for (j = 0; j < number_of_processes; j++) 2d7: a1 e4 11 00 00 mov 0x11e4,%eax 2dc: 85 c0 test %eax,%eax 2de: 7e 3b jle 31b <cpu+0x4b> 2e0: 31 db xor %ebx,%ebx 2e2: eb 11 jmp 2f5 <cpu+0x25> 2e4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if (pid == 0) 2e8: 74 5f je 349 <cpu+0x79> for (j = 0; j < number_of_processes; j++) 2ea: 83 c3 01 add $0x1,%ebx 2ed: 39 1d e4 11 00 00 cmp %ebx,0x11e4 2f3: 7e 26 jle 31b <cpu+0x4b> int pid = fork(); 2f5: e8 10 05 00 00 call 80a <fork> if (pid < 0) 2fa: 85 c0 test %eax,%eax 2fc: 79 ea jns 2e8 <cpu+0x18> printf(1, "Fork failed\n"); 2fe: 83 ec 08 sub $0x8,%esp for (j = 0; j < number_of_processes; j++) 301: 83 c3 01 add $0x1,%ebx printf(1, "Fork failed\n"); 304: 68 c8 0c 00 00 push $0xcc8 309: 6a 01 push $0x1 30b: e8 60 06 00 00 call 970 <printf> continue; 310: 83 c4 10 add $0x10,%esp for (j = 0; j < number_of_processes; j++) 313: 39 1d e4 11 00 00 cmp %ebx,0x11e4 319: 7f da jg 2f5 <cpu+0x25> for (j = 0; j < number_of_processes+5; j++) 31b: 83 3d e4 11 00 00 fc cmpl $0xfffffffc,0x11e4 322: 7c 20 jl 344 <cpu+0x74> 324: 31 db xor %ebx,%ebx 326: 8d 76 00 lea 0x0(%esi),%esi 329: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi wait(); 330: e8 e5 04 00 00 call 81a <wait> for (j = 0; j < number_of_processes+5; j++) 335: a1 e4 11 00 00 mov 0x11e4,%eax 33a: 83 c3 01 add $0x1,%ebx 33d: 83 c0 04 add $0x4,%eax 340: 39 d8 cmp %ebx,%eax 342: 7d ec jge 330 <cpu+0x60> exit(); 344: e8 c9 04 00 00 call 812 <exit> for (volatile int k = 0; k < number_of_processes; k++) 349: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 350: 8b 45 f4 mov -0xc(%ebp),%eax 353: 39 05 e4 11 00 00 cmp %eax,0x11e4 359: 7e e9 jle 344 <cpu+0x74> 35b: 90 nop 35c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for (i = 0; i < 100000000; i++) 360: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 367: 8b 45 f0 mov -0x10(%ebp),%eax 36a: 3d ff e0 f5 05 cmp $0x5f5e0ff,%eax 36f: 7f 1a jg 38b <cpu+0xbb> 371: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 378: 8b 45 f0 mov -0x10(%ebp),%eax 37b: 83 c0 01 add $0x1,%eax 37e: 89 45 f0 mov %eax,-0x10(%ebp) 381: 8b 45 f0 mov -0x10(%ebp),%eax 384: 3d ff e0 f5 05 cmp $0x5f5e0ff,%eax 389: 7e ed jle 378 <cpu+0xa8> sleep(15); 38b: 83 ec 0c sub $0xc,%esp 38e: 6a 0f push $0xf 390: e8 0d 05 00 00 call 8a2 <sleep> for (volatile int k = 0; k < number_of_processes; k++) 395: 8b 45 f4 mov -0xc(%ebp),%eax 398: 83 c4 10 add $0x10,%esp 39b: 83 c0 01 add $0x1,%eax 39e: 89 45 f4 mov %eax,-0xc(%ebp) 3a1: 8b 45 f4 mov -0xc(%ebp),%eax 3a4: 3b 05 e4 11 00 00 cmp 0x11e4,%eax 3aa: 7c b4 jl 360 <cpu+0x90> 3ac: eb 96 jmp 344 <cpu+0x74> 3ae: 66 90 xchg %ax,%ax 000003b0 <mixed>: { 3b0: 55 push %ebp 3b1: 89 e5 mov %esp,%ebp 3b3: 53 push %ebx 3b4: 83 ec 14 sub $0x14,%esp for (j = 0; j < number_of_processes; j++) 3b7: a1 e4 11 00 00 mov 0x11e4,%eax 3bc: 85 c0 test %eax,%eax 3be: 7e 3b jle 3fb <mixed+0x4b> 3c0: 31 db xor %ebx,%ebx 3c2: eb 11 jmp 3d5 <mixed+0x25> 3c4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if (pid == 0) 3c8: 74 5f je 429 <mixed+0x79> for (j = 0; j < number_of_processes; j++) 3ca: 83 c3 01 add $0x1,%ebx 3cd: 39 1d e4 11 00 00 cmp %ebx,0x11e4 3d3: 7e 26 jle 3fb <mixed+0x4b> int pid = fork(); 3d5: e8 30 04 00 00 call 80a <fork> if (pid < 0) 3da: 85 c0 test %eax,%eax 3dc: 79 ea jns 3c8 <mixed+0x18> printf(1, "Fork failed\n"); 3de: 83 ec 08 sub $0x8,%esp for (j = 0; j < number_of_processes; j++) 3e1: 83 c3 01 add $0x1,%ebx printf(1, "Fork failed\n"); 3e4: 68 c8 0c 00 00 push $0xcc8 3e9: 6a 01 push $0x1 3eb: e8 80 05 00 00 call 970 <printf> continue; 3f0: 83 c4 10 add $0x10,%esp for (j = 0; j < number_of_processes; j++) 3f3: 39 1d e4 11 00 00 cmp %ebx,0x11e4 3f9: 7f da jg 3d5 <mixed+0x25> for (j = 0; j < number_of_processes+5; j++) 3fb: 83 3d e4 11 00 00 fc cmpl $0xfffffffc,0x11e4 402: 7c 20 jl 424 <mixed+0x74> 404: 31 db xor %ebx,%ebx 406: 8d 76 00 lea 0x0(%esi),%esi 409: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi wait(); 410: e8 05 04 00 00 call 81a <wait> for (j = 0; j < number_of_processes+5; j++) 415: a1 e4 11 00 00 mov 0x11e4,%eax 41a: 83 c3 01 add $0x1,%ebx 41d: 83 c0 04 add $0x4,%eax 420: 39 d8 cmp %ebx,%eax 422: 7d ec jge 410 <mixed+0x60> exit(); 424: e8 e9 03 00 00 call 812 <exit> for (volatile int k = 0; k < number_of_processes; k++) 429: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 430: 8b 45 f4 mov -0xc(%ebp),%eax 433: 3b 05 e4 11 00 00 cmp 0x11e4,%eax 439: 7d e9 jge 424 <mixed+0x74> 43b: 83 e3 01 and $0x1,%ebx if(j%2==0) 43e: 85 db test %ebx,%ebx 440: 75 56 jne 498 <mixed+0xe8> 442: 8d b6 00 00 00 00 lea 0x0(%esi),%esi for (i = 0; i < 100000000; i++) 448: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 44f: 8b 45 f0 mov -0x10(%ebp),%eax 452: 3d ff e0 f5 05 cmp $0x5f5e0ff,%eax 457: 7f 1a jg 473 <mixed+0xc3> 459: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 460: 8b 45 f0 mov -0x10(%ebp),%eax 463: 83 c0 01 add $0x1,%eax 466: 89 45 f0 mov %eax,-0x10(%ebp) 469: 8b 45 f0 mov -0x10(%ebp),%eax 46c: 3d ff e0 f5 05 cmp $0x5f5e0ff,%eax 471: 7e ed jle 460 <mixed+0xb0> sleep(15); 473: 83 ec 0c sub $0xc,%esp 476: 6a 0f push $0xf 478: e8 25 04 00 00 call 8a2 <sleep> 47d: 83 c4 10 add $0x10,%esp for (volatile int k = 0; k < number_of_processes; k++) 480: 8b 45 f4 mov -0xc(%ebp),%eax 483: 83 c0 01 add $0x1,%eax 486: 89 45 f4 mov %eax,-0xc(%ebp) 489: 8b 45 f4 mov -0xc(%ebp),%eax 48c: 3b 05 e4 11 00 00 cmp 0x11e4,%eax 492: 7d 90 jge 424 <mixed+0x74> if(j%2==0) 494: 85 db test %ebx,%ebx 496: 74 b0 je 448 <mixed+0x98> sleep(300); //io time 498: 83 ec 0c sub $0xc,%esp 49b: 68 2c 01 00 00 push $0x12c 4a0: e8 fd 03 00 00 call 8a2 <sleep> 4a5: 83 c4 10 add $0x10,%esp 4a8: eb d6 jmp 480 <mixed+0xd0> 4aa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 000004b0 <optimized>: { 4b0: 55 push %ebp 4b1: 89 e5 mov %esp,%ebp 4b3: 53 push %ebx 4b4: 83 ec 14 sub $0x14,%esp for (int j = 0; j < number_of_processes; j++) 4b7: a1 e4 11 00 00 mov 0x11e4,%eax 4bc: 85 c0 test %eax,%eax 4be: 7e 3b jle 4fb <optimized+0x4b> 4c0: 31 db xor %ebx,%ebx 4c2: eb 11 jmp 4d5 <optimized+0x25> 4c4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if (pid == 0) 4c8: 74 5f je 529 <optimized+0x79> for (int j = 0; j < number_of_processes; j++) 4ca: 83 c3 01 add $0x1,%ebx 4cd: 39 1d e4 11 00 00 cmp %ebx,0x11e4 4d3: 7e 26 jle 4fb <optimized+0x4b> int pid = fork(); 4d5: e8 30 03 00 00 call 80a <fork> if (pid < 0) 4da: 85 c0 test %eax,%eax 4dc: 79 ea jns 4c8 <optimized+0x18> printf(1, "Fork failed\n"); 4de: 83 ec 08 sub $0x8,%esp for (int j = 0; j < number_of_processes; j++) 4e1: 83 c3 01 add $0x1,%ebx printf(1, "Fork failed\n"); 4e4: 68 c8 0c 00 00 push $0xcc8 4e9: 6a 01 push $0x1 4eb: e8 80 04 00 00 call 970 <printf> continue; 4f0: 83 c4 10 add $0x10,%esp for (int j = 0; j < number_of_processes; j++) 4f3: 39 1d e4 11 00 00 cmp %ebx,0x11e4 4f9: 7f da jg 4d5 <optimized+0x25> for (int j = 0; j < number_of_processes+5; j++) 4fb: 83 3d e4 11 00 00 fc cmpl $0xfffffffc,0x11e4 502: 7c 20 jl 524 <optimized+0x74> 504: 31 db xor %ebx,%ebx 506: 8d 76 00 lea 0x0(%esi),%esi 509: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi wait(); 510: e8 05 03 00 00 call 81a <wait> for (int j = 0; j < number_of_processes+5; j++) 515: a1 e4 11 00 00 mov 0x11e4,%eax 51a: 83 c3 01 add $0x1,%ebx 51d: 83 c0 04 add $0x4,%eax 520: 39 d8 cmp %ebx,%eax 522: 7d ec jge 510 <optimized+0x60> exit(); 524: e8 e9 02 00 00 call 812 <exit> for (volatile int k = 0; k < number_of_processes; k++) 529: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 530: 8b 15 e4 11 00 00 mov 0x11e4,%edx 536: 8b 45 f4 mov -0xc(%ebp),%eax 539: 39 c2 cmp %eax,%edx 53b: 7e 59 jle 596 <optimized+0xe6> 53d: 8d 76 00 lea 0x0(%esi),%esi if(j==number_of_processes/2) 540: 89 d0 mov %edx,%eax 542: c1 e8 1f shr $0x1f,%eax 545: 01 d0 add %edx,%eax 547: d1 f8 sar %eax 549: 39 d8 cmp %ebx,%eax 54b: 74 61 je 5ae <optimized+0xfe> for (i = 0; i < 100000000; i++) 54d: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 554: 8b 45 f0 mov -0x10(%ebp),%eax 557: 3d ff e0 f5 05 cmp $0x5f5e0ff,%eax 55c: 7f 15 jg 573 <optimized+0xc3> 55e: 66 90 xchg %ax,%ax 560: 8b 45 f0 mov -0x10(%ebp),%eax 563: 83 c0 01 add $0x1,%eax 566: 89 45 f0 mov %eax,-0x10(%ebp) 569: 8b 45 f0 mov -0x10(%ebp),%eax 56c: 3d ff e0 f5 05 cmp $0x5f5e0ff,%eax 571: 7e ed jle 560 <optimized+0xb0> sleep(5); 573: 83 ec 0c sub $0xc,%esp 576: 6a 05 push $0x5 578: e8 25 03 00 00 call 8a2 <sleep> 57d: 83 c4 10 add $0x10,%esp for (volatile int k = 0; k < number_of_processes; k++) 580: 8b 45 f4 mov -0xc(%ebp),%eax 583: 8b 15 e4 11 00 00 mov 0x11e4,%edx 589: 83 c0 01 add $0x1,%eax 58c: 89 45 f4 mov %eax,-0xc(%ebp) 58f: 8b 45 f4 mov -0xc(%ebp),%eax 592: 39 d0 cmp %edx,%eax 594: 7c aa jl 540 <optimized+0x90> printf(1, "Process: %d with PID: %d Finished\n", j,getpid()); 596: e8 f7 02 00 00 call 892 <getpid> 59b: 50 push %eax 59c: 53 push %ebx 59d: 68 04 0d 00 00 push $0xd04 5a2: 6a 01 push $0x1 5a4: e8 c7 03 00 00 call 970 <printf> exit(); 5a9: e8 64 02 00 00 call 812 <exit> sleep(200); 5ae: 83 ec 0c sub $0xc,%esp 5b1: 68 c8 00 00 00 push $0xc8 5b6: e8 e7 02 00 00 call 8a2 <sleep> continue; 5bb: 83 c4 10 add $0x10,%esp 5be: eb c0 jmp 580 <optimized+0xd0> 000005c0 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 5c0: 55 push %ebp 5c1: 89 e5 mov %esp,%ebp 5c3: 53 push %ebx 5c4: 8b 45 08 mov 0x8(%ebp),%eax 5c7: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 5ca: 89 c2 mov %eax,%edx 5cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 5d0: 83 c1 01 add $0x1,%ecx 5d3: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 5d7: 83 c2 01 add $0x1,%edx 5da: 84 db test %bl,%bl 5dc: 88 5a ff mov %bl,-0x1(%edx) 5df: 75 ef jne 5d0 <strcpy+0x10> ; return os; } 5e1: 5b pop %ebx 5e2: 5d pop %ebp 5e3: c3 ret 5e4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 5ea: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000005f0 <strcmp>: int strcmp(const char *p, const char *q) { 5f0: 55 push %ebp 5f1: 89 e5 mov %esp,%ebp 5f3: 53 push %ebx 5f4: 8b 55 08 mov 0x8(%ebp),%edx 5f7: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 5fa: 0f b6 02 movzbl (%edx),%eax 5fd: 0f b6 19 movzbl (%ecx),%ebx 600: 84 c0 test %al,%al 602: 75 1c jne 620 <strcmp+0x30> 604: eb 2a jmp 630 <strcmp+0x40> 606: 8d 76 00 lea 0x0(%esi),%esi 609: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 610: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 613: 0f b6 02 movzbl (%edx),%eax p++, q++; 616: 83 c1 01 add $0x1,%ecx 619: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) 61c: 84 c0 test %al,%al 61e: 74 10 je 630 <strcmp+0x40> 620: 38 d8 cmp %bl,%al 622: 74 ec je 610 <strcmp+0x20> return (uchar)*p - (uchar)*q; 624: 29 d8 sub %ebx,%eax } 626: 5b pop %ebx 627: 5d pop %ebp 628: c3 ret 629: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 630: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 632: 29 d8 sub %ebx,%eax } 634: 5b pop %ebx 635: 5d pop %ebp 636: c3 ret 637: 89 f6 mov %esi,%esi 639: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000640 <strlen>: uint strlen(const char *s) { 640: 55 push %ebp 641: 89 e5 mov %esp,%ebp 643: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 646: 80 39 00 cmpb $0x0,(%ecx) 649: 74 15 je 660 <strlen+0x20> 64b: 31 d2 xor %edx,%edx 64d: 8d 76 00 lea 0x0(%esi),%esi 650: 83 c2 01 add $0x1,%edx 653: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 657: 89 d0 mov %edx,%eax 659: 75 f5 jne 650 <strlen+0x10> ; return n; } 65b: 5d pop %ebp 65c: c3 ret 65d: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) 660: 31 c0 xor %eax,%eax } 662: 5d pop %ebp 663: c3 ret 664: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 66a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000670 <memset>: void* memset(void *dst, int c, uint n) { 670: 55 push %ebp 671: 89 e5 mov %esp,%ebp 673: 57 push %edi 674: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 677: 8b 4d 10 mov 0x10(%ebp),%ecx 67a: 8b 45 0c mov 0xc(%ebp),%eax 67d: 89 d7 mov %edx,%edi 67f: fc cld 680: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 682: 89 d0 mov %edx,%eax 684: 5f pop %edi 685: 5d pop %ebp 686: c3 ret 687: 89 f6 mov %esi,%esi 689: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000690 <strchr>: char* strchr(const char *s, char c) { 690: 55 push %ebp 691: 89 e5 mov %esp,%ebp 693: 53 push %ebx 694: 8b 45 08 mov 0x8(%ebp),%eax 697: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 69a: 0f b6 10 movzbl (%eax),%edx 69d: 84 d2 test %dl,%dl 69f: 74 1d je 6be <strchr+0x2e> if(*s == c) 6a1: 38 d3 cmp %dl,%bl 6a3: 89 d9 mov %ebx,%ecx 6a5: 75 0d jne 6b4 <strchr+0x24> 6a7: eb 17 jmp 6c0 <strchr+0x30> 6a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 6b0: 38 ca cmp %cl,%dl 6b2: 74 0c je 6c0 <strchr+0x30> for(; *s; s++) 6b4: 83 c0 01 add $0x1,%eax 6b7: 0f b6 10 movzbl (%eax),%edx 6ba: 84 d2 test %dl,%dl 6bc: 75 f2 jne 6b0 <strchr+0x20> return (char*)s; return 0; 6be: 31 c0 xor %eax,%eax } 6c0: 5b pop %ebx 6c1: 5d pop %ebp 6c2: c3 ret 6c3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 6c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000006d0 <gets>: char* gets(char *buf, int max) { 6d0: 55 push %ebp 6d1: 89 e5 mov %esp,%ebp 6d3: 57 push %edi 6d4: 56 push %esi 6d5: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 6d6: 31 f6 xor %esi,%esi 6d8: 89 f3 mov %esi,%ebx { 6da: 83 ec 1c sub $0x1c,%esp 6dd: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 6e0: eb 2f jmp 711 <gets+0x41> 6e2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 6e8: 8d 45 e7 lea -0x19(%ebp),%eax 6eb: 83 ec 04 sub $0x4,%esp 6ee: 6a 01 push $0x1 6f0: 50 push %eax 6f1: 6a 00 push $0x0 6f3: e8 32 01 00 00 call 82a <read> if(cc < 1) 6f8: 83 c4 10 add $0x10,%esp 6fb: 85 c0 test %eax,%eax 6fd: 7e 1c jle 71b <gets+0x4b> break; buf[i++] = c; 6ff: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 703: 83 c7 01 add $0x1,%edi 706: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 709: 3c 0a cmp $0xa,%al 70b: 74 23 je 730 <gets+0x60> 70d: 3c 0d cmp $0xd,%al 70f: 74 1f je 730 <gets+0x60> for(i=0; i+1 < max; ){ 711: 83 c3 01 add $0x1,%ebx 714: 3b 5d 0c cmp 0xc(%ebp),%ebx 717: 89 fe mov %edi,%esi 719: 7c cd jl 6e8 <gets+0x18> 71b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 71d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 720: c6 03 00 movb $0x0,(%ebx) } 723: 8d 65 f4 lea -0xc(%ebp),%esp 726: 5b pop %ebx 727: 5e pop %esi 728: 5f pop %edi 729: 5d pop %ebp 72a: c3 ret 72b: 90 nop 72c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 730: 8b 75 08 mov 0x8(%ebp),%esi 733: 8b 45 08 mov 0x8(%ebp),%eax 736: 01 de add %ebx,%esi 738: 89 f3 mov %esi,%ebx buf[i] = '\0'; 73a: c6 03 00 movb $0x0,(%ebx) } 73d: 8d 65 f4 lea -0xc(%ebp),%esp 740: 5b pop %ebx 741: 5e pop %esi 742: 5f pop %edi 743: 5d pop %ebp 744: c3 ret 745: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 749: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000750 <stat>: int stat(const char *n, struct stat *st) { 750: 55 push %ebp 751: 89 e5 mov %esp,%ebp 753: 56 push %esi 754: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 755: 83 ec 08 sub $0x8,%esp 758: 6a 00 push $0x0 75a: ff 75 08 pushl 0x8(%ebp) 75d: e8 f0 00 00 00 call 852 <open> if(fd < 0) 762: 83 c4 10 add $0x10,%esp 765: 85 c0 test %eax,%eax 767: 78 27 js 790 <stat+0x40> return -1; r = fstat(fd, st); 769: 83 ec 08 sub $0x8,%esp 76c: ff 75 0c pushl 0xc(%ebp) 76f: 89 c3 mov %eax,%ebx 771: 50 push %eax 772: e8 f3 00 00 00 call 86a <fstat> close(fd); 777: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 77a: 89 c6 mov %eax,%esi close(fd); 77c: e8 b9 00 00 00 call 83a <close> return r; 781: 83 c4 10 add $0x10,%esp } 784: 8d 65 f8 lea -0x8(%ebp),%esp 787: 89 f0 mov %esi,%eax 789: 5b pop %ebx 78a: 5e pop %esi 78b: 5d pop %ebp 78c: c3 ret 78d: 8d 76 00 lea 0x0(%esi),%esi return -1; 790: be ff ff ff ff mov $0xffffffff,%esi 795: eb ed jmp 784 <stat+0x34> 797: 89 f6 mov %esi,%esi 799: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000007a0 <atoi>: int atoi(const char *s) { 7a0: 55 push %ebp 7a1: 89 e5 mov %esp,%ebp 7a3: 53 push %ebx 7a4: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 7a7: 0f be 11 movsbl (%ecx),%edx 7aa: 8d 42 d0 lea -0x30(%edx),%eax 7ad: 3c 09 cmp $0x9,%al n = 0; 7af: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 7b4: 77 1f ja 7d5 <atoi+0x35> 7b6: 8d 76 00 lea 0x0(%esi),%esi 7b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 7c0: 8d 04 80 lea (%eax,%eax,4),%eax 7c3: 83 c1 01 add $0x1,%ecx 7c6: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 7ca: 0f be 11 movsbl (%ecx),%edx 7cd: 8d 5a d0 lea -0x30(%edx),%ebx 7d0: 80 fb 09 cmp $0x9,%bl 7d3: 76 eb jbe 7c0 <atoi+0x20> return n; } 7d5: 5b pop %ebx 7d6: 5d pop %ebp 7d7: c3 ret 7d8: 90 nop 7d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000007e0 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 7e0: 55 push %ebp 7e1: 89 e5 mov %esp,%ebp 7e3: 56 push %esi 7e4: 53 push %ebx 7e5: 8b 5d 10 mov 0x10(%ebp),%ebx 7e8: 8b 45 08 mov 0x8(%ebp),%eax 7eb: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 7ee: 85 db test %ebx,%ebx 7f0: 7e 14 jle 806 <memmove+0x26> 7f2: 31 d2 xor %edx,%edx 7f4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 7f8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 7fc: 88 0c 10 mov %cl,(%eax,%edx,1) 7ff: 83 c2 01 add $0x1,%edx while(n-- > 0) 802: 39 d3 cmp %edx,%ebx 804: 75 f2 jne 7f8 <memmove+0x18> return vdst; } 806: 5b pop %ebx 807: 5e pop %esi 808: 5d pop %ebp 809: c3 ret 0000080a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 80a: b8 01 00 00 00 mov $0x1,%eax 80f: cd 40 int $0x40 811: c3 ret 00000812 <exit>: SYSCALL(exit) 812: b8 02 00 00 00 mov $0x2,%eax 817: cd 40 int $0x40 819: c3 ret 0000081a <wait>: SYSCALL(wait) 81a: b8 03 00 00 00 mov $0x3,%eax 81f: cd 40 int $0x40 821: c3 ret 00000822 <pipe>: SYSCALL(pipe) 822: b8 04 00 00 00 mov $0x4,%eax 827: cd 40 int $0x40 829: c3 ret 0000082a <read>: SYSCALL(read) 82a: b8 05 00 00 00 mov $0x5,%eax 82f: cd 40 int $0x40 831: c3 ret 00000832 <write>: SYSCALL(write) 832: b8 10 00 00 00 mov $0x10,%eax 837: cd 40 int $0x40 839: c3 ret 0000083a <close>: SYSCALL(close) 83a: b8 15 00 00 00 mov $0x15,%eax 83f: cd 40 int $0x40 841: c3 ret 00000842 <kill>: SYSCALL(kill) 842: b8 06 00 00 00 mov $0x6,%eax 847: cd 40 int $0x40 849: c3 ret 0000084a <exec>: SYSCALL(exec) 84a: b8 07 00 00 00 mov $0x7,%eax 84f: cd 40 int $0x40 851: c3 ret 00000852 <open>: SYSCALL(open) 852: b8 0f 00 00 00 mov $0xf,%eax 857: cd 40 int $0x40 859: c3 ret 0000085a <mknod>: SYSCALL(mknod) 85a: b8 11 00 00 00 mov $0x11,%eax 85f: cd 40 int $0x40 861: c3 ret 00000862 <unlink>: SYSCALL(unlink) 862: b8 12 00 00 00 mov $0x12,%eax 867: cd 40 int $0x40 869: c3 ret 0000086a <fstat>: SYSCALL(fstat) 86a: b8 08 00 00 00 mov $0x8,%eax 86f: cd 40 int $0x40 871: c3 ret 00000872 <link>: SYSCALL(link) 872: b8 13 00 00 00 mov $0x13,%eax 877: cd 40 int $0x40 879: c3 ret 0000087a <mkdir>: SYSCALL(mkdir) 87a: b8 14 00 00 00 mov $0x14,%eax 87f: cd 40 int $0x40 881: c3 ret 00000882 <chdir>: SYSCALL(chdir) 882: b8 09 00 00 00 mov $0x9,%eax 887: cd 40 int $0x40 889: c3 ret 0000088a <dup>: SYSCALL(dup) 88a: b8 0a 00 00 00 mov $0xa,%eax 88f: cd 40 int $0x40 891: c3 ret 00000892 <getpid>: SYSCALL(getpid) 892: b8 0b 00 00 00 mov $0xb,%eax 897: cd 40 int $0x40 899: c3 ret 0000089a <sbrk>: SYSCALL(sbrk) 89a: b8 0c 00 00 00 mov $0xc,%eax 89f: cd 40 int $0x40 8a1: c3 ret 000008a2 <sleep>: SYSCALL(sleep) 8a2: b8 0d 00 00 00 mov $0xd,%eax 8a7: cd 40 int $0x40 8a9: c3 ret 000008aa <uptime>: SYSCALL(uptime) 8aa: b8 0e 00 00 00 mov $0xe,%eax 8af: cd 40 int $0x40 8b1: c3 ret 000008b2 <waitx>: SYSCALL(waitx) 8b2: b8 16 00 00 00 mov $0x16,%eax 8b7: cd 40 int $0x40 8b9: c3 ret 000008ba <set_priority>: SYSCALL(set_priority) 8ba: b8 17 00 00 00 mov $0x17,%eax 8bf: cd 40 int $0x40 8c1: c3 ret 000008c2 <ps>: SYSCALL(ps) 8c2: b8 18 00 00 00 mov $0x18,%eax 8c7: cd 40 int $0x40 8c9: c3 ret 8ca: 66 90 xchg %ax,%ax 8cc: 66 90 xchg %ax,%ax 8ce: 66 90 xchg %ax,%ax 000008d0 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 8d0: 55 push %ebp 8d1: 89 e5 mov %esp,%ebp 8d3: 57 push %edi 8d4: 56 push %esi 8d5: 53 push %ebx 8d6: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 8d9: 85 d2 test %edx,%edx { 8db: 89 45 c0 mov %eax,-0x40(%ebp) neg = 1; x = -xx; 8de: 89 d0 mov %edx,%eax if(sgn && xx < 0){ 8e0: 79 76 jns 958 <printint+0x88> 8e2: f6 45 08 01 testb $0x1,0x8(%ebp) 8e6: 74 70 je 958 <printint+0x88> x = -xx; 8e8: f7 d8 neg %eax neg = 1; 8ea: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) } else { x = xx; } i = 0; 8f1: 31 f6 xor %esi,%esi 8f3: 8d 5d d7 lea -0x29(%ebp),%ebx 8f6: eb 0a jmp 902 <printint+0x32> 8f8: 90 nop 8f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi do{ buf[i++] = digits[x % base]; 900: 89 fe mov %edi,%esi 902: 31 d2 xor %edx,%edx 904: 8d 7e 01 lea 0x1(%esi),%edi 907: f7 f1 div %ecx 909: 0f b6 92 94 0e 00 00 movzbl 0xe94(%edx),%edx }while((x /= base) != 0); 910: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 912: 88 14 3b mov %dl,(%ebx,%edi,1) }while((x /= base) != 0); 915: 75 e9 jne 900 <printint+0x30> if(neg) 917: 8b 45 c4 mov -0x3c(%ebp),%eax 91a: 85 c0 test %eax,%eax 91c: 74 08 je 926 <printint+0x56> buf[i++] = '-'; 91e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 923: 8d 7e 02 lea 0x2(%esi),%edi 926: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi 92a: 8b 7d c0 mov -0x40(%ebp),%edi 92d: 8d 76 00 lea 0x0(%esi),%esi 930: 0f b6 06 movzbl (%esi),%eax write(fd, &c, 1); 933: 83 ec 04 sub $0x4,%esp 936: 83 ee 01 sub $0x1,%esi 939: 6a 01 push $0x1 93b: 53 push %ebx 93c: 57 push %edi 93d: 88 45 d7 mov %al,-0x29(%ebp) 940: e8 ed fe ff ff call 832 <write> while(--i >= 0) 945: 83 c4 10 add $0x10,%esp 948: 39 de cmp %ebx,%esi 94a: 75 e4 jne 930 <printint+0x60> putc(fd, buf[i]); } 94c: 8d 65 f4 lea -0xc(%ebp),%esp 94f: 5b pop %ebx 950: 5e pop %esi 951: 5f pop %edi 952: 5d pop %ebp 953: c3 ret 954: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 958: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 95f: eb 90 jmp 8f1 <printint+0x21> 961: eb 0d jmp 970 <printf> 963: 90 nop 964: 90 nop 965: 90 nop 966: 90 nop 967: 90 nop 968: 90 nop 969: 90 nop 96a: 90 nop 96b: 90 nop 96c: 90 nop 96d: 90 nop 96e: 90 nop 96f: 90 nop 00000970 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 970: 55 push %ebp 971: 89 e5 mov %esp,%ebp 973: 57 push %edi 974: 56 push %esi 975: 53 push %ebx 976: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 979: 8b 75 0c mov 0xc(%ebp),%esi 97c: 0f b6 1e movzbl (%esi),%ebx 97f: 84 db test %bl,%bl 981: 0f 84 b3 00 00 00 je a3a <printf+0xca> ap = (uint*)(void*)&fmt + 1; 987: 8d 45 10 lea 0x10(%ebp),%eax 98a: 83 c6 01 add $0x1,%esi state = 0; 98d: 31 ff xor %edi,%edi ap = (uint*)(void*)&fmt + 1; 98f: 89 45 d4 mov %eax,-0x2c(%ebp) 992: eb 2f jmp 9c3 <printf+0x53> 994: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 998: 83 f8 25 cmp $0x25,%eax 99b: 0f 84 a7 00 00 00 je a48 <printf+0xd8> write(fd, &c, 1); 9a1: 8d 45 e2 lea -0x1e(%ebp),%eax 9a4: 83 ec 04 sub $0x4,%esp 9a7: 88 5d e2 mov %bl,-0x1e(%ebp) 9aa: 6a 01 push $0x1 9ac: 50 push %eax 9ad: ff 75 08 pushl 0x8(%ebp) 9b0: e8 7d fe ff ff call 832 <write> 9b5: 83 c4 10 add $0x10,%esp 9b8: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 9bb: 0f b6 5e ff movzbl -0x1(%esi),%ebx 9bf: 84 db test %bl,%bl 9c1: 74 77 je a3a <printf+0xca> if(state == 0){ 9c3: 85 ff test %edi,%edi c = fmt[i] & 0xff; 9c5: 0f be cb movsbl %bl,%ecx 9c8: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 9cb: 74 cb je 998 <printf+0x28> state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 9cd: 83 ff 25 cmp $0x25,%edi 9d0: 75 e6 jne 9b8 <printf+0x48> if(c == 'd'){ 9d2: 83 f8 64 cmp $0x64,%eax 9d5: 0f 84 05 01 00 00 je ae0 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 9db: 81 e1 f7 00 00 00 and $0xf7,%ecx 9e1: 83 f9 70 cmp $0x70,%ecx 9e4: 74 72 je a58 <printf+0xe8> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 9e6: 83 f8 73 cmp $0x73,%eax 9e9: 0f 84 99 00 00 00 je a88 <printf+0x118> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 9ef: 83 f8 63 cmp $0x63,%eax 9f2: 0f 84 08 01 00 00 je b00 <printf+0x190> putc(fd, *ap); ap++; } else if(c == '%'){ 9f8: 83 f8 25 cmp $0x25,%eax 9fb: 0f 84 ef 00 00 00 je af0 <printf+0x180> write(fd, &c, 1); a01: 8d 45 e7 lea -0x19(%ebp),%eax a04: 83 ec 04 sub $0x4,%esp a07: c6 45 e7 25 movb $0x25,-0x19(%ebp) a0b: 6a 01 push $0x1 a0d: 50 push %eax a0e: ff 75 08 pushl 0x8(%ebp) a11: e8 1c fe ff ff call 832 <write> a16: 83 c4 0c add $0xc,%esp a19: 8d 45 e6 lea -0x1a(%ebp),%eax a1c: 88 5d e6 mov %bl,-0x1a(%ebp) a1f: 6a 01 push $0x1 a21: 50 push %eax a22: ff 75 08 pushl 0x8(%ebp) a25: 83 c6 01 add $0x1,%esi } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; a28: 31 ff xor %edi,%edi write(fd, &c, 1); a2a: e8 03 fe ff ff call 832 <write> for(i = 0; fmt[i]; i++){ a2f: 0f b6 5e ff movzbl -0x1(%esi),%ebx write(fd, &c, 1); a33: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ a36: 84 db test %bl,%bl a38: 75 89 jne 9c3 <printf+0x53> } } } a3a: 8d 65 f4 lea -0xc(%ebp),%esp a3d: 5b pop %ebx a3e: 5e pop %esi a3f: 5f pop %edi a40: 5d pop %ebp a41: c3 ret a42: 8d b6 00 00 00 00 lea 0x0(%esi),%esi state = '%'; a48: bf 25 00 00 00 mov $0x25,%edi a4d: e9 66 ff ff ff jmp 9b8 <printf+0x48> a52: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); a58: 83 ec 0c sub $0xc,%esp a5b: b9 10 00 00 00 mov $0x10,%ecx a60: 6a 00 push $0x0 a62: 8b 7d d4 mov -0x2c(%ebp),%edi a65: 8b 45 08 mov 0x8(%ebp),%eax a68: 8b 17 mov (%edi),%edx a6a: e8 61 fe ff ff call 8d0 <printint> ap++; a6f: 89 f8 mov %edi,%eax a71: 83 c4 10 add $0x10,%esp state = 0; a74: 31 ff xor %edi,%edi ap++; a76: 83 c0 04 add $0x4,%eax a79: 89 45 d4 mov %eax,-0x2c(%ebp) a7c: e9 37 ff ff ff jmp 9b8 <printf+0x48> a81: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; a88: 8b 45 d4 mov -0x2c(%ebp),%eax a8b: 8b 08 mov (%eax),%ecx ap++; a8d: 83 c0 04 add $0x4,%eax a90: 89 45 d4 mov %eax,-0x2c(%ebp) if(s == 0) a93: 85 c9 test %ecx,%ecx a95: 0f 84 8e 00 00 00 je b29 <printf+0x1b9> while(*s != 0){ a9b: 0f b6 01 movzbl (%ecx),%eax state = 0; a9e: 31 ff xor %edi,%edi s = (char*)*ap; aa0: 89 cb mov %ecx,%ebx while(*s != 0){ aa2: 84 c0 test %al,%al aa4: 0f 84 0e ff ff ff je 9b8 <printf+0x48> aaa: 89 75 d0 mov %esi,-0x30(%ebp) aad: 89 de mov %ebx,%esi aaf: 8b 5d 08 mov 0x8(%ebp),%ebx ab2: 8d 7d e3 lea -0x1d(%ebp),%edi ab5: 8d 76 00 lea 0x0(%esi),%esi write(fd, &c, 1); ab8: 83 ec 04 sub $0x4,%esp s++; abb: 83 c6 01 add $0x1,%esi abe: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); ac1: 6a 01 push $0x1 ac3: 57 push %edi ac4: 53 push %ebx ac5: e8 68 fd ff ff call 832 <write> while(*s != 0){ aca: 0f b6 06 movzbl (%esi),%eax acd: 83 c4 10 add $0x10,%esp ad0: 84 c0 test %al,%al ad2: 75 e4 jne ab8 <printf+0x148> ad4: 8b 75 d0 mov -0x30(%ebp),%esi state = 0; ad7: 31 ff xor %edi,%edi ad9: e9 da fe ff ff jmp 9b8 <printf+0x48> ade: 66 90 xchg %ax,%ax printint(fd, *ap, 10, 1); ae0: 83 ec 0c sub $0xc,%esp ae3: b9 0a 00 00 00 mov $0xa,%ecx ae8: 6a 01 push $0x1 aea: e9 73 ff ff ff jmp a62 <printf+0xf2> aef: 90 nop write(fd, &c, 1); af0: 83 ec 04 sub $0x4,%esp af3: 88 5d e5 mov %bl,-0x1b(%ebp) af6: 8d 45 e5 lea -0x1b(%ebp),%eax af9: 6a 01 push $0x1 afb: e9 21 ff ff ff jmp a21 <printf+0xb1> putc(fd, *ap); b00: 8b 7d d4 mov -0x2c(%ebp),%edi write(fd, &c, 1); b03: 83 ec 04 sub $0x4,%esp putc(fd, *ap); b06: 8b 07 mov (%edi),%eax write(fd, &c, 1); b08: 6a 01 push $0x1 ap++; b0a: 83 c7 04 add $0x4,%edi putc(fd, *ap); b0d: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); b10: 8d 45 e4 lea -0x1c(%ebp),%eax b13: 50 push %eax b14: ff 75 08 pushl 0x8(%ebp) b17: e8 16 fd ff ff call 832 <write> ap++; b1c: 89 7d d4 mov %edi,-0x2c(%ebp) b1f: 83 c4 10 add $0x10,%esp state = 0; b22: 31 ff xor %edi,%edi b24: e9 8f fe ff ff jmp 9b8 <printf+0x48> s = "(null)"; b29: bb 8c 0e 00 00 mov $0xe8c,%ebx while(*s != 0){ b2e: b8 28 00 00 00 mov $0x28,%eax b33: e9 72 ff ff ff jmp aaa <printf+0x13a> b38: 66 90 xchg %ax,%ax b3a: 66 90 xchg %ax,%ax b3c: 66 90 xchg %ax,%ax b3e: 66 90 xchg %ax,%ax 00000b40 <free>: static Header base; static Header *freep; void free(void *ap) { b40: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) b41: a1 d8 11 00 00 mov 0x11d8,%eax { b46: 89 e5 mov %esp,%ebp b48: 57 push %edi b49: 56 push %esi b4a: 53 push %ebx b4b: 8b 5d 08 mov 0x8(%ebp),%ebx bp = (Header*)ap - 1; b4e: 8d 4b f8 lea -0x8(%ebx),%ecx b51: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) b58: 39 c8 cmp %ecx,%eax b5a: 8b 10 mov (%eax),%edx b5c: 73 32 jae b90 <free+0x50> b5e: 39 d1 cmp %edx,%ecx b60: 72 04 jb b66 <free+0x26> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) b62: 39 d0 cmp %edx,%eax b64: 72 32 jb b98 <free+0x58> break; if(bp + bp->s.size == p->s.ptr){ b66: 8b 73 fc mov -0x4(%ebx),%esi b69: 8d 3c f1 lea (%ecx,%esi,8),%edi b6c: 39 fa cmp %edi,%edx b6e: 74 30 je ba0 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; b70: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ b73: 8b 50 04 mov 0x4(%eax),%edx b76: 8d 34 d0 lea (%eax,%edx,8),%esi b79: 39 f1 cmp %esi,%ecx b7b: 74 3a je bb7 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; b7d: 89 08 mov %ecx,(%eax) freep = p; b7f: a3 d8 11 00 00 mov %eax,0x11d8 } b84: 5b pop %ebx b85: 5e pop %esi b86: 5f pop %edi b87: 5d pop %ebp b88: c3 ret b89: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) b90: 39 d0 cmp %edx,%eax b92: 72 04 jb b98 <free+0x58> b94: 39 d1 cmp %edx,%ecx b96: 72 ce jb b66 <free+0x26> { b98: 89 d0 mov %edx,%eax b9a: eb bc jmp b58 <free+0x18> b9c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; ba0: 03 72 04 add 0x4(%edx),%esi ba3: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; ba6: 8b 10 mov (%eax),%edx ba8: 8b 12 mov (%edx),%edx baa: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ bad: 8b 50 04 mov 0x4(%eax),%edx bb0: 8d 34 d0 lea (%eax,%edx,8),%esi bb3: 39 f1 cmp %esi,%ecx bb5: 75 c6 jne b7d <free+0x3d> p->s.size += bp->s.size; bb7: 03 53 fc add -0x4(%ebx),%edx freep = p; bba: a3 d8 11 00 00 mov %eax,0x11d8 p->s.size += bp->s.size; bbf: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; bc2: 8b 53 f8 mov -0x8(%ebx),%edx bc5: 89 10 mov %edx,(%eax) } bc7: 5b pop %ebx bc8: 5e pop %esi bc9: 5f pop %edi bca: 5d pop %ebp bcb: c3 ret bcc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000bd0 <malloc>: return freep; } void* malloc(uint nbytes) { bd0: 55 push %ebp bd1: 89 e5 mov %esp,%ebp bd3: 57 push %edi bd4: 56 push %esi bd5: 53 push %ebx bd6: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; bd9: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ bdc: 8b 15 d8 11 00 00 mov 0x11d8,%edx nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; be2: 8d 78 07 lea 0x7(%eax),%edi be5: c1 ef 03 shr $0x3,%edi be8: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ beb: 85 d2 test %edx,%edx bed: 0f 84 9d 00 00 00 je c90 <malloc+0xc0> bf3: 8b 02 mov (%edx),%eax bf5: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ bf8: 39 cf cmp %ecx,%edi bfa: 76 6c jbe c68 <malloc+0x98> bfc: 81 ff 00 10 00 00 cmp $0x1000,%edi c02: bb 00 10 00 00 mov $0x1000,%ebx c07: 0f 43 df cmovae %edi,%ebx p = sbrk(nu * sizeof(Header)); c0a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi c11: eb 0e jmp c21 <malloc+0x51> c13: 90 nop c14: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ c18: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ c1a: 8b 48 04 mov 0x4(%eax),%ecx c1d: 39 f9 cmp %edi,%ecx c1f: 73 47 jae c68 <malloc+0x98> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) c21: 39 05 d8 11 00 00 cmp %eax,0x11d8 c27: 89 c2 mov %eax,%edx c29: 75 ed jne c18 <malloc+0x48> p = sbrk(nu * sizeof(Header)); c2b: 83 ec 0c sub $0xc,%esp c2e: 56 push %esi c2f: e8 66 fc ff ff call 89a <sbrk> if(p == (char*)-1) c34: 83 c4 10 add $0x10,%esp c37: 83 f8 ff cmp $0xffffffff,%eax c3a: 74 1c je c58 <malloc+0x88> hp->s.size = nu; c3c: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); c3f: 83 ec 0c sub $0xc,%esp c42: 83 c0 08 add $0x8,%eax c45: 50 push %eax c46: e8 f5 fe ff ff call b40 <free> return freep; c4b: 8b 15 d8 11 00 00 mov 0x11d8,%edx if((p = morecore(nunits)) == 0) c51: 83 c4 10 add $0x10,%esp c54: 85 d2 test %edx,%edx c56: 75 c0 jne c18 <malloc+0x48> return 0; } } c58: 8d 65 f4 lea -0xc(%ebp),%esp return 0; c5b: 31 c0 xor %eax,%eax } c5d: 5b pop %ebx c5e: 5e pop %esi c5f: 5f pop %edi c60: 5d pop %ebp c61: c3 ret c62: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if(p->s.size == nunits) c68: 39 cf cmp %ecx,%edi c6a: 74 54 je cc0 <malloc+0xf0> p->s.size -= nunits; c6c: 29 f9 sub %edi,%ecx c6e: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; c71: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; c74: 89 78 04 mov %edi,0x4(%eax) freep = prevp; c77: 89 15 d8 11 00 00 mov %edx,0x11d8 } c7d: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); c80: 83 c0 08 add $0x8,%eax } c83: 5b pop %ebx c84: 5e pop %esi c85: 5f pop %edi c86: 5d pop %ebp c87: c3 ret c88: 90 nop c89: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; c90: c7 05 d8 11 00 00 dc movl $0x11dc,0x11d8 c97: 11 00 00 c9a: c7 05 dc 11 00 00 dc movl $0x11dc,0x11dc ca1: 11 00 00 base.s.size = 0; ca4: b8 dc 11 00 00 mov $0x11dc,%eax ca9: c7 05 e0 11 00 00 00 movl $0x0,0x11e0 cb0: 00 00 00 cb3: e9 44 ff ff ff jmp bfc <malloc+0x2c> cb8: 90 nop cb9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi prevp->s.ptr = p->s.ptr; cc0: 8b 08 mov (%eax),%ecx cc2: 89 0a mov %ecx,(%edx) cc4: eb b1 jmp c77 <malloc+0xa7>
/* $Id: HostDnsServiceResolvConf.cpp $ */ /** @file * Base class for Host DNS & Co services. */ /* * Copyright (C) 2014 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /* -*- indent-tabs-mode: nil; -*- */ #include <VBox/com/string.h> #include <VBox/com/ptr.h> #ifdef RT_OS_OS2 # include <sys/socket.h> typedef int socklen_t; #endif #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <iprt/assert.h> #include <iprt/err.h> #include <iprt/file.h> #include <iprt/critsect.h> #include <VBox/log.h> #include <string> #include "HostDnsService.h" #include "../../Devices/Network/slirp/resolv_conf_parser.h" struct HostDnsServiceResolvConf::Data { Data(const char *fileName):resolvConfFilename(fileName){}; std::string resolvConfFilename; }; const std::string& HostDnsServiceResolvConf::resolvConf() const { return m->resolvConfFilename; } HostDnsServiceResolvConf::~HostDnsServiceResolvConf() { if (m) { delete m; m = NULL; } } HRESULT HostDnsServiceResolvConf::init(VirtualBox *virtualbox, const char *aResolvConfFileName) { m = new Data(aResolvConfFileName); HostDnsMonitor::init(virtualbox); readResolvConf(); return S_OK; } HRESULT HostDnsServiceResolvConf::readResolvConf() { struct rcp_state st; st.rcps_flags = RCPSF_NO_STR2IPCONV; int rc = rcp_parse(&st, m->resolvConfFilename.c_str()); if (rc == -1) return S_OK; HostDnsInformation info; for (unsigned i = 0; i != st.rcps_num_nameserver; ++i) { AssertBreak(st.rcps_str_nameserver[i]); info.servers.push_back(st.rcps_str_nameserver[i]); } if (st.rcps_domain) info.domain = st.rcps_domain; for (unsigned i = 0; i != st.rcps_num_searchlist; ++i) { AssertBreak(st.rcps_searchlist[i]); info.searchList.push_back(st.rcps_searchlist[i]); } setInfo(info); return S_OK; }
SECTION code_fp_math16 PUBLIC ___h2sint PUBLIC _f16_i16_f16 EXTERN cm16_sdcc___h2sint defc ___h2sint = cm16_sdcc___h2sint defc _f16_i16_f16 = cm16_sdcc___h2sint
INCLUDE "clib_cfg.asm" SECTION code_clib SECTION code_math PUBLIC l_fast_mulu_8_8x8 EXTERN l_fast_mulu_16_8x8 ; unsigned multiplication of two 8-bit ; multiplicands into a sixteen bit product ; ; error reported on overflow ; ; enter : l = 8-bit multiplicand ; e = 8-bit multiplicand ; ; exit : a = 0 ; d = 0 ; ; success ; ; h = 0 (LIA-1 enabled only) ; l = 8-bit product ; carry reset ; ; unsigned overflow (LIA-1 enabled only) ; ; h = $ff ; l = $ff = UCHAR_MAX ; carry set, errno = ERANGE ; ; uses : af, b, de, hl ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_IMATH_FAST & $80 EXTERN error_mulu_overflow_mc l_fast_mulu_8_8x8: call l_fast_mulu_16_8x8 inc h dec h ret z jp error_mulu_overflow_mc ELSE defc l_fast_mulu_8_8x8 = l_fast_mulu_16_8x8 ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "EditorSelectionAccentSystemComponent.h" #include <AzCore/Debug/Profiler.h> #include <AzCore/Debug/Trace.h> #include <AzCore/Component/TickBus.h> #include <AzCore/Component/TransformBus.h> #include <AzToolsFramework/API/ComponentEntityObjectBus.h> #include <AzFramework/Entity/EntityContextBus.h> #include <AzCore/Slice/SliceComponent.h> namespace AzToolsFramework { namespace Components { void EditorSelectionAccentSystemComponent::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context)) { serialize->Class<EditorSelectionAccentSystemComponent, AZ::Component>() ->Version(0) ; if (AZ::EditContext* ec = serialize->GetEditContext()) { ec->Class<EditorSelectionAccentSystemComponent>("EditorSelectionAccenting", "Used for selection accenting behavior in the viewport") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System")) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ; } } } void EditorSelectionAccentSystemComponent::Activate() { AzToolsFramework::ToolsApplicationEvents::Bus::Handler::BusConnect(); AzToolsFramework::Components::EditorSelectionAccentingRequestBus::Handler::BusConnect(); } void EditorSelectionAccentSystemComponent::AfterEntityHighlightingChanged() { if (!m_isAccentRefreshQueued) { QueueAccentRefresh(); } } void EditorSelectionAccentSystemComponent::AfterEntitySelectionChanged(const AzToolsFramework::EntityIdList&, const AzToolsFramework::EntityIdList&) { if (!m_isAccentRefreshQueued) { QueueAccentRefresh(); } } void EditorSelectionAccentSystemComponent::QueueAccentRefresh() { AZ_Assert(!m_isAccentRefreshQueued, "Queueing another accent refresh when one is already queued!"); m_isAccentRefreshQueued = true; AZStd::function<void()> accentRefreshCallback = [this]() { AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorSelectionAccentSystemComponent::QueueAccentRefresh:AccentRefreshCallback"); InvalidateAccents(); RecalculateAndApplyAccents(); m_isAccentRefreshQueued = false; }; AZ::TickBus::QueueFunction(accentRefreshCallback); } void EditorSelectionAccentSystemComponent::ForceSelectionAccentRefresh() { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); InvalidateAccents(); RecalculateAndApplyAccents(); } void EditorSelectionAccentSystemComponent::InvalidateAccents() { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); for (const AZ::EntityId& accentedEntity : m_currentlyAccentedEntities) { AzToolsFramework::ComponentEntityEditorRequestBus::Event(accentedEntity, &AzToolsFramework::ComponentEntityEditorRequests::SetSandboxObjectAccent, ComponentEntityAccentType::None); } m_currentlyAccentedEntities.clear(); } void EditorSelectionAccentSystemComponent::RecalculateAndApplyAccents() { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); AzToolsFramework::EntityIdList selectedEntities; AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntities, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); AzToolsFramework::EntityIdSet selectedEntitiesSet; selectedEntitiesSet.insert(selectedEntities.begin(), selectedEntities.end()); for (const AZ::EntityId& selectedEntity : selectedEntities) { // Set selected entities accent to 'Selected' AzToolsFramework::ComponentEntityEditorRequestBus::Event(selectedEntity, &AzToolsFramework::ComponentEntityEditorRequests::SetSandboxObjectAccent, ComponentEntityAccentType::Selected); m_currentlyAccentedEntities.insert(selectedEntity); // Find all selected entities children and Set their accent to 'Parent Selected' AzToolsFramework::EntityIdList descendants; AZ::TransformBus::EventResult(descendants, selectedEntity, &AZ::TransformInterface::GetAllDescendants); for (const AZ::EntityId& descendant : descendants) { if (selectedEntitiesSet.find(descendant) == selectedEntitiesSet.end()) { AzToolsFramework::ComponentEntityEditorRequestBus::Event(descendant, &ComponentEntityEditorRequests::SetSandboxObjectAccent, ComponentEntityAccentType::ParentSelected); m_currentlyAccentedEntities.insert(descendant); } } } // Find Hovered entities // Set their accent to 'Hover' AzToolsFramework::EntityIdList highlightedEntities; AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(highlightedEntities, &AzToolsFramework::ToolsApplicationRequests::GetHighlightedEntities); for (const AZ::EntityId& highlightedEntity : highlightedEntities) { AzToolsFramework::ComponentEntityEditorRequestBus::Event(highlightedEntity, &ComponentEntityEditorRequests::SetSandboxObjectAccent, ComponentEntityAccentType::Hover); m_currentlyAccentedEntities.insert(highlightedEntity); } } void EditorSelectionAccentSystemComponent::Deactivate() { AzToolsFramework::ToolsApplicationEvents::Bus::Handler::BusConnect(); AzToolsFramework::Components::EditorSelectionAccentingRequestBus::Handler::BusDisconnect(); } } } // namespace LmbrCentral
; ; jemul8 - JavaScript x86 Emulator ; Copyright (c) 2013 http://jemul8.com. All Rights Reserved. ; ; MODULE: Tests for CPU stack handling - x86 PUSH instruction ; %include '../../tools.inc' ; Jump over data jmp main ; --- Data --- ; Test descriptions test1 db "should decrease SP by 2 when an 8-bit value is pushed",0 test2 db "should decrease SP by 2 when a 16-bit value is pushed",0 ; --- Tests --- main: ; Ready to begin testing cmp ax, 0 if e mov si, test1 call print_description ; Save initial stack pointer mov bx, sp ; Push an 8-bit value: it should be zero-extended to 16-bit push 0x12 ; Save stack pointer after push mov cx, sp ; Subtract 2 from initial stack pointer, leaving expected CX in AX mov ax, bx sub ax, 2 ; Restore stack pointer mov sp, bx cmp cx, ax if e call pass else call fail endif jmp done endif cmp ax, 1 if e mov si, test2 call print_description ; Save initial stack pointer mov bx, sp mov ax, 0x1234 push ax ; Save stack pointer after push mov cx, sp ; Subtract 2 from initial stack pointer, leaving expected CX in AX mov ax, bx sub ax, 2 ; Restore stack pointer mov sp, bx cmp cx, ax if e call pass else call fail endif jmp done endif call finished jmp done
; A038762: a(n) = 6*a(n-1) - a(n-2) for n >= 2, with a(0)=3, a(1)=13. ; 3,13,75,437,2547,14845,86523,504293,2939235,17131117,99847467,581953685,3391874643,19769294173,115223890395,671574048197,3914220398787,22813748344525,132968269668363,774995869665653,4517006948325555,26327045820287677,153445267973400507,894344562020115365,5212622104147291683,30381388062863634733,177075706273034516715,1032072849575343465557,6015361391179026276627,35060095497498814194205,204345211593813858888603,1191011174065384339137413,6941721832798492175935875,40459319822725568716477837,235814197103554920122931147,1374425862798603952021109045,8010740979688068792003723123,46690020015329808800001229693,272129379112290784008003655035,1586086254658414895248020700517,9244388148838198587480120548067,53880242638370776629632702587885,314037067681386461190316094979243,1830342163449947990512263867287573,10668015913018301481883267108746195,62177753314659860900787338785189597,362398503974940863922840765602391387 mov $1,3 mov $2,1 lpb $0 sub $0,1 add $1,$2 add $2,$1 add $2,$1 add $1,$2 lpe mov $0,$1
; A047334: Duplicate of A032775. ; 0,1,2,3,5,6,7,8,9,10,12,13,14,15,16,17,19,20,21,22,23,24,26,27,28,29 mov $1,$0 mul $1,7 add $1,2 div $1,6
; Copyright 2015-2021 Matt "MateoConLechuga" Waltz ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; ; 1. Redistributions of source code must retain the above copyright notice, ; this list of conditions and the following disclaimer. ; ; 2. Redistributions in binary form must reproduce the above copyright notice, ; this list of conditions and the following disclaimer in the documentation ; and/or other materials provided with the distribution. ; ; 3. Neither the name of the copyright holder nor the names of its contributors ; may be used to endorse or promote products derived from this software ; without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; process for displaying the list of programs / appvars view_vat_items: call gui_show_item_count set_normal_text compare_hl_zero jr nz,.can_view ld a,(iy + settings_adv_flag) and a,(1 shl setting_special_directories) or (1 shl setting_enable_usb) jr nz,.can_view ; can't show anything call gui_draw_static_options ld hl,sprite_egg draw_sprite_2x 120, 57 print string_new_prgm, 199, 195 ld de,287 .no_new: ld (lcd_x),de inc hl call lcd_string .can_view: set_cursor 24, 30 xor a,a sbc hl,hl ld (iy + prgm_flag),a ; reset the program status flags ld (current_prgm_drawing),a ld bc,(number_of_items) sbc hl,hl adc hl,bc ret z ; return if no programs are found ld hl,(scroll_amount) compare_hl_zero ld de,item_location_base ex de,hl jr z,.loop .get_physical_offset: inc hl inc hl inc hl inc hl dec de dec bc ld a,e or a,d jr nz,.get_physical_offset .loop: xor a,a ld (iy + temp_prgm_flag),a ; reset the temporary flags res drawing_selected,(iy + item_flag) ; not drawing the selected one yet ld e,0 current_prgm_drawing := $-1 ld a,(current_selection) cp a,e jr nz,.not_selected set drawing_selected,(iy + item_flag) ld (prgm_ptr),hl ld a,(color_tertiary) ld (lcd_text_bg),a ; highlight the currently selected item .not_selected: ld a,e inc a ld (current_prgm_drawing),a ld a,(lcd_y) cp a,220 jp nc,util_set_more_items_flag ; more to scroll, so draw an arrow or something later push bc ; bc = number of programs left to draw push hl ; hl -> lookup table ld hl,(hl) ; load name pointer push hl ; push the name pointer inc hl ; the next byte is the status ld a,(hl) call ti.SetDEUToA inc hl ld d,(hl) inc hl ld e,(hl) push hl ex de,hl cp a,$d0 jr nc,.in_ram set temp_prgm_archived,(iy + temp_prgm_flag) ld de,9 add hl,de ld e,(hl) add hl,de inc hl .in_ram: call ti.LoadDEInd_s ld (temp_prgm_data_ptr),hl bit drawing_selected,(iy + item_flag) jr z,.not_drawing_selected ld (prgm_data_ptr),hl ld (prgm_real_size),de .not_drawing_selected: ex de,hl ld de,9 add hl,de pop de ; lookup table pop bc ; name pointer ld a,(bc) push bc push de call ti.AddHLAndA ld (prgm_size),hl pop hl inc hl inc hl inc hl ld a,(hl) ; previously stored type of program cp a,ti.ProtProgObj jr nz,.not_locked set temp_prgm_locked,(iy + temp_prgm_flag) .not_locked: ld a,(lcd_text_fg) ld (color_save),a pop hl ld b,(hl) dec hl ld a,(hl) cp a,64 jr nc,.draw_item add a,64 ld (hl),a set temp_prgm_hidden,(iy + temp_prgm_flag) ld a,(color_quinary) ld (lcd_text_fg),a .draw_item: push hl .draw_item_name: ld a,(hl) dec hl push bc call lcd_char pop bc djnz .draw_item_name pop hl bit temp_prgm_hidden,(iy + temp_prgm_flag) jr z,.not_hidden ld a,0 color_save := $-1 ld (lcd_text_fg),a ld a,(hl) sub a,64 ld (hl),a .not_hidden: ld a,(lcd_y) add a,20 ld (lcd_y),a sub a,25 ld c,a ld a,24 ld (lcd_x),a ld b,2 pop hl inc hl inc hl inc hl ld a,(hl) bit drawing_selected,(iy + item_flag) jr z,.dont_set_type ld (prgm_type),a .dont_set_type: inc hl push hl ; save location in list ld de,string_directory ld hl,sprite_directory cp a,file_dir jp z,file_directory cp a,file_usb_dir ld de,string_usb ld hl,sprite_usb jp z,file_usb_directory ; it's a directory right? ld de,string_appvar ld hl,sprite_file_appvar cp a,file_appvar jr z,file_uneditable ld de,string_asm ld hl,sprite_file_asm cp a,file_asm jr z,file_uneditable ld de,string_c ld hl,sprite_file_c cp a,file_c jr z,file_uneditable ld de,string_ice ld hl,sprite_file_ice cp a,file_ice jr z,file_uneditable set temp_prgm_is_basic,(iy + temp_prgm_flag) ld de,string_ice_source cp a,file_ice_source jq z,file_editable ld de,string_basic ld hl,sprite_file_basic cp a,file_basic jq z,file_editable jp exit_full ; abort file_usb_directory: set temp_prgm_is_usb_directory,(iy + temp_prgm_flag) file_directory: push hl or a,a sbc hl,hl ld (prgm_size),hl pop hl jp draw_listed_entry file_uneditable: push de push hl ld hl,0 ; hl -> program data temp_prgm_data_ptr := $-3 inc hl inc hl ld a,(hl) cp a,byte_jp jr z,.custom_icon inc hl ld a,(hl) cp a,byte_jp jr nz,.no_custom_icon .custom_icon: inc hl inc hl inc hl inc hl ; hl -> icon indicator byte, hopefully ld a,(hl) cp a,byte_icon ; cesium indicator byte jr z,.valid_icon cp a,byte_description jr nz,.no_custom_icon bit drawing_selected,(iy + item_flag) ; check if the description should be drawn jr z,.no_custom_icon inc hl call gui_show_description jr .no_custom_icon .valid_icon: pop de ; pop the old icon inc hl bit drawing_selected,(iy + item_flag) ; check if the description should be drawn jr z,.icon push hl ld e,(hl) inc hl ld d,(hl) mlt de inc de add hl,de ; hl -> description string (null terminated) call gui_show_description ; actually draw the description string .no_custom_icon: pop hl ; hl -> icon .icon: pop de ; de -> language string jp draw_listed_entry check_dcs_icon: ld hl,(temp_prgm_data_ptr) ld de,lut_dcs_icon ld b,6 .verify_icon: ld a,(de) cp a,(hl) inc hl inc de ret nz djnz .verify_icon ret check_dcs6_icon: ld hl,(temp_prgm_data_ptr) ld de,lut_dcs6_icon ld b,7 jr check_dcs_icon.verify_icon check_mos_dcs_icon: ld hl,(temp_prgm_data_ptr) ld de,lut_dcs6_icon ld b,7 jr check_dcs_icon.verify_icon check_description_icon: ld hl,(temp_prgm_data_ptr) .enter: ld de,lut_description_icon ld b,2 jr check_dcs_icon.verify_icon file_editable: push bc push de push hl call check_description_icon jq z,description_icon call check_dcs_icon jr z,.dcs_icon call check_dcs6_icon jr z,.dcs_icon jr .no_custom_icon .dcs_icon: pop de ; remove default icon push hl ld hl,sprite_temp+2 ld (hl),224 push hl pop de inc de ld bc,256-1 ldir pop hl ld de,sprite_temp ld a,16 ld (de),a inc de ld (de),a inc de push hl push hl ; save the size of the sprite ld bc,256 ld a,ti.tEnter ; now determine if it is a 8x8 monochrome, 16x16 monochrome, or 16x16 color icon cpir pop bc or a,a sbc hl,bc ; number of bytes read ld bc,17 or a,a sbc hl,bc add hl,bc ; monochrome 8x8 jq z,monochrome_8x8 ld bc,65 or a,a sbc hl,bc add hl,bc ; monochrome 16x16 jq z,monochrome_16x16 jq color_16x16 .return_icon: ld hl,sprite_temp ; yay, a custom icon push hl .no_custom_icon: pop hl pop de pop bc jq draw_listed_entry color_16x16: pop hl ld b,0 .loop: ; okay, now loop 256 times to do the squish ld a,(hl) sub a,$30 cp a,$11 jr c,.no_overflow sub a,$07 .no_overflow: ; rather than doing an actual routine, just do this push hl ld hl,lut_color_basic call ti.AddHLAndA ld a,(hl) pop hl ld (de),a inc de inc hl djnz .loop ; collect all the values jq file_editable.return_icon monochrome_8x8: pop hl ex de,hl ld b,8 .loop: ld a,(de) ; high nibble inc de call util_ascii_nibble_to_byte add a,a add a,a add a,a add a,a ld c,a ld a,(de) ; high nibble inc de call util_ascii_nibble_to_byte add a,c ; byte :) ld c,a push bc push hl ld b,8 .inner_byte: rl c ld a,107 jr c,.set .not_set: ld a,(color_senary) .set: ld (hl),a inc hl ld (hl),a inc hl djnz .inner_byte push hl pop bc pop hl push de push bc pop de ld bc,16 ldir ex de,hl pop de pop bc djnz .loop jq file_editable.return_icon monochrome_16x16: pop hl ex de,hl ld b,64 .loop: ld a,(de) ; high nibble inc de call util_ascii_nibble_to_byte add a,a add a,a add a,a add a,a ld c,a ld a,(de) ; high nibble inc de call util_ascii_nibble_to_byte add a,c ; byte :) ld c,a push bc ld b,8 .inner_byte: rl c ld a,107 jr c,.set .not_set: ld a,(color_senary) .set: ld (hl),a inc hl djnz .inner_byte pop bc djnz .loop jq file_editable.return_icon description_icon: ld de,sprite_temp xor a,a .next_token: push hl push de push af ld a,(hl) cp a,$3F jr z,.done_get_icon call ti.Get_Tok_Strng ld c,a pop af add a,c cp a,25 jr nc,.fail pop de pop hl push af ld a,(hl) call ti.Isa2ByteTok jr nz,.not2byte inc hl .not2byte: inc hl push hl ld hl,ti.OP3 ldir pop hl pop af jr .next_token .done_get_icon: xor a,a ld (de),a pop bc,bc,bc inc hl push hl ld hl,sprite_temp bit drawing_selected,(iy + item_flag) call nz,gui_show_description pop hl call check_description_icon.enter jq nz,file_editable.no_custom_icon jq file_editable.dcs_icon .fail: pop bc,bc jq file_editable.no_custom_icon draw_listed_entry: ld a,(lcd_y) push af ld ix,(lcd_x) push ix ; save_cursor ld (tmp_y),a push de ; save language string push hl ; save icon pointer call lcd_sprite ld a,0 tmp_y := $-1 sub a,20 ld c,a ld hl,sprite_locked ld b,250 bit temp_prgm_locked,(iy + temp_prgm_flag) jr z,.not_protected push bc call lcd_sprite pop bc .not_protected: ld a,b sub a,4 ld b,a ld hl,sprite_archived bit temp_prgm_archived,(iy + temp_prgm_flag) call nz,lcd_sprite bit drawing_selected,(iy + item_flag) pop hl ; hl -> program icon jp z,.not_selected ld a,(iy + temp_prgm_flag) ld (iy + prgm_flag),a ; load the program info draw_sprite_2x 120, 57 ld a,(color_senary) ld (lcd_text_bg),a print string_language, 199, 107 pop hl call lcd_string ; hl -> language string bit temp_prgm_is_usb_directory,(iy + temp_prgm_flag) jq nz,.nosize print string_size, 199, 151 ld hl,(prgm_size) call lcd_num_5 .nosize: print string_attributes, 199, 173 set_cursor_x 262 inc hl call lcd_string print string_archived, 199, 118 ld a,(current_screen) cp a,screen_appvars ; don't draw things that appvars can't handle jr z,.dont_draw_extras print string_locked, 199, 129 print string_hidden, 199, 140 print string_rename, 199, 195 ld de,262 ld (lcd_x),de inc hl call lcd_string bit prgm_locked,(iy + prgm_flag) jr nz,.is_locked print string_edit_prgm, 199, 184 ld de,269 jr .no_new .is_locked: print string_new_prgm, 199, 184 ld de,287 .no_new: ld (lcd_x),de inc hl call lcd_string .dont_draw_extras: call gui_draw_item_options call gui_draw_static_options push de .not_selected: pop de ; description may not have been popped pop bc ld (lcd_x),bc pop af ld (lcd_y),a ; restore_cursor pop hl ; restore list location pop bc dec bc ld a,b or a,c jp nz,view_vat_items.loop ret .file_directory: push hl or a,a sbc hl,hl ld (prgm_size),hl pop hl jp draw_listed_entry
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: VROSC.NoteBoard #include "VROSC/NoteBoard.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: VROSC namespace VROSC { // Skipping declaration: NoteBoardNote because it is already included! // Forward declaring type: NoteFieldParameters class NoteFieldParameters; // Forward declaring type: NoteFieldData class NoteFieldData; } // Completed forward declares // Type namespace: VROSC namespace VROSC { // Forward declaring type: TouchableObject class TouchableObject; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::TouchableObject); DEFINE_IL2CPP_ARG_TYPE(::VROSC::TouchableObject*, "VROSC", "TouchableObject"); // Type namespace: VROSC namespace VROSC { // Size: 0x74 #pragma pack(push, 1) // Autogenerated type: VROSC.TouchableObject // [TokenAttribute] Offset: FFFFFFFF class TouchableObject : public ::UnityEngine::MonoBehaviour { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private VROSC.NoteBoardNote _note // Size: 0x8 // Offset: 0x18 ::VROSC::NoteBoardNote* note; // Field size check static_assert(sizeof(::VROSC::NoteBoardNote*) == 0x8); // private VROSC.NoteBoardNote _xUp // Size: 0x8 // Offset: 0x20 ::VROSC::NoteBoardNote* xUp; // Field size check static_assert(sizeof(::VROSC::NoteBoardNote*) == 0x8); // private VROSC.NoteBoardNote _xDown // Size: 0x8 // Offset: 0x28 ::VROSC::NoteBoardNote* xDown; // Field size check static_assert(sizeof(::VROSC::NoteBoardNote*) == 0x8); // private VROSC.NoteBoardNote _yUp // Size: 0x8 // Offset: 0x30 ::VROSC::NoteBoardNote* yUp; // Field size check static_assert(sizeof(::VROSC::NoteBoardNote*) == 0x8); // private VROSC.NoteBoardNote _yDown // Size: 0x8 // Offset: 0x38 ::VROSC::NoteBoardNote* yDown; // Field size check static_assert(sizeof(::VROSC::NoteBoardNote*) == 0x8); // private VROSC.NoteBoardNote _zUp // Size: 0x8 // Offset: 0x40 ::VROSC::NoteBoardNote* zUp; // Field size check static_assert(sizeof(::VROSC::NoteBoardNote*) == 0x8); // private VROSC.NoteBoardNote _zDown // Size: 0x8 // Offset: 0x48 ::VROSC::NoteBoardNote* zDown; // Field size check static_assert(sizeof(::VROSC::NoteBoardNote*) == 0x8); // private System.Int32 _x // Size: 0x4 // Offset: 0x50 int x; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 _y // Size: 0x4 // Offset: 0x54 int y; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 _z // Size: 0x4 // Offset: 0x58 int z; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 _3d // Size: 0x4 // Offset: 0x5C int _3d; // Field size check static_assert(sizeof(int) == 0x4); // private UnityEngine.Vector3 _playingPower // Size: 0xC // Offset: 0x60 ::UnityEngine::Vector3 playingPower; // Field size check static_assert(sizeof(::UnityEngine::Vector3) == 0xC); // private System.Boolean _playing // Size: 0x1 // Offset: 0x6C bool playing; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: playing and: height char __padding12[0x3] = {}; // private System.Single _height // Size: 0x4 // Offset: 0x70 float height; // Field size check static_assert(sizeof(float) == 0x4); public: // Deleting conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept = delete; // Get instance field reference: private VROSC.NoteBoardNote _note ::VROSC::NoteBoardNote*& dyn__note(); // Get instance field reference: private VROSC.NoteBoardNote _xUp ::VROSC::NoteBoardNote*& dyn__xUp(); // Get instance field reference: private VROSC.NoteBoardNote _xDown ::VROSC::NoteBoardNote*& dyn__xDown(); // Get instance field reference: private VROSC.NoteBoardNote _yUp ::VROSC::NoteBoardNote*& dyn__yUp(); // Get instance field reference: private VROSC.NoteBoardNote _yDown ::VROSC::NoteBoardNote*& dyn__yDown(); // Get instance field reference: private VROSC.NoteBoardNote _zUp ::VROSC::NoteBoardNote*& dyn__zUp(); // Get instance field reference: private VROSC.NoteBoardNote _zDown ::VROSC::NoteBoardNote*& dyn__zDown(); // Get instance field reference: private System.Int32 _x int& dyn__x(); // Get instance field reference: private System.Int32 _y int& dyn__y(); // Get instance field reference: private System.Int32 _z int& dyn__z(); // Get instance field reference: private System.Int32 _3d int& dyn__3d(); // Get instance field reference: private UnityEngine.Vector3 _playingPower ::UnityEngine::Vector3& dyn__playingPower(); // Get instance field reference: private System.Boolean _playing bool& dyn__playing(); // Get instance field reference: private System.Single _height float& dyn__height(); // public VROSC.NoteBoardNote get_Note() // Offset: 0x1400D00 ::VROSC::NoteBoardNote* get_Note(); // public System.Void Setup(VROSC.NoteFieldParameters parameters, VROSC.NoteFieldData noteFieldData, UnityEngine.Vector3 fieldSize) // Offset: 0x1400D08 void Setup(::VROSC::NoteFieldParameters* parameters, ::VROSC::NoteFieldData* noteFieldData, ::UnityEngine::Vector3 fieldSize); // public System.Void UpdateHovering(System.Boolean isInside) // Offset: 0x1401118 void UpdateHovering(bool isInside); // public System.Void UpdatePlaying(System.Boolean isInside, System.Boolean playing, VROSC.NoteBoard/VROSC.PlayAxis playAxis) // Offset: 0x1401140 void UpdatePlaying(bool isInside, bool playing, ::VROSC::NoteBoard::PlayAxis playAxis); // public System.Void SetHeight(System.Single height) // Offset: 0x14011E4 void SetHeight(float height); // public System.Void UpdateVisuals() // Offset: 0x14011EC void UpdateVisuals(); // private System.Void AutoSetup() // Offset: 0x14012C8 void AutoSetup(); // private System.Void AutoSetupNeighbours() // Offset: 0x140131C void AutoSetupNeighbours(); // private System.Void OnDrawGizmosSelected() // Offset: 0x140160C void OnDrawGizmosSelected(); // public System.Void .ctor() // Offset: 0x14019F8 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static TouchableObject* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::TouchableObject::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<TouchableObject*, creationType>())); } }; // VROSC.TouchableObject #pragma pack(pop) static check_size<sizeof(TouchableObject), 112 + sizeof(float)> __VROSC_TouchableObjectSizeCheck; static_assert(sizeof(TouchableObject) == 0x74); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::TouchableObject::get_Note // Il2CppName: get_Note template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::VROSC::NoteBoardNote* (VROSC::TouchableObject::*)()>(&VROSC::TouchableObject::get_Note)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "get_Note", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::Setup // Il2CppName: Setup template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TouchableObject::*)(::VROSC::NoteFieldParameters*, ::VROSC::NoteFieldData*, ::UnityEngine::Vector3)>(&VROSC::TouchableObject::Setup)> { static const MethodInfo* get() { static auto* parameters = &::il2cpp_utils::GetClassFromName("VROSC", "NoteFieldParameters")->byval_arg; static auto* noteFieldData = &::il2cpp_utils::GetClassFromName("VROSC", "NoteFieldData")->byval_arg; static auto* fieldSize = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "Setup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{parameters, noteFieldData, fieldSize}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::UpdateHovering // Il2CppName: UpdateHovering template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TouchableObject::*)(bool)>(&VROSC::TouchableObject::UpdateHovering)> { static const MethodInfo* get() { static auto* isInside = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "UpdateHovering", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{isInside}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::UpdatePlaying // Il2CppName: UpdatePlaying template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TouchableObject::*)(bool, bool, ::VROSC::NoteBoard::PlayAxis)>(&VROSC::TouchableObject::UpdatePlaying)> { static const MethodInfo* get() { static auto* isInside = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; static auto* playing = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; static auto* playAxis = &::il2cpp_utils::GetClassFromName("VROSC", "NoteBoard/PlayAxis")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "UpdatePlaying", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{isInside, playing, playAxis}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::SetHeight // Il2CppName: SetHeight template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TouchableObject::*)(float)>(&VROSC::TouchableObject::SetHeight)> { static const MethodInfo* get() { static auto* height = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "SetHeight", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{height}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::UpdateVisuals // Il2CppName: UpdateVisuals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TouchableObject::*)()>(&VROSC::TouchableObject::UpdateVisuals)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "UpdateVisuals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::AutoSetup // Il2CppName: AutoSetup template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TouchableObject::*)()>(&VROSC::TouchableObject::AutoSetup)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "AutoSetup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::AutoSetupNeighbours // Il2CppName: AutoSetupNeighbours template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TouchableObject::*)()>(&VROSC::TouchableObject::AutoSetupNeighbours)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "AutoSetupNeighbours", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::OnDrawGizmosSelected // Il2CppName: OnDrawGizmosSelected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TouchableObject::*)()>(&VROSC::TouchableObject::OnDrawGizmosSelected)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TouchableObject*), "OnDrawGizmosSelected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TouchableObject::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
; A002548: Denominators of coefficients for numerical differentiation. ; Submitted by Christian Krause ; 1,1,12,6,180,10,560,1260,12600,1260,166320,13860,2522520,2702700,2882880,360360,110270160,2042040,775975200,162954792,56904848,2586584,1427794368,892371480,116008292400,120470149800,1124388064800,40156716600,34936343442000,1164544781400,1155228423148800,2382658622744400,223169127199200,229732925058000,236296722916800,6563797858800,9228699789472800,9471560310248400,9714420831024000,242860520775600,418205816775583200,1422468764542800,2691310902514977600,30277247653293498000,30950075378922242400 add $0,1 mov $2,1 mov $3,$0 add $0,1 lpb $3 mul $1,$3 mul $1,$0 mov $4,$3 add $4,1 mul $2,$4 add $1,$2 mul $2,$0 sub $3,1 lpe mul $4,$2 gcd $2,$1 mov $1,$4 div $1,$2 mov $0,$1 div $0,4
; void *z180_otir(void *src, uint8_t port, uint8_t num) SECTION code_clib SECTION code_z180 PUBLIC z180_otir EXTERN asm_z180_otir z180_otir: pop af pop de pop bc pop hl push hl push bc push de push af ld b,e jp asm_z180_otir
; int ungetc(int c, FILE *stream) INCLUDE "clib_cfg.asm" SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC ungetc EXTERN asm_ungetc ungetc: pop af pop ix pop hl push hl push hl push af jp asm_ungetc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC ungetc EXTERN ungetc_unlocked defc ungetc = ungetc_unlocked ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
object_const_def ; object_event constants const ROUTE36_YOUNGSTER1 const ROUTE36_YOUNGSTER2 const ROUTE36_WEIRD_TREE const ROUTE36_LASS1 const ROUTE36_FISHER const ROUTE36_FRUIT_TREE const ROUTE36_ARTHUR const ROUTE36_FLORIA const ROUTE36_SUICUNE Route36_MapScripts: db 2 ; scene scripts scene_script .DummyScene0 ; SCENE_ROUTE36_NOTHING scene_script .DummyScene1 ; SCENE_ROUTE36_SUICUNE db 1 ; callbacks callback MAPCALLBACK_OBJECTS, .ArthurCallback .DummyScene0: end .DummyScene1: end .ArthurCallback: readvar VAR_WEEKDAY ifequal THURSDAY, .ArthurAppears disappear ROUTE36_ARTHUR return .ArthurAppears: appear ROUTE36_ARTHUR return Route36SuicuneScript: showemote EMOTE_SHOCK, PLAYER, 15 pause 15 playsound SFX_WARP_FROM turnobject PLAYER, UP applymovement ROUTE36_SUICUNE, Route36SuicuneMovement disappear ROUTE36_SUICUNE turnobject PLAYER, DOWN pause 10 setscene SCENE_ROUTE36_NOTHING clearevent EVENT_SAW_SUICUNE_AT_CIANWOOD_CITY setmapscene CIANWOOD_CITY, SCENE_CIANWOODCITY_SUICUNE_AND_EUSINE end SudowoodoScript: checkitem SQUIRTBOTTLE iftrue .Fight waitsfx playsound SFX_SANDSTORM applymovement ROUTE36_WEIRD_TREE, SudowoodoShakeMovement end .Fight: opentext writetext UseSquirtbottleText yesorno iffalse DidntUseSquirtbottleScript closetext WateredWeirdTreeScript:: ; export (for when you use Squirtbottle from pack) opentext writetext UsedSquirtbottleText waitbutton closetext waitsfx playsound SFX_SANDSTORM applymovement ROUTE36_WEIRD_TREE, SudowoodoShakeMovement opentext writetext SudowoodoAttackedText waitbutton closetext loadwildmon SUDOWOODO, 20 startbattle setevent EVENT_FOUGHT_SUDOWOODO ifequal DRAW, DidntCatchSudowoodo disappear ROUTE36_WEIRD_TREE variablesprite SPRITE_WEIRD_TREE, SPRITE_TWIN reloadmapafterbattle end DidntUseSquirtbottleScript: closetext end DidntCatchSudowoodo: reloadmapafterbattle applymovement ROUTE36_WEIRD_TREE, WeirdTreeMovement_Flee disappear ROUTE36_WEIRD_TREE variablesprite SPRITE_WEIRD_TREE, SPRITE_TWIN special LoadUsedSpritesGFX special RefreshSprites end Route36FloriaScript: faceplayer opentext checkevent EVENT_TALKED_TO_FLORIA_AT_FLOWER_SHOP iftrue .SecondTimeTalking setevent EVENT_MET_FLORIA writetext FloriaText1 waitbutton closetext clearevent EVENT_FLORIA_AT_FLOWER_SHOP readvar VAR_FACING ifequal UP, .Up applymovement ROUTE36_FLORIA, FloriaMovement1 disappear ROUTE36_FLORIA end .Up: applymovement ROUTE36_FLORIA, FloriaMovement2 disappear ROUTE36_FLORIA end .SecondTimeTalking: writetext FloriaText2 waitbutton closetext end Route36RockSmashGuyScript: faceplayer opentext checkevent EVENT_GOT_TM08_ROCK_SMASH iftrue .AlreadyGotRockSmash checkevent EVENT_FOUGHT_SUDOWOODO iftrue .ClearedSudowoodo writetext RockSmashGuyText1 waitbutton closetext end .ClearedSudowoodo: writetext RockSmashGuyText2 buttonsound verbosegivetmhm TM_ROCK_SMASH iffalse .NoRoomForTM setevent EVENT_GOT_TM08_ROCK_SMASH .AlreadyGotRockSmash: writetext RockSmashGuyText3 waitbutton .NoRoomForTM: closetext end Route36LassScript: faceplayer opentext checkevent EVENT_FOUGHT_SUDOWOODO iftrue .ClearedSudowoodo writetext Route36LassText waitbutton closetext end .ClearedSudowoodo: writetext Route36LassText_ClearedSudowoodo waitbutton closetext end TrainerSchoolboyAlan1: trainer SCHOOLBOY, ALAN1, EVENT_BEAT_SCHOOLBOY_ALAN, SchoolboyAlan1SeenText, SchoolboyAlan1BeatenText, 0, .Script .Script: loadvar VAR_CALLERID, PHONE_SCHOOLBOY_ALAN endifjustbattled opentext checkflag ENGINE_ALAN iftrue .ChooseRematch checkflag ENGINE_ALAN_HAS_FIRE_STONE iftrue .GiveFireStone checkcellnum PHONE_SCHOOLBOY_ALAN iftrue .NumberAccepted checkevent EVENT_ALAN_ASKED_FOR_PHONE_NUMBER iftrue .AskAgainForPhoneNumber writetext UnknownText_0x1947aa buttonsound setevent EVENT_ALAN_ASKED_FOR_PHONE_NUMBER scall .AskNumber1 sjump .ContinueAskForPhoneNumber .AskAgainForPhoneNumber: scall .AskNumber2 .ContinueAskForPhoneNumber: askforphonenumber PHONE_SCHOOLBOY_ALAN ifequal PHONE_CONTACTS_FULL, .PhoneFull ifequal PHONE_CONTACT_REFUSED, .NumberDeclined gettrainername STRING_BUFFER_3, SCHOOLBOY, ALAN1 scall .RegisteredNumber sjump .NumberAccepted .ChooseRematch: scall .Rematch winlosstext SchoolboyAlan1BeatenText, 0 readmem wAlanFightCount ifequal 4, .Fight4 ifequal 3, .Fight3 ifequal 2, .Fight2 ifequal 1, .Fight1 ifequal 0, .LoadFight0 .Fight4: checkevent EVENT_RESTORED_POWER_TO_KANTO iftrue .LoadFight4 .Fight3: checkevent EVENT_BEAT_ELITE_FOUR iftrue .LoadFight3 .Fight2: checkflag ENGINE_FLYPOINT_BLACKTHORN iftrue .LoadFight2 .Fight1: checkflag ENGINE_FLYPOINT_OLIVINE iftrue .LoadFight1 .LoadFight0: loadtrainer SCHOOLBOY, ALAN1 startbattle reloadmapafterbattle loadmem wAlanFightCount, 1 clearflag ENGINE_ALAN end .LoadFight1: loadtrainer SCHOOLBOY, ALAN2 startbattle reloadmapafterbattle loadmem wAlanFightCount, 2 clearflag ENGINE_ALAN end .LoadFight2: loadtrainer SCHOOLBOY, ALAN3 startbattle reloadmapafterbattle loadmem wAlanFightCount, 3 clearflag ENGINE_ALAN end .LoadFight3: loadtrainer SCHOOLBOY, ALAN4 startbattle reloadmapafterbattle loadmem wAlanFightCount, 4 clearflag ENGINE_ALAN end .LoadFight4: loadtrainer SCHOOLBOY, ALAN5 startbattle reloadmapafterbattle clearflag ENGINE_ALAN end .GiveFireStone: scall .Gift verbosegiveitem FIRE_STONE iffalse .BagFull clearflag ENGINE_ALAN_HAS_FIRE_STONE setevent EVENT_ALAN_GAVE_FIRE_STONE sjump .NumberAccepted .BagFull: sjump .PackFull .AskNumber1: jumpstd asknumber1m end .AskNumber2: jumpstd asknumber2m end .RegisteredNumber: jumpstd registerednumberm end .NumberAccepted: jumpstd numberacceptedm end .NumberDeclined: jumpstd numberdeclinedm end .PhoneFull: jumpstd phonefullm end .Rematch: jumpstd rematchm end .Gift: jumpstd giftm end .PackFull: jumpstd packfullm end TrainerPsychicMark: trainer PSYCHIC_T, MARK, EVENT_BEAT_PSYCHIC_MARK, PsychicMarkSeenText, PsychicMarkBeatenText, 0, .Script .Script: endifjustbattled opentext writetext PsychicMarkAfterBattleText waitbutton closetext end ArthurScript: faceplayer opentext checkevent EVENT_GOT_HARD_STONE_FROM_ARTHUR iftrue .AlreadyGotStone readvar VAR_WEEKDAY ifnotequal THURSDAY, ArthurNotThursdayScript checkevent EVENT_MET_ARTHUR_OF_THURSDAY iftrue .MetArthur writetext MeetArthurText buttonsound setevent EVENT_MET_ARTHUR_OF_THURSDAY .MetArthur: writetext ArthurGivesGiftText buttonsound verbosegiveitem HARD_STONE iffalse .BagFull setevent EVENT_GOT_HARD_STONE_FROM_ARTHUR writetext ArthurGaveGiftText waitbutton closetext end .AlreadyGotStone: writetext ArthurThursdayText waitbutton .BagFull: closetext end ArthurNotThursdayScript: writetext ArthurNotThursdayText waitbutton closetext end Route36Sign: jumptext Route36SignText RuinsOfAlphNorthSign: jumptext RuinsOfAlphNorthSignText Route36TrainerTips1: jumptext Route36TrainerTips1Text Route36TrainerTips2: jumptext Route36TrainerTips2Text Route36FruitTree: fruittree FRUITTREE_ROUTE_36 SudowoodoShakeMovement: tree_shake ; shake step_end WeirdTreeMovement_Flee: fast_jump_step UP fast_jump_step UP step_end FloriaMovement1: step DOWN step DOWN step DOWN step LEFT step LEFT step LEFT step LEFT step LEFT step LEFT step_end FloriaMovement2: step LEFT step DOWN step DOWN step DOWN step LEFT step LEFT step LEFT step LEFT step LEFT step_end Route36SuicuneMovement: set_sliding fast_jump_step DOWN fast_jump_step DOWN fast_jump_step DOWN fast_jump_step RIGHT fast_jump_step RIGHT fast_jump_step RIGHT remove_sliding step_end UseSquirtbottleText: text "It's a weird tree." line "Use SQUIRTBOTTLE?" done UsedSquirtbottleText: text "<PLAYER> used the" line "SQUIRTBOTTLE." done SudowoodoAttackedText: text "The weird tree" line "doesn't like the" cont "SQUIRTBOTTLE!" para "The weird tree" line "attacked!" done FloriaText1: text "I'm the FLOWER" line "SHOP's FLORIA!" para "Listen, listen!" para "When I sprinkled" line "water on that" para "wiggly tree, it" line "jumped right up!" para "It just has to be" line "a #MON." para "I bet it would be" line "shocked out of its" para "disguise if you" line "soaked it!" para "I know! I'll tell" line "my sis and borrow" cont "her water bottle!" done FloriaText2: text "When I told my sis" line "about the jiggly" para "tree, she said" line "it's dangerous." para "If I beat WHITNEY," line "I wonder if she'll" para "lend me her water" line "bottle…" done RockSmashGuyText1: text "Wa-hey!" para "I was going to" line "snap that tree" para "with my straight-" line "arm punch." para "But I couldn't!" line "I'm a failure!" done RockSmashGuyText2: text "Did you clear that" line "wretched tree?" para "I'm impressed!" line "I want you to" cont "have this." done UnknownText_0x19451a: text "<PLAYER> received" line "TM08." done RockSmashGuyText3: text "That happens to be" line "ROCK SMASH." para "You can shatter" line "rocks with just a" para "single well-aimed" line "smack." para "If any rocks are" line "in your way, just" cont "smash 'em up!" done UnknownText_0x1945b8: text "An odd tree is" line "blocking the way" cont "to GOLDENROD CITY." para "I wanted to go see" line "the huge #MON" para "CENTER they just" line "opened…" done Route36LassText: text "An odd tree is" line "blocking the way" cont "to GOLDENROD CITY." para "It's preventing" line "me from shopping." para "Something should" line "be done about it." done Route36LassText_ClearedSudowoodo: text "That odd tree dis-" line "appeared without a" cont "trace." para "Oh! That tree was" line "really a #MON?" done PsychicMarkSeenText: text "I'm going to read" line "your thoughts!" done PsychicMarkBeatenText: text "I misread you!" done PsychicMarkAfterBattleText: text "I'd be strong if" line "only I could tell" para "what my opponent" line "was thinking." done SchoolboyAlan1SeenText: text "Thanks to my stud-" line "ies, I'm ready for" cont "any #MON!" done SchoolboyAlan1BeatenText: text "Oops! Computation" line "error?" done UnknownText_0x1947aa: text "Darn. I study five" line "hours a day too." para "There's more to" line "learning than just" cont "reading books." done MeetArthurText: text "ARTHUR: Who are" line "you?" para "I'm ARTHUR of" line "Thursday." done ArthurGivesGiftText: text "Here. You can have" line "this." done ArthurGaveGiftText: text "ARTHUR: A #MON" line "that uses rock-" para "type moves should" line "hold on to that." para "It pumps up rock-" line "type attacks." done ArthurThursdayText: text "ARTHUR: I'm ARTHUR" line "of Thursday. I'm" para "the second son out" line "of seven children." done ArthurNotThursdayText: text "ARTHUR: Today's" line "not Thursday. How" cont "disappointing." done Route36SignText: text "ROUTE 36" done RuinsOfAlphNorthSignText: text "RUINS OF ALPH" line "NORTH ENTRANCE" done Route36TrainerTips1Text: text "TRAINER TIPS" para "#MON stats" line "vary--even within" cont "the same species." para "Their stats may be" line "similar at first." para "However, differ-" line "ences will become" para "pronounced as the" line "#MON grow." done Route36TrainerTips2Text: text "TRAINER TIPS" para "Use DIG to return" line "to the entrance of" cont "any place." para "It is convenient" line "for exploring" para "caves and other" line "landmarks." done Route36_MapEvents: db 0, 0 ; filler db 4 ; warp events warp_event 18, 8, ROUTE_36_NATIONAL_PARK_GATE, 3 warp_event 18, 9, ROUTE_36_NATIONAL_PARK_GATE, 4 warp_event 47, 13, ROUTE_36_RUINS_OF_ALPH_GATE, 1 warp_event 48, 13, ROUTE_36_RUINS_OF_ALPH_GATE, 2 db 2 ; coord events coord_event 20, 7, SCENE_ROUTE36_SUICUNE, Route36SuicuneScript coord_event 22, 7, SCENE_ROUTE36_SUICUNE, Route36SuicuneScript db 4 ; bg events bg_event 29, 1, BGEVENT_READ, Route36TrainerTips2 bg_event 45, 11, BGEVENT_READ, RuinsOfAlphNorthSign bg_event 55, 7, BGEVENT_READ, Route36Sign bg_event 21, 7, BGEVENT_READ, Route36TrainerTips1 db 9 ; object events object_event 20, 13, SPRITE_YOUNGSTER, SPRITEMOVEDATA_STANDING_RIGHT, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_TRAINER, 3, TrainerPsychicMark, -1 object_event 31, 14, SPRITE_YOUNGSTER, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_TRAINER, 5, TrainerSchoolboyAlan1, -1 object_event 35, 9, SPRITE_WEIRD_TREE, SPRITEMOVEDATA_SUDOWOODO, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, SudowoodoScript, EVENT_ROUTE_36_SUDOWOODO object_event 51, 8, SPRITE_LASS, SPRITEMOVEDATA_WALK_LEFT_RIGHT, 2, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, Route36LassScript, -1 object_event 44, 9, SPRITE_FISHER, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, Route36RockSmashGuyScript, -1 object_event 21, 4, SPRITE_FRUIT_TREE, SPRITEMOVEDATA_STILL, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, Route36FruitTree, -1 object_event 46, 6, SPRITE_YOUNGSTER, SPRITEMOVEDATA_WANDER, 1, 1, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, ArthurScript, EVENT_ROUTE_36_ARTHUR_OF_THURSDAY object_event 33, 12, SPRITE_LASS, SPRITEMOVEDATA_STANDING_DOWN, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_SCRIPT, 0, Route36FloriaScript, EVENT_FLORIA_AT_SUDOWOODO object_event 21, 6, SPRITE_SUICUNE, SPRITEMOVEDATA_STILL, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_SCRIPT, 0, ObjectEvent, EVENT_SAW_SUICUNE_ON_ROUTE_36
; FILE *freopen_callee(char *filename, char *mode, FILE *stream) INCLUDE "clib_cfg.asm" SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _freopen_callee EXTERN asm_freopen _freopen_callee: pop af pop hl pop de pop ix push af jp asm_freopen ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _freopen_callee EXTERN _freopen_unlocked_callee defc _freopen_callee = _freopen_unlocked_callee ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A287393: Domination number for knight's graph on a 2 X n board. ; 0,2,4,4,4,4,4,6,8,8,8,8,8,10,12,12,12,12,12,14,16,16,16,16,16,18,20,20,20,20,20,22,24,24,24,24,24,26,28,28,28,28,28,30,32,32,32,32,32,34,36,36,36,36,36,38,40,40,40,40,40,42,44,44,44,44,44,46,48,48,48,48,48,50,52,52,52,52,52,54,56,56,56,56,56,58,60,60,60,60,60,62,64,64,64,64,64,66,68,68,68,68,68,70,72,72,72,72,72,74,76,76,76,76,76,78,80,80,80,80,80,82,84,84,84,84,84,86,88,88,88,88,88,90,92,92,92,92,92,94,96,96,96,96,96,98,100,100,100,100,100,102,104,104,104,104,104,106,108,108,108,108,108,110,112,112,112,112,112,114,116,116,116,116,116,118,120,120,120,120,120,122,124,124,124,124,124,126,128,128,128,128,128,130,132,132,132,132,132,134,136,136,136,136,136,138,140,140,140,140,140,142,144,144,144,144,144,146,148,148,148,148,148,150,152,152,152,152,152,154,156,156,156,156,156,158,160,160,160,160,160,162,164,164,164,164,164,166,168,168 lpb $0,1 sub $0,1 trn $0,$3 add $1,2 mov $2,$3 mov $3,4 sub $3,$2 lpe
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <chainparams.h> #include <clientversion.h> #include <compat.h> #include <fs.h> #include <interfaces/chain.h> #include <rpc/server.h> #include <init.h> #include <noui.h> #include <shutdown.h> #include <util/system.h> #include <httpserver.h> #include <httprpc.h> #include <util/strencodings.h> #include <walletinitinterface.h> #include <stdio.h> const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin, * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * See https://github.com/bitcoin/bitcoin and https://bitcoincore.org/ for further information about the project. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static void WaitForShutdown() { while (!ShutdownRequested()) { MilliSleep(200); } Interrupt(); } ////////////////////////////////////////////////////////////////////////////// // // Start // static bool AppInit(int argc, char* argv[]) { InitInterfaces interfaces; interfaces.chain = interfaces::MakeChain(); bool fRet = false; // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() SetupServerArgs(); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str()); return false; } // Process help and version before taking care about datadir if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { std::string strUsage = PACKAGE_NAME " Daemon version " + FormatFullVersion() + "\n"; if (gArgs.IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()) + "\n"; } else { strUsage += "\nUsage: torchcoind [options] Start " PACKAGE_NAME " Daemon\n"; strUsage += "\n" + gArgs.GetHelpMessage(); } tfm::format(std::cout, "%s", strUsage.c_str()); return true; } try { if (!fs::is_directory(GetDataDir(false))) { tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } if (!gArgs.ReadConfigFiles(error, true)) { tfm::format(std::cerr, "Error reading configuration file: %s\n", error.c_str()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { tfm::format(std::cerr, "Error: %s\n", e.what()); return false; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { tfm::format(std::cerr, "Error: Command line contains unexpected token '%s', see torchcoind -h for a list of options.\n", argv[i]); return false; } } // -server defaults to true for bitcoind but not for the GUI so do this here gArgs.SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); if (!AppInitBasicSetup()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitParameterInteraction()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitSanityChecks()) { // InitError will have been called with detailed error, which ends up on console return false; } if (gArgs.GetBoolArg("-daemon", false)) { #if HAVE_DECL_DAEMON #if defined(MAC_OSX) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif tfm::format(std::cout, "Torchcoin server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) tfm::format(std::cerr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #if defined(MAC_OSX) #pragma GCC diagnostic pop #endif #else tfm::format(std::cerr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } // Lock data directory after daemonization if (!AppInitLockDataDirectory()) { // If locking the data directory failed, exit immediately return false; } fRet = AppInitMain(interfaces); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(nullptr, "AppInit()"); } if (!fRet) { Interrupt(); } else { WaitForShutdown(); } Shutdown(interfaces); return fRet; } int main(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); // Connect bitcoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); }
#include "Race.h" #include <iostream> /* YOU MUST WRITE THE IMPLEMENTATIONS OF THE REQUESTED FUNCTIONS IN THIS FILE. START YOUR IMPLEMENTATIONS BELOW THIS LINE */ Race::Race(std::string given_race_name): race_name {given_race_name}, average_laptime {Laptime(Utilizer::generateAverageLaptime())}, head {NULL} {} Race::Race(const Race& rhs_race):average_laptime{rhs_race.average_laptime.getLaptime()}, race_name{rhs_race.race_name}, head{NULL} { Car* rhs_car_traveller = rhs_race.head; Car* this_car_traveller; if(rhs_car_traveller){ Car* new_car = new Car(rhs_car_traveller->getDriverName()); new_car->setPerformance(rhs_car_traveller->getPerformance()); this->head = new_car; rhs_car_traveller = rhs_car_traveller->getNext(); this_car_traveller = this->head; while(rhs_car_traveller){ Car* new_car = new Car(rhs_car_traveller->getDriverName()); new_car->setPerformance(rhs_car_traveller->getPerformance()); this_car_traveller->setNext(new_car); this_car_traveller = this_car_traveller->getNext(); rhs_car_traveller = rhs_car_traveller->getNext(); } } } Race::~Race(){ // TO DO: IT DOES NOT DYNAMICLY DELETES LAPTIMES NOW !! Car* temp_car; Car* this_car_traveller=this->head; while(this_car_traveller){ temp_car=this_car_traveller->getNext(); delete this_car_traveller; this_car_traveller = temp_car; } } std::string Race::getRaceName() const{ return race_name; } void Race::addCartoRace(){ std::string car_name = Race::randomName(); Car* new_car = new Car(car_name); Car* temp = this->head; // TO DO: NOW NEW CAR ADDED TO THE BEGINNING, CHECK IT this->head = new_car; this->head->setNext(temp); } void Race::addCartoRace(Car& car){ Car* temp = this->head; // TO DO: NOW NEW CAR ADDED TO THE BEGINNING, CHECK IT this->head = &car; this->head->setNext(temp); } int Race::getNumberOfCarsinRace(){ int total_cars = 0; Car* this_car_traveller = this->head; while(this_car_traveller){ total_cars++; this_car_traveller = this_car_traveller->getNext(); } return total_cars; } Car Race::operator[](const int car_in_position){ Car* this_car_traveller = this->head; int curr_car =0; while(curr_car < car_in_position){ this_car_traveller = this_car_traveller->getNext(); curr_car++; if(this_car_traveller==NULL){ printf("Car does not exist\n"); exit(1); } } return (*this_car_traveller); } Car Race::operator[](std::string driver_name){ Car* this_car_traveller = this->head; while(this_car_traveller){ if(this_car_traveller->getDriverName() == driver_name){ return (*this_car_traveller); } this_car_traveller = this_car_traveller->getNext(); } printf("Car with given name does not exist\n"); exit(1); } int main(){ Race a("alemciler"); Car* b = new Car("ayi hazan"); a.addCartoRace(*b); Laptime avg(60000); a["ayi hazan"].Lap(avg); a.addCartoRace(); std::cout<<a["ayi hazan"].getHead()->getLaptime()<<std::endl; //std::cout<<a.randomName()<<std::endl; return 0; }
add $r1 $r2 $r3 sub $r1 $r2 $r3 sub $r5 $r6 $r3 jal 0x3456 bne $r1 $r2 0x1234 lw $r1 4($r3) sw $r1 4($r3)
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft import six %> <%docstring>get_mempolicy(mode, nodemask, maxnode, addr, flags) -> str Invokes the syscall get_mempolicy. See 'man 2 get_mempolicy' for more information. Arguments: mode(int*): mode nodemask(unsigned*): nodemask maxnode(unsigned): maxnode addr(unsigned): addr flags(unsigned): flags Returns: int </%docstring> <%page args="mode=0, nodemask=0, maxnode=0, addr=0, flags=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = [] can_pushstr_array = [] argument_names = ['mode', 'nodemask', 'maxnode', 'addr', 'flags'] argument_values = [mode, nodemask, maxnode, addr, flags] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False))) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)): if isinstance(arg, six.text_type): arg = arg.encode('utf-8') string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_get_mempolicy']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* get_mempolicy(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
; A082910: a(n) = prime(prime(n+1)-prime(n)). ; 2,3,3,7,3,7,3,7,13,3,13,7,3,7,13,13,3,13,7,3,13,7,13,19,7,3,7,3,7,43,7,13,3,29,3,13,13,7,13,13,3,29,3,7,3,37,37,7,3,7,13,3,29,13,13,13,3,13,7,3,29,43,7,3,7,43,13,29,3,7,13,19,13,13,7,13,19,7,19,29,3,29,3,13,7,13 seq $0,46933 ; Number of composites between successive primes. seq $0,40 ; The prime numbers.