text
stringlengths
1
1.05M
;-------------------------------------------------------------------------- ; ; Program: 2048.asm ; Final Project ; Name: Ryan Pendleton ; Class: CS2810 ; Date: 5 Dec 2014 ; Version: 1.0 ; ; Ethics: I declare that the following source code was written ; solely by me. I understand that copying any source ; code, in whole or in part, constitutes cheating, ; and that I will receive a zero grade on this ; project if I am found in violation of this ethic. ; ; X Ryan Pendleton ; ; Description: An implementation of git.io/2048 created using LC-3. ; License can be found in the accompanying LICENSE file. ; ;-------------------------------------------------------------------------- .ORIG x3000 ;-------------------------------------------------------------------------- ; MAIN ; Initializes program ;-------------------------------------------------------------------------- MAIN LD R6, STACK ; load stack pointer LEA R5, BOARD ; load board pointer LEA R0, INSTRUCTION_MESSAGE ; show instructions PUTS LEA R0, PROMPT_TYPE_MESSAGE ; prompt for ANSI terminal JSR PROMPT BRp NEW STI R0, CLEAR_STRING_PTR NEW JSR RESET_BOARD ; reset the board LOOP JSR DISPLAY_BOARD ; display the board JSR GET_KEY ; wait for for a move LD R0, DEAD ; check if user is dead BRp IS_DEAD BRnzp LOOP IS_DEAD JSR DISPLAY_BOARD ; display the board a final time LEA R0, DEATH_MESSAGE ; display the death message PUTS LEA R0, PROMPT_DEATH_MESSAGE ; prompt for a new game JSR PROMPT BRp NEW HALT ; global data STACK .FILL x4000 ; GAME_STATE DEAD .FILL x00 BOARD .FILL x01 ; creates an initial game state that .FILL x07 ; can be used to debug game logic .FILL x08 .FILL x0F ; these cells will normally be reset .FILL x01 .FILL x06 .FILL x09 .FILL x0E .FILL x02 .FILL x05 .FILL x0A .FILL x0D .FILL x03 .FILL x04 .FILL x0B .FILL x0C CLEAR_STRING_PTR .FILL CLEAR_STRING PROMPT_TYPE_MESSAGE .STRINGZ "Are you on an ANSI terminal (y/n)? " PROMPT_DEATH_MESSAGE .STRINGZ "Would you like to play again (y/n)? " DEATH_MESSAGE .STRINGZ "\nYou lost :(\n\n" INSTRUCTION_MESSAGE .STRINGZ "Control the game using WASD keys.\n" ;-------------------------------------------------------------------------- ; RESET_BOARD ; Resets the board and adds two random cells ; Clobbers r0, r1, r2, r3 ;-------------------------------------------------------------------------- RESET_BOARD STR R7, R6, #-1 ADD R6, R6, #-1 AND R0, R0, #0 AND R1, R1, #0 ST R0, DEAD RESET_LOOP ADD R2, R1, R5 STR R0, R2, #0 ADD R1, R1, #1 ADD R2, R1, #-16 BRn RESET_LOOP RESET_RANDOM JSR ADD_RANDOM_CELL JSR ADD_RANDOM_CELL LDR R7, R6, #0 ADD R6, R6, #1 RET ;-------------------------------------------------------------------------- ; GET_KEY ; Waits for the user to press a key, then updates the board based ; Clobbers r0, r1 ;-------------------------------------------------------------------------- GET_KEY STR R7, R6, #-1 ADD R6, R6, #-1 GET_KEY_LOOP GETC LD R1, W_NEG ADD R1, R0, R1 BRz UP LD R1, A_NEG ADD R1, R0, R1 BRz LEFT LD R1, S_NEG ADD R1, R0, R1 BRz DOWN LD R1, D_NEG ADD R1, R0, R1 BRz RIGHT BRnzp GET_KEY_LOOP LEFT JSR SLIDE_BOARD_LEFT BRnzp GET_KEY_CHECK RIGHT JSR ROTATE_BOARD JSR ROTATE_BOARD JSR SLIDE_BOARD_LEFT JSR ROTATE_BOARD JSR ROTATE_BOARD BRnzp GET_KEY_CHECK UP JSR ROTATE_BOARD JSR ROTATE_BOARD JSR ROTATE_BOARD JSR SLIDE_BOARD_LEFT JSR ROTATE_BOARD BRnzp GET_KEY_CHECK DOWN JSR ROTATE_BOARD JSR SLIDE_BOARD_LEFT JSR ROTATE_BOARD JSR ROTATE_BOARD JSR ROTATE_BOARD GET_KEY_CHECK ADD R0, R0, #0 ; R0 contains whether the move was valid BRnz GET_KEY_LOOP ; the move wasn't valid GET_KEY_ADD_RANDOM JSR ADD_RANDOM_CELL ; R0 now contains how many spaces are empty ADD R0, R0, #0 ; check for how many spaces are left BRp GET_KEY_EXIT GET_KEY_CHECK_DEATH JSR CHECK_DEATH ST R0, DEAD GET_KEY_EXIT LDR R7, R6, #0 ADD R6, R6, #1 RET ; data W_NEG .FILL xFF89 ; ~x77+1 A_NEG .FILL xFF9F ; ~x61+1 S_NEG .FILL xFF8D ; ~x73+1 D_NEG .FILL xFF9C ; ~x64+1 ;-------------------------------------------------------------------------- ; ROTATE_BOARD ; Rotates the board clockwise once ;-------------------------------------------------------------------------- ROTATE_BOARD STR R0, R6, #-1 ADD R6, R6, #-1 LDR R0, R5, #1 ; push board[1] STR R0, R6, #-1 LDR R0, R5, #2 ; push board[2] STR R0, R6, #-2 LDR R0, R5, #3 ; push board[3] STR R0, R6, #-3 ADD R6, R6, #-3 ; update stack LDR R0, R5, x0 ; board[3] = board[0] STR R0, R5, x3 LDR R0, R5, x4 ; board[2] = board[4] STR R0, R5, x2 LDR R0, R5, x8 ; board[1] = board[8] STR R0, R5, x1 LDR R0, R5, xC ; board[0] = board[C] STR R0, R5, x0 LDR R0, R5, xD ; board[4] = board[D] STR R0, R5, x4 LDR R0, R5, xE ; board[8] = board[E] STR R0, R5, x8 LDR R0, R5, xF ; board[C] = board[F] STR R0, R5, xC LDR R0, R5, xB ; board[D] = board[B] STR R0, R5, xD LDR R0, R5, x7 ; board[E] = board[7] STR R0, R5, xE LDR R0, R6, #0 ; board[F] = board[3] (from stack) STR R0, R5, xF LDR R0, R6, #1 ; board[B] = board[2] (from stack) STR R0, R5, xB LDR R0, R6, #2 ; board[7] = board[1] (from stack) STR R0, R5, x7 ADD R6, R6, #3 ; restore stack LDR R0, R5, #6 ; push board[6] STR R0, R6, #-1 ADD R6, R6, #-1 ; update stack LDR R0, R5, x5 ; board[6] = board[5] STR R0, R5, x6 LDR R0, R5, x9 ; board[5] = board[9] STR R0, R5, x5 LDR R0, R5, xA ; board[9] = board[A] STR R0, R5, x9 LDR R0, R6, #0 ; board[A] = board[6] (from stack) STR R0, R5, xA ADD R6, R6, #1 ; restore stack LDR R0, R6, #0 ADD R6, R6, #1 RET ;-------------------------------------------------------------------------- ; SLIDE_BOARD_LEFT ; Slide the board to the left ; Returns r0 > 0 if the move was successful ;-------------------------------------------------------------------------- SLIDE_BOARD_LEFT STR R7, R6, #-1 ; save registers STR R1, R6, #-2 ADD R6, R6, #-2 AND R1, R1, #0 ; clear R1 to save if there was a change ADD R0, R5, x0 ; slide first row JSR SLIDE_ROW_LEFT ADD R1, R0, R1 ADD R0, R5, x4 ; slide second row JSR SLIDE_ROW_LEFT ADD R1, R0, R1 ADD R0, R5, x8 ; slide third row JSR SLIDE_ROW_LEFT ADD R1, R0, R1 ADD R0, R5, xC ; slide fourth row JSR SLIDE_ROW_LEFT ADD R0, R0, R1 LDR R1, R6, #0 LDR R7, R6, #1 ADD R6, R6, #2 RET ;-------------------------------------------------------------------------- ; SLIDE_ROW_LEFT ; Slides a row to the left ; Returns r0 = 1 if successful move ; Clobbers r2, r3, r4 ;-------------------------------------------------------------------------- SLIDE_ROW_LEFT STR R1, R6, #-1 ; save registers ADD R6, R6, #-1 AND R1, R1, #0 ; clear R1 (cell counter) AND R2, R2, #0 ; clear R2 (non-empty counter) ; R3 is used to calculate pointers ; R4 stores read cell values SLIDE_CHECKSUM LDR R4, R0, #0 ; calculate checksum board[0] ADD R3, R4, R4 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 LDR R4, R0, #1 ; calculate checksum board[1] ADD R3, R3, R4 ; R3 += R4 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 LDR R4, R0, #2 ; calculate checksum board[2] ADD R3, R3, R4 ; R3 += R4 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 LDR R4, R0, #3 ; calculate checksum board[3] ADD R3, R3, R4 ; R3 += R4 STR R3, R6, #-1 ADD R6, R6, #-1 SLIDE_FIND_LOOP ; shift all cells to left ADD R4, R0, R1 LDR R4, R4, #0 ; get cell at row[non-incremented R1] BRnz SLIDE_CHECK_NEXT SLIDE_FOUND_BOX ADD R3, R0, R2 ADD R2, R2, #1 STR R4, R3, #0 SLIDE_CHECK_NEXT ADD R1, R1, #1 ADD R4, R1, #-4 BRn SLIDE_FIND_LOOP AND R1, R1, #0 ; clear R1 (fill remaining cells with 0) SLIDE_FILL_LOOP ADD R4, R2, #-4 ; check for existing cells BRz SLIDE_FIND_FIRST_MATCH ADD R3, R0, R2 ADD R2, R2, #1 STR R1, R3, #0 BRnzp SLIDE_FILL_LOOP SLIDE_FIND_FIRST_MATCH LDR R1, R0, #0 LDR R3, R0, #1 BRz SLIDE_FINISHED_MATCHING ; if(no_cell) stop_matching NOT R3, R3 ; if(stack[-1] == stack[-2]) ADD R3, R3, #1 ; ADD R3, R1, R3 ; BRnp SLIDE_FIND_SECOND_MATCH ; { ADD R1, R1, #1 ; stack[-1]++; STR R1, R0, #0 ; LDR R1, R0, #2 ; stack[-2] = stack[-3]; STR R1, R0, #1 ; LDR R1, R0, #3 ; stack[-3] = stack[-4]; STR R1, R0, #2 ; AND R1, R1, #0 ; stack[-4] = 0; STR R1, R0, #3 ; ; } SLIDE_FIND_SECOND_MATCH LDR R1, R0, #1 LDR R3, R0, #2 BRz SLIDE_FINISHED_MATCHING ; if(no_cell) stop_matching NOT R3, R3 ; if(stack[-2] == stack[-3]) ADD R3, R3, #1 ; ADD R3, R1, R3 ; BRnp SLIDE_FIND_THIRD_MATCH ; { ADD R1, R1, #1 ; stack[-2]++; STR R1, R0, #1 ; LDR R1, R0, #3 ; stack[-3] = stack[-4]; STR R1, R0, #2 ; AND R1, R1, #0 ; stack[-4] = 0; STR R1, R0, #3 ; ; } BRnzp SLIDE_FINISHED_MATCHING SLIDE_FIND_THIRD_MATCH LDR R1, R0, #2 LDR R3, R0, #3 BRz SLIDE_FINISHED_MATCHING ; if(no_cell) stop_matching NOT R3, R3 ; if(stack[-3] == stack[-4]) ADD R3, R3, #1 ; ADD R3, R1, R3 ; BRnp SLIDE_FINISHED_MATCHING ; { ADD R1, R1, #1 ; stack[-3]++; STR R1, R0, #2 ; AND R1, R1, #0 ; stack[-4] = 0; STR R1, R0, #3 ; ; } SLIDE_FINISHED_MATCHING LDR R4, R0, #0 ; calculate checksum board[0] ADD R3, R4, R4 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 LDR R4, R0, #1 ; calculate checksum board[1] ADD R3, R3, R4 ; R3 += R4 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 LDR R4, R0, #2 ; calculate checksum board[2] ADD R3, R3, R4 ; R3 += R4 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 ADD R3, R3, R3 ; R3 << 1 LDR R4, R0, #3 ; calculate checksum board[3] ADD R3, R3, R4 ; R3 += R4 NOT R3, R3 ADD R3, R3, #1 LDR R4, R6, #0 AND R0, R0, #0 ADD R3, R3, R4 BRz SLIDE_EXIT ADD R0, R0, #1 SLIDE_EXIT LDR R1, R6, #1 ADD R6, R6, #2 RET ;-------------------------------------------------------------------------- ; ADD_RANDOM_CELL ; Adds a random cell to the board ; Returns r0 = empty spaces remaining ; Clobbers r1, r2 ;-------------------------------------------------------------------------- ADD_RANDOM_CELL STR R7, R6, #-1 ADD R6, R6, #-1 AND R1, R1, #0 ; clear R1 (count empty) AND R2, R2, #0 ; clear R2 (count total) ADD_RANDOM_LOOP ADD R0, R2, R5 ; get value at board[R2] ADD R2, R2, #1 STR R0, R6, #-1 ; keep on stack in case empty LDR R0, R0, #0 BRp ADD_RANDOM_NEXT ADD_RANDOM_EMPTY ADD R1, R1, #1 ; empty ADD R6, R6, #-1 ; update stack ADD_RANDOM_NEXT ADD R0, R2, #-16 BRn ADD_RANDOM_LOOP ADD_RANDOM_COUNTED ADD R0, R1, #0 ; calculate random spot BRz ADD_RANDOM_EXIT JSR RAND_MOD ADD R2, R0, R6 ; calculate pointer to spot LD R0, RANDOM_4_MOD ; determine which block to place JSR RAND_MOD ADD R0, R0, #0 ; check if == 0 BRz ADD_RANDOM_4 ADD_RANDOM_2 AND R0, R0, #0 ADD R0, R0, #1 BRnzp ADD_RANDOM_RESTORE ADD_RANDOM_4 ADD R0, R0, #2 ADD_RANDOM_RESTORE ; R0: 1 or 2, depending on block type ; R1: number of empty spots ; R2: pointer to stack spot LDR R2, R2, #0 ; get destination address STR R0, R2, #0 ; store new block in address ADD R0, R1, #-1 ; subtract one from empty spaces since we filled one ADD_RANDOM_EXIT ADD R6, R6, R1 ; restore stack LDR R7, R6, #0 ADD R6, R6, #1 RET ; data RANDOM_4_MOD .FILL xB ; (random() % 11 == 0, so 1/10 chance) ;-------------------------------------------------------------------------- ; CHECK_DEATH ; Checks if there are plays available in a full board ; Returns r0 = 1 if dead, 0 if alive ;-------------------------------------------------------------------------- CHECK_DEATH STR R7, R6, #-1 ; save registers ADD R6, R6, #-1 AND R4, R4, #0 ; 1 if regular, 0 if rotated ADD R4, R4, #1 CHECK_DEATH_LOOP ADD R0, R5, x0 ; check first row JSR CHECK_DEATH_ROW BRz DEATH_FINISHED_CHECKING ADD R0, R5, x4 ; check second row JSR CHECK_DEATH_ROW BRz DEATH_FINISHED_CHECKING ADD R0, R5, x8 ; check third row JSR CHECK_DEATH_ROW BRz DEATH_FINISHED_CHECKING ADD R0, R5, xC ; check fourth row JSR CHECK_DEATH_ROW BRz DEATH_FINISHED_CHECKING ADD R4, R4, #-1 BRn DEATH_FINISHED_CHECKING JSR ROTATE_BOARD BRnzp CHECK_DEATH_LOOP DEATH_FINISHED_CHECKING ADD R4, R4, #0 ; check to see if we rotated the board BRp DEATH_EXIT DEATH_ROTATE JSR ROTATE_BOARD JSR ROTATE_BOARD JSR ROTATE_BOARD DEATH_EXIT LDR R7, R6, #0 ADD R6, R6, #1 ADD R0, R1, #0 RET ;-------------------------------------------------------------------------- ; CHECK_DEATH_ROW ; Checks if there are plays available in a full row (pointed to by r0) ; Returns r1 = 1 if dead, 0 if alive ;-------------------------------------------------------------------------- CHECK_DEATH_ROW LDR R2, R0, x0 ; R2 = row[0] LDR R3, R0, x1 ; R3 = row[1] NOT R3, R3 ADD R3, R3, #1 ; R3 = -row[1] ADD R1, R2, R3 ; R1 = row[0] - row[1] BRz DEATH_ROW_PLAYS_AVAILABLE LDR R2, R0, x2 ; R2 = row[2] ADD R1, R2, R3 ; R1 = row[2] - row[1] BRz DEATH_ROW_PLAYS_AVAILABLE LDR R3, R0, x3 ; R3 = row[3] NOT R3, R3 ADD R3, R3, #1 ; R3 = -row[3] ADD R1, R2, R3 ; R1 = row[2] - row[3] BRz DEATH_ROW_PLAYS_AVAILABLE DEATH_ROW_NO_PLAYS AND R1, R1, #0 ADD R1, R1, #1 DEATH_ROW_PLAYS_AVAILABLE RET ;-------------------------------------------------------------------------- ; DISPLAY_BOARD ; Displays the board and clears the screen on an ANSI terminal ; Clobbers r0, r1, r2, r3 ;-------------------------------------------------------------------------- DISPLAY_BOARD STR R7, R6, #-1 ADD R6, R6, #-1 LEA R0, CLEAR_STRING ; clear screen if on ANSI terminal PUTS LEA R1, BOARD_LABELS AND R2, R2, #0 LEA R0, LINE_BORDER ; display border PUTS LD R0, NEW_LINE OUT DISPLAY_NEXT_LINE LEA R0, EMPTY_BORDER PUTS LD R0, NEW_LINE OUT LEA R0, LEFT_BORDER PUTS DISPLAY_NEXT_SPACE LD R0, SPACE OUT ADD R3, R5, R2 ; get value at board[R2++] LDR R3, R3, #0 ADD R2, R2, #1 ADD R0, R3, R3 ; multiply by 5 ADD R0, R0, R0 ADD R0, R0, R3 ADD R0, R0, R1 ; get the label for board[i] PUTS LD R0, SPACE OUT ADD R0, R2, #-4 ; end of first line BRz DISPLAY_RIGHT_BORDER ADD R0, R2, #-8 ; end of second line BRz DISPLAY_RIGHT_BORDER ADD R0, R2, #-12 ; end of third line BRz DISPLAY_RIGHT_BORDER ADD R0, R2, #-16 ; end of last line BRz DISPLAY_RIGHT_BORDER BRnp DISPLAY_NEXT_SPACE DISPLAY_RIGHT_BORDER LEA R0, RIGHT_BORDER PUTS ADD R0, R2, #-16 ; end of last line BRnp DISPLAY_NEXT_LINE DISPLAY_BOTTOM_BORDER LEA R0, EMPTY_BORDER PUTS LD R0, NEW_LINE OUT LEA R0, LINE_BORDER PUTS LD R0, NEW_LINE OUT DIS_FINISH LDR R7, R6, #0 ADD R6, R6, #1 RET ; data ; SYSTEM_TYPE ; first byte of clear string is either \e or \0 CLEAR_STRING .STRINGZ "\e[2J\e[H\e[3J" LINE_BORDER .STRINGZ "+--------------------------+" EMPTY_BORDER .STRINGZ "| |" LEFT_BORDER .STRINGZ "| " RIGHT_BORDER .STRINGZ " |\n" SPACE .FILL x20 ; space NEW_LINE .FILL x0A ; new line BOARD_LABELS .STRINGZ " " .STRINGZ " 2 " .STRINGZ " 4 " .STRINGZ " 8 " .STRINGZ " 16 " .STRINGZ " 32 " .STRINGZ " 64 " .STRINGZ "128 " .STRINGZ "256 " .STRINGZ "512 " .STRINGZ "1024" .STRINGZ "2048" .STRINGZ "4096" .STRINGZ "8192" .STRINGZ "2^14" .STRINGZ "2^15" .STRINGZ "2^16" ;-------------------------------------------------------------------------- ; RAND_MOD ; Generates random number between 0 and r0 - 1 inclusively ; Returns r0 = random number ;-------------------------------------------------------------------------- RAND_MOD STR R0, R6, #-1 STR R1, R6, #-2 STR R2, R6, #-3 STR R7, R6, #-4 ADD R6, R6, #-4 LD R0, RAND_SEED LD R1, RAND_Q JSR MOD_DIV ; R0 = x % q LD R1, RAND_A JSR MULT ; R0 = (x % q) * a ST R0, RAND_SEED LDR R1, R6, #3 ; get original R0 JSR MOD_DIV LDR R7, R6, #0 LDR R2, R6, #1 LDR R1, R6, #2 ADD R6, R6, #4 RET ; data RAND_INIT .FILL x0000 RAND_SEED .FILL xC20D RAND_A .FILL x0007 RAND_M .FILL x7FFF ; 2^15 - 1 RAND_Q .FILL x1249 ; M/A ;-------------------------------------------------------------------------- ; PROMPT ; Prompts the user until they enter y/n ; Returns r0 = 0 if false, 1 if true, sets flags ;-------------------------------------------------------------------------- PROMPT STR R0, R6, #-1 ; save registers STR R1, R6, #-2 STR R7, R6, #-3 ADD R6, R6, #-3 PROMPT_LOOP ; prompt until y/n LDR R0, R6, #2 PUTS JSR GETC_SEED OUT ADD R1, R0, #0 LD R0, PROMPT_NEW_LINE OUT LD R0, PROMPT_RESPONSE_y ADD R0, R0, R1 BRz PROMPT_YES LD R0, PROMPT_RESPONSE_n ADD R0, R0, R1 BRz PROMPT_NO PROMPT_INVALID ADD R0, R1, #0 OUT LEA R0, PROMPT_INVALID_MESSAGE PUTS BRnzp PROMPT_LOOP PROMPT_NO AND R0, R0, #0 BRnzp PROMPT_EXIT PROMPT_YES AND R0, R0, #0 ADD R0, R0, #1 PROMPT_EXIT LDR R7, R6, #0 ; restore registers LDR R1, R6, #1 ADD R6, R6, #3 ADD R0, R0, #0 RET ; data PROMPT_INVALID_MESSAGE .STRINGZ " is not a valid input.\n\n" PROMPT_RESPONSE_y .FILL xFF87 ; ~x79+1 PROMPT_RESPONSE_n .FILL xFF92 ; ~x6e+1 PROMPT_NEW_LINE .FILL x0A ;-------------------------------------------------------------------------- ; GETC_SEED ; Seeds random number generator while getting a character from the keyboard ; Returns r0 = character ;-------------------------------------------------------------------------- GETC_SEED STR R1, R6, #-1 ; save R1 ADD R6, R6, #-1 AND R1, R1, #0 GETC_SEED_LOOP ; R1++ until character pressed ADD R1, R1, #1 LDI R0, OS_KBSR BRzp GETC_SEED_LOOP LD R0, SEED_MASK AND R1, R1, R0 LDI R0, OS_KBDR ; get character ST R1, RAND_SEED ; save R1 to seed ST R1, RAND_INIT ; save initial for debugging LDR R1, R6, #0 ; restore R1 ADD R6, R6, #1 RET ; data OS_KBSR .FILL xFE00 OS_KBDR .FILL xFE02 SEED_MASK .FILL x7FFF ;-------------------------------------------------------------------------- ; MOD_DIV ; Performs r0 % r1 and r0/r1. ; Returns r0 = remainder, r1 = quotient ;-------------------------------------------------------------------------- MOD_DIV STR R1, R6, #-1 ; save registers STR R2, R6, #-2 STR R3, R6, #-3 ADD R6, R6, #-3 NOT R2, R1 ADD R2, R2, #1 BRz MOD_DIV_EX ; halt if dividing by zero AND R1, R1, #0 ; clear R1 (quotient) MOD_DIV_LOOP ADD R1, R1, #1 ADD R0, R0, R2 ; R0 -= R1 BRp MOD_DIV_LOOP ; R0 - R1 > 0, so keep looping BRz MOD_DIV_END ; R0 = 0, so we finished exactly ; R0 < 0, so we subtracted an extra one LDR R2, R6, #2 ; add it back in ADD R1, R1, #-1 ADD R0, R0, R2 MOD_DIV_END LDR R3, R6, #0 LDR R2, R6, #1 ADD R6, R6, #3 RET MOD_DIV_EX HALT ;-------------------------------------------------------------------------- ; MULT ; Performs multiplication using bit shifting ; Returns r0 = r0 * r1 ;-------------------------------------------------------------------------- MULT ADD R0, R0, #0 BRz MULT_ZERO ; return 0 if R0 = 0 ADD R1, R1, #0 BRz MULT_ZERO ; return 0 if R1 = 0 STR R1, R6, #-1 ; save registers STR R2, R6, #-2 ; save registers STR R3, R6, #-3 STR R4, R6, #-4 ADD R6, R6, #-4 AND R2, R2, #0 ; clear R2 (product) ADD R3, R2, #1 ; set R3 = 1 (bit tester) MULT_LOOP ; for each bit in R0 AND R4, R0, R3 ; R4 = bit test(R0, R3) BRnz #1 ; only execute next line if bit is set ADD R2, R2, R1 ; product = product + R1 ADD R1, R1, R1 ; R1 << 1 ADD R3, R3, R3 ; R3 << 1 BRp MULT_LOOP ADD R0, R2, #0 ; move product to R0 MULT_END LDR R4, R6, #0 ; restore registers LDR R3, R6, #1 LDR R2, R6, #2 LDR R1, R6, #3 ADD R6, R6, #4 RET MULT_ZERO AND R0, R0, #0 RET .END
MODULE ba_BestFit_callee SECTION code_alloc_balloc PUBLIC ba_BestFit_callee PUBLIC _ba_BestFit_callee EXTERN balloc_firstfit_callee defc ba_BestFit_callee = balloc_firstfit_callee defc _ba_BestFit_callee = balloc_firstfit_callee
; ******************************************************************************************* ; ******************************************************************************************* ; ; Name : interface_tools.asm ; Purpose : Interface routines ; Date : 18th August 2019 ; Author : Paul Robson (paul@robsons.org.uk) ; ; ******************************************************************************************* ; ******************************************************************************************* ; ******************************************************************************************* ; ; Clear Screen ; ; ******************************************************************************************* IFT_ClearScreen: pha phx phy jsr IF_Home ; home cursor ldx #IF_Height ; this many lines. _IFT_CS0: ldy #IF_Width ; this many chars/line _IFT_CS1: lda #' ' ; clear line. jsr IF_Write dey bne _IFT_CS1 jsr IF_NewLine ; next line down dex bne _IFT_CS0 ply plx pla ; ******************************************************************************************* ; ; Home Cursor ; ; ******************************************************************************************* IFT_HomeCursor: pha jsr IF_Home lda #0 sta IFT_XCursor sta IFT_YCursor pla rts ; ******************************************************************************************* ; ; Up one line ; ; ******************************************************************************************* IFT_UpLine: pha lda IFT_YCursor ; get Y dec a ; line above bmi _IFTULExit ; too far, abort jsr IFT_SetYPos ; set to that line. _IFTULExit: pla rts ; ******************************************************************************************* ; ; Print Character on screen (ASCII in A) ; ; ******************************************************************************************* IFT_PrintCharacter: cmp #13 ; handle newline. beq IFT_NewLine cmp #8 beq _IFT_Left pha jsr IFT_UpperCase ; make upper case jsr IF_Write ; write out. inc IFT_XCursor ; bump x cursor lda IFT_XCursor ; reached RHS ? cmp #IF_Width bne _IFT_PCNotEOL jsr IFT_NewLine ; if so do new line. _IFT_PCNotEOL: pla rts _IFT_Left: pha jsr IF_LeftOne pla rts ; ******************************************************************************************* ; ; Go to next line ; ; ******************************************************************************************* IFT_NewLine: pha jsr IF_NewLine ; new line on actual screen. lda #0 ; reset x position sta IFT_XCursor inc IFT_YCursor ; move down. lda IFT_YCursor cmp #IF_Height ; reached bottom. bne _IFT_NL_NotEOS jsr IFT_Scroll ; scroll screen up. _IFT_NL_NotEOS: pla rts ; ******************************************************************************************* ; ; Capitalise ASCII character ; ; ******************************************************************************************* IFT_UpperCase: cmp #"a" bcc _IFT_UCExit cmp #"z"+1 bcs _IFT_UCExit eor #$20 _IFT_UCExit: rts IFT_Scroll: pha ; save AXY phx phy ldx #0 ; start scrolling. _IFT_SLoop: jsr _IFT_ScrollLine ; scroll line X+1 => X inx cpx #IF_Height-1 ; do whole screen bne _IFT_SLoop lda #IF_Height-1 ; move to X = 0,Y = A jsr IFT_SetYPos ldx #IF_Width ; blank line _IFT_SBlank: lda #32 jsr IF_Write dex bne _IFT_SBlank ; lda #IF_Height-1 ; move to X = 0,Y = A jsr IFT_SetYPos ply plx pla rts _IFT_ScrollLine: phx phx txa ; copy line into buffer. inc a ; next line down. jsr IFT_SetYPos ldx #0 _IFTScrollCopy1: jsr IF_Read sta IFT_Buffer,x inx cpx #IF_Width bne _IFTScrollCopy1 pla jsr IFT_SetYPos ldx #0 _IFTScrollCopy2: lda IFT_Buffer,x jsr IF_Write inx cpx #IF_Width bne _IFTScrollCopy2 plx rts ; ******************************************************************************************* ; ; Move to (0,A) ; ; ******************************************************************************************* IFT_SetYPos: pha phx tax jsr IFT_HomeCursor cpx #0 beq _IFT_MOAExit _IFT_MOALoop: jsr IF_NewLine inc IFT_YCursor dex bne _IFT_MOALoop _IFT_MOAExit: plx pla rts ; ******************************************************************************************* ; ; Get key, showing cursor highlight ; ; ******************************************************************************************* IFT_GetKeyCursor: jsr _IFT_FlipCursor ; reverse current _IFT_GKCWait: jsr IF_GetKey ; get key beq _IFT_GKCWait _IFT_FlipCursor: pha ; save jsr IF_Read ; read jsr IF_LeftOne eor #$80 ; reverse jsr IF_Write ; write jsr IF_LeftOne pla rts ; ******************************************************************************************* ; ; Read line into buffer ; ; ******************************************************************************************* IFT_ReadLine: pha _IFT_RLLoop: jsr IFT_GetKeyCursor ; get keystroke cmp #13 ; return beq _IFT_RLExit cmp #32 ; control character bcc _IFT_Control jsr IFT_PrintCharacter bra _IFT_RLLoop ; _IFT_Control: cmp #"A"-64 beq _IFT_Left cmp #"D"-64 beq _IFT_Right cmp #"W"-64 beq _IFT_Up cmp #"S"-64 beq _IFT_Down cmp #"H"-64 beq _IFT_Backspace cmp #"Z"-64 bne _IFT_RLLoop jsr IFT_ClearScreen ; clear CTL-Z bra _IFT_RLLoop ; _IFT_Backspace: lda IFT_XCursor ; check not start of line. beq _IFT_RLLoop jsr IF_LeftOne lda #" " ; overwrite with space, drop through to left jsr IF_Write ; _IFT_Left: dec IFT_XCursor ; left CTL-W bpl _IFT_Reposition lda #IF_Width-1 _IFT_SetX: sta IFT_XCursor bra _IFT_Reposition _IFT_Right: ; right CTL-D inc IFT_XCursor lda IFT_XCursor eor #IF_Width beq _IFT_SetX bra _IFT_Reposition ; _IFT_Up: ; up CTL-A dec IFT_YCursor bpl _IFT_Reposition lda #IF_Height-1 _IFT_SetY: sta IFT_YCursor bra _IFT_Reposition _IFT_Down: ; down CTL-S inc IFT_YCursor lda IFT_YCursor eor #IF_Height beq _IFT_SetY ; _IFT_Reposition: lda IFT_XCursor ; put cursor at xCursor,yCursor pha lda IFT_YCursor jsr IFT_SetYPos pla tax cpx #0 beq _IFT_RLLoop _IFT_MoveRight: jsr IF_Read inc IFT_XCursor dex bne _IFT_MoveRight jmp _IFT_RLLoop ; _IFT_RLExit: ; CR-Exit. lda IFT_YCursor ; go to start of line. jsr IFT_SetYPos ldx #0 ; read text into line. _IFT_RLRead: jsr IF_Read sta IFT_LineBuffer,x inx cpx #IF_Width bne _IFT_RLRead ; _IFT_RL_Trim: ; trim RH spaces dex ; previous char bmi _IFT_Found ; gone too far lda IFT_LineBuffer,x ; go back if space cmp #" " beq _IFT_RL_Trim _IFT_Found: inx ; forward to non-space lda #0 ; make it ASCIIZ sta IFT_LineBuffer,x jsr IFT_NewLine ; go to next line. pla ldx #IFT_LineBuffer & $FF ; put address in YX ldy #IFT_LineBuffer >> 8 rts
BITS 64 section .text global _start _start: mov rax, 1 mov rdi, 1 mov rsi, msg mov rdx, msglen syscall mov rdi, [g] mov rax, 60 syscall section .data global g g: dq 30 msg: db "Hello, world!", 10 msglen: equ $ - msg
; A167562: The fifth row of the ED2 array A167560. ; 120,480,1344,3072,6144,11160,18840,30024,45672,66864,94800,130800,176304,232872,302184,386040,486360,605184,744672,907104,1094880,1310520,1556664,1836072,2151624,2506320,2903280,3345744,3837072,4380744,4980360,5639640,6362424,7152672,8014464,8952000,9969600,11071704,12262872,13547784,14931240,16418160,18013584,19722672,21550704,23503080,25585320,27803064,30162072,32668224,35327520,38146080,41130144,44286072,47620344,51139560,54850440,58759824,62874672,67202064,71749200,76523400,81532104,86782872,92283384,98041440,104064960,110361984,116940672,123809304,130976280,138450120,146239464,154353072,162799824,171588720,180728880,190229544,200100072,210349944,220988760,232026240,243472224,255336672,267629664,280361400,293542200,307182504,321292872,335883984,350966640,366551760,382650384,399273672,416432904,434139480,452404920,471240864,490659072,510671424 mov $7,$0 mul $0,2 add $0,9 mov $4,$0 sub $0,3 mov $1,1 sub $4,1 lpb $0 sub $0,1 trn $2,5 add $2,$1 add $1,$4 add $2,2 lpe add $1,$2 sub $1,44 mov $3,56 mov $8,$7 lpb $3 add $1,$8 sub $3,1 lpe mov $5,$7 lpb $5 sub $5,1 add $6,$8 lpe mov $3,85 mov $8,$6 lpb $3 add $1,$8 sub $3,1 lpe mov $5,$7 mov $6,0 lpb $5 sub $5,1 add $6,$8 lpe mov $3,26 mov $8,$6 lpb $3 add $1,$8 sub $3,1 lpe mov $5,$7 mov $6,0 lpb $5 sub $5,1 add $6,$8 lpe mov $3,5 mov $8,$6 lpb $3 add $1,$8 sub $3,1 lpe mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r10 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x1c3dc, %rsi lea addresses_normal_ht+0xd13c, %rdi dec %r10 mov $18, %rcx rep movsw nop nop nop add $45555, %rbp lea addresses_A_ht+0x13e3c, %rbx nop nop nop nop nop add $52767, %rax movl $0x61626364, (%rbx) nop nop and $17453, %r10 lea addresses_WC_ht+0x9f3c, %rbp nop nop cmp $23223, %rdi mov $0x6162636465666768, %rbx movq %rbx, %xmm6 vmovups %ymm6, (%rbp) nop cmp %rdi, %rdi lea addresses_A_ht+0xce3c, %rdi nop nop nop nop cmp $8504, %rsi mov $0x6162636465666768, %rax movq %rax, %xmm6 vmovups %ymm6, (%rdi) sub $42568, %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r15 push %r8 push %rsi // Faulty Load mov $0x72ff160000000a3c, %rsi xor $8535, %r11 vmovaps (%rsi), %ymm4 vextracti128 $1, %ymm4, %xmm4 vpextrq $0, %xmm4, %r8 lea oracles, %r11 and $0xff, %r8 shlq $12, %r8 mov (%r11,%r8,1), %r8 pop %rsi pop %r8 pop %r15 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_NC', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_NC', 'AVXalign': True, 'size': 32, 'NT': True, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 7}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 10}} {'e2': 1, 'bd': 2, '96': 1, '3d': 1, 'cc': 1, 'd1': 1, 'd9': 3, '41': 2, 'ab': 1, 'f6': 1, '4d': 2, 'ca': 1, 'df': 2, '03': 2, 'eb': 1, '67': 3, 'db': 1, 'fd': 3, '2b': 2, 'f2': 1, '91': 2, 'c4': 1, 'f3': 2, '30': 1, 'f8': 1, '63': 1, 'a4': 1, 'd5': 2, '1e': 1, '77': 1, 'd8': 1, '9c': 1, '1d': 1, '22': 1, 'b0': 1, 'c7': 1, '0a': 1, 'c3': 2, 'd0': 2, '38': 1, 'e5': 2, '87': 1, '6c': 1, 'da': 2, '0b': 2, 'e0': 1, '21': 1, 'af': 1, '6e': 1, 'd7': 1, '4b': 1, 'cf': 2, '02': 207, 'ef': 1, '6d': 2, '00': 2, '09': 2, 'ec': 1, 'dd': 1, '8f': 1, '98': 1, 'ff': 2, '42': 1, '7c': 109, 'f1': 1, '65': 1, 'e9': 2, 'b2': 1, 'c9': 1, '6b': 2, '37': 1, '4f': 3, '5d': 1, 'f7': 3, '3f': 1, 'f0': 1, '2f': 2, 'a5': 1, '7f': 1, '8c': 1, '46': 1, '2d': 1, '79': 1, 'b1': 1, '2c': 1, '59': 1, '61': 1, '01': 1, 'f9': 2, '92': 1, '32': 1, '47': 1, '71': 2, '88': 1, 'e1': 1, '7a': 1, '3e': 1, 'ba': 1, 'cd': 2, '97': 1, '3c': 1, '19': 1, '56': 1, '3a': 1, '28': 1, '60': 20911, '55': 2, 'a9': 1, '8b': 2, 'fe': 2, '7b': 77, '83': 2, '85': 3, 'fc': 1, '39': 1, '84': 1, '78': 1, '29': 1, '31': 1, 'e6': 2, '1b': 2, '5f': 2, 'ce': 1, '70': 1, 'e3': 1, 'f5': 3, '57': 1, '12': 1, '81': 3, 'b5': 2, 'b7': 1, '06': 341, 'd6': 1, 'bb': 1, '3b': 1, 'c5': 1, '0d': 1, 'cb': 2, '2e': 1} 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 fd 60 60 60 60 60 60 60 60 02 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 42 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 02 60 02 60 60 60 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 7b 60 60 60 60 60 60 60 06 60 60 60 60 60 60 60 60 60 02 60 60 60 60 60 60 60 60 56 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 06 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 e0 60 06 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 7b 60 02 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 02 60 60 60 60 60 60 60 60 60 60 60 60 60 7c 60 06 60 60 60 60 60 60 60 60 60 60 60 60 06 60 60 60 02 60 60 60 60 60 60 60 af 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 7b 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 39 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 4d 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 92 60 60 60 60 60 60 60 02 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 d7 60 60 60 60 60 60 60 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 7b 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 7b 60 60 60 60 60 60 60 60 60 06 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 7c 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 02 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 ba 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 02 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 7b 60 60 60 60 06 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 ce 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 06 60 06 60 60 60 60 60 06 60 */
; A180123: Second of three "least, sum, least" self-generating sequences. ; 2,6,10,13,17,21,25,28,32,36,40,43,47,51,54,58,62,66,69,73,77,81,84,88,92,96,99,103,107,110,114,118,122,125,129,133,137,140,144,148,152,155,159,163,166,170,174,178,181,185,189,193,196,200,204,207,211,215,219,222,226,230,234,237,241,245,249,252,256,260,263,267,271,275,278,282,286,290,293,297,301,305,308,312,316,319,323,327,331,334,338,342,346,349,353,357,361,364,368,372,375,379,383,387,390,394,398,402,405,409,413,416,420,424,428,431,435,439,443,446,450,454,458,461,465,469,472,476,480,484,487,491,495,499,502,506,510,514,517,521,525,528,532,536,540,543,547,551,555,558,562,566,570,573,577,581,584,588,592,596,599,603,607,611,614,618,622,625,629,633,637,640,644,648,652,655,659,663,667,670,674,678,681,685,689,693,696,700,704,708,711,715,719,723,726,730,734,737,741,745,749,752,756,760,764,767,771,775,778,782,786,790,793,797,801,805,808,812,816,820,823,827,831,834,838,842,846,849,853,857,861,864,868,872,876,879,883,887,890,894,898,902,905,909,913,917,920,924,928,932 mov $2,$0 add $2,1 mov $5,$0 lpb $2 mov $0,$5 sub $2,1 sub $0,$2 mov $7,$0 mov $9,2 lpb $9 mov $0,$7 sub $9,1 add $0,$9 sub $0,1 mov $11,$0 add $0,1 add $6,$0 pow $0,2 mul $0,3 mov $3,1 trn $3,$6 lpb $0 add $3,2 sub $0,$3 trn $0,1 lpe mov $4,$3 mov $12,$11 mul $12,2 add $4,$12 mov $8,$9 lpb $8 sub $8,1 mov $10,$4 lpe lpe lpb $7 mov $7,0 sub $10,$4 lpe mov $4,$10 trn $4,4 add $4,6 add $1,$4 lpe sub $1,6 div $1,2 add $1,2
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("files/input.txt", "r", stdin); freopen("files/output.txt", "w", stdout); #endif ll n; cin >> n; vector<ll> arr(n); for (ll i = 0; i < n; ++i) cin >> arr[i]; sort(arr.begin(), arr.end()); ll i = 0, j = arr.size() - 1, total = 0; while(i < j) { ll k = (arr[i] + arr[j]); total += (k * k); i++; j--; } cout << total << endl; return 0; }
; A152773: 3 times heptagonal numbers: a(n) = 3n(5n-3)/2. ; 0,3,21,54,102,165,243,336,444,567,705,858,1026,1209,1407,1620,1848,2091,2349,2622,2910,3213,3531,3864,4212,4575,4953,5346,5754,6177,6615,7068,7536,8019,8517,9030,9558,10101,10659,11232,11820,12423,13041,13674,14322,14985,15663,16356,17064,17787,18525,19278,20046,20829,21627,22440,23268,24111,24969,25842,26730,27633,28551,29484,30432,31395,32373,33366,34374,35397,36435,37488,38556,39639,40737,41850,42978,44121,45279,46452,47640,48843,50061,51294,52542,53805,55083,56376,57684,59007,60345,61698 mov $1,$0 bin $1,2 mul $1,5 add $0,$1 mul $0,3
; A111093: Like sequence A111072 but moving right by the squares of the sequence of positive integers. ; 0,1,6,10,10,15,16,16,20,25,30,36,36,45,50,50,56,61,70,70,70,71,76,80,80,85,86,86,90,95,100,106,106,115,120,120,126,131,140,140,140,141,146,150,150,155,156,156,160,165,170,176,176,185,190,190,196,201,210,210 mov $2,$0 mov $3,$0 lpb $2 mov $0,$3 sub $2,1 sub $0,$2 mov $4,0 mov $6,0 lpb $0 mov $5,$0 sub $0,1 add $6,$5 add $4,$6 lpe mod $4,10 add $1,$4 lpe mov $0,$1
; ; Copyright (C) 2008-2020 Advanced Micro Devices, 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. ; 3. Neither the name of the copyright holder nor the names of its contributors ; may be used to endorse or promote products derived from this software without ; specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ; IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ; BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ; OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; ; ; vrs4sinf.asm ; ; A vector implementation of the sin libm function. ; ; Prototype: ; ; __m128 vrs4_sinf(__m128 x); ; ; Computes Sine of x for an array of input values. ; Places the results into the supplied y array. ; Does not perform error checking. ; Denormal inputs may produce unexpected results. ; This routine computes 4 single precision Sine values at a time. ; The four values are passed as packed single in xmm10. ; The four results are returned as packed singles in xmm10. ; Note that this represents a non-standard ABI usage, as no ABI ; ( and indeed C) currently allows returning 2 values for a function. ; It is expected that some compilers may be able to take advantage of this ; interface when implementing vectorized loops. Using the array implementation ; of the routine requires putting the inputs into memory, and retrieving ; the results from memory. This routine eliminates the need for this ; overhead if the data does not already reside in memory. ; Author: Harsha Jagasia ; Email: harsha.jagasia@amd.com CONST SEGMENT __real_7fffffffffffffff DQ 07fffffffffffffffh ;Sign bit zero DQ 07fffffffffffffffh __real_3ff0000000000000 DQ 03ff0000000000000h ; 1.0 DQ 03ff0000000000000h __real_v2p__27 DQ 03e40000000000000h ; 2p-27 DQ 03e40000000000000h __real_3fe0000000000000 DQ 03fe0000000000000h ; 0.5 DQ 03fe0000000000000h __real_3fc5555555555555 DQ 03fc5555555555555h ; 0.166666666666 DQ 03fc5555555555555h __real_3fe45f306dc9c883 DQ 03fe45f306dc9c883h ; twobypi DQ 03fe45f306dc9c883h __real_3ff921fb54400000 DQ 03ff921fb54400000h ; piby2_1 DQ 03ff921fb54400000h __real_3dd0b4611a626331 DQ 03dd0b4611a626331h ; piby2_1tail DQ 03dd0b4611a626331h __real_3dd0b4611a600000 DQ 03dd0b4611a600000h ; piby2_2 DQ 03dd0b4611a600000h __real_3ba3198a2e037073 DQ 03ba3198a2e037073h ; piby2_2tail DQ 03ba3198a2e037073h __real_fffffffff8000000 DQ 0fffffffff8000000h ; mask for stripping head and tail DQ 0fffffffff8000000h __real_8000000000000000 DQ 08000000000000000h ; -0 or signbit DQ 08000000000000000h __reald_one_one DQ 00000000100000001h ; dq 0 __reald_two_two DQ 00000000200000002h ; dq 0 __reald_one_zero DQ 00000000100000000h ; sin_cos_filter dq 0 __reald_zero_one DQ 00000000000000001h ; dq 0 __reald_two_zero DQ 00000000200000000h ; dq 0 __realq_one_one DQ 00000000000000001h ; DQ 00000000000000001h ; __realq_two_two DQ 00000000000000002h ; DQ 00000000000000002h ; __real_1_x_mask DQ 0ffffffffffffffffh ; DQ 03ff0000000000000h ; __real_zero DQ 00000000000000000h ; DQ 00000000000000000h ; __real_one DQ 00000000000000001h ; DQ 00000000000000001h ; cosarray: DQ 03FA5555555502F31h ; 0.0416667 c1 DQ 03FA5555555502F31h DQ 0BF56C16BF55699D7h ; -0.00138889 c2 DQ 0BF56C16BF55699D7h DQ 03EFA015C50A93B49h ; 2.48016e-005 c3 DQ 03EFA015C50A93B49h DQ 0BE92524743CC46B8h ; -2.75573e-007 c4 DQ 0BE92524743CC46B8h sinarray: DQ 0BFC555555545E87Dh ; -0.166667 s1 DQ 0BFC555555545E87Dh DQ 03F811110DF01232Dh ; 0.00833333 s2 DQ 03F811110DF01232Dh DQ 0BF2A013A88A37196h ; -0.000198413 s3 DQ 0BF2A013A88A37196h DQ 03EC6DBE4AD1572D5h ; 2.75573e-006 s4 DQ 03EC6DBE4AD1572D5h sincosarray: DQ 0BFC555555545E87Dh ; -0.166667 s1 DQ 03FA5555555502F31h ; 0.0416667 c1 DQ 03F811110DF01232Dh ; 0.00833333 s2 DQ 0BF56C16BF55699D7h DQ 0BF2A013A88A37196h ; -0.000198413 s3 DQ 03EFA015C50A93B49h DQ 03EC6DBE4AD1572D5h ; 2.75573e-006 s4 DQ 0BE92524743CC46B8h cossinarray: DQ 03FA5555555502F31h ; 0.0416667 c1 DQ 0BFC555555545E87Dh ; -0.166667 s1 DQ 0BF56C16BF55699D7h ; c2 DQ 03F811110DF01232Dh DQ 03EFA015C50A93B49h ; c3 DQ 0BF2A013A88A37196h DQ 0BE92524743CC46B8h ; c4 DQ 03EC6DBE4AD1572D5h CONST ENDS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; define local variable storage offsets p_temp equ 0 ; temporary for get/put bits operation p_temp1 equ 10h ; temporary for get/put bits operation save_xmm6 equ 20h ; temporary for get/put bits operation save_xmm7 equ 30h ; temporary for get/put bits operation save_xmm8 equ 40h ; temporary for get/put bits operation save_xmm9 equ 50h ; temporary for get/put bits operation save_xmm0 equ 60h ; temporary for get/put bits operation save_xmm11 equ 70h ; temporary for get/put bits operation save_xmm12 equ 80h ; temporary for get/put bits operation save_xmm13 equ 90h ; temporary for get/put bits operation save_xmm14 equ 0A0h ; temporary for get/put bits operation save_xmm15 equ 0B0h ; temporary for get/put bits operation r equ 0C0h ; pointer to r for remainder_piby2 rr equ 0D0h ; pointer to r for remainder_piby2 region equ 0E0h ; pointer to r for remainder_piby2 r1 equ 0F0h ; pointer to r for remainder_piby2 rr1 equ 0100h ; pointer to r for remainder_piby2 region1 equ 0110h ; pointer to r for remainder_piby2 p_temp2 equ 0120h ; temporary for get/put bits operation p_temp3 equ 0130h ; temporary for get/put bits operation p_temp4 equ 0140h ; temporary for get/put bits operation p_temp5 equ 0150h ; temporary for get/put bits operation p_original equ 0160h ; original x p_mask equ 0170h ; original x p_sign equ 0180h ; original x p_original1 equ 0190h ; original x p_mask1 equ 01A0h ; original x p_sign1 equ 01B0h ; original x save_r12 equ 01C0h ; temporary for get/put bits operation save_r13 equ 01D0h ; temporary for get/put bits operation stack_size equ 01E8h ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; include fm.inc FN_PROTOTYPE_BAS64 vrs4_sinf fname_remainder_piby2d2f TEXTEQU <__amd_remainder_piby2d2f> EXTRN fname_remainder_piby2d2f:NEAR .DATA align 8 evensin_oddcos_tbl label qword dq sinsin_sinsin_piby4 ; 0 * ; Done dq sinsin_sincos_piby4 ; 1 + ; Done dq sinsin_cossin_piby4 ; 2 ; Done dq sinsin_coscos_piby4 ; 3 + ; Done dq sincos_sinsin_piby4 ; 4 ; Done dq sincos_sincos_piby4 ; 5 * ; Done dq sincos_cossin_piby4 ; 6 ; Done dq sincos_coscos_piby4 ; 7 ; Done dq cossin_sinsin_piby4 ; 8 ; Done dq cossin_sincos_piby4 ; 9 ; TBD dq cossin_cossin_piby4 ; 10 * ; Done dq cossin_coscos_piby4 ; 11 ; Done dq coscos_sinsin_piby4 ; 12 ; Done dq coscos_sincos_piby4 ; 13 + ; Done dq coscos_cossin_piby4 ; 14 ; Done dq coscos_coscos_piby4 ; 15 * ; Done ;TEXT SEGMENT page 'CODE' .CODE PUBLIC fname fname proc frame sub rsp,stack_size .ALLOCSTACK stack_size ; unwind data, needed since we call ; remainder_piby2 and could have exceptions ; but it costs no performance to include it. movdqa OWORD PTR [rsp+020h],xmm6 ; save xmm6 .SAVEXMM128 xmm6, 020h movdqa OWORD PTR [rsp+030h],xmm7 ; save xmm7 .SAVEXMM128 xmm7, 030h movdqa OWORD PTR [rsp+040h],xmm8 ; save xmm8 .SAVEXMM128 xmm8, 040h movdqa OWORD PTR [rsp+050h],xmm9 ; save xmm9 .SAVEXMM128 xmm9, 050h movdqa OWORD PTR [rsp+060h],xmm10 ; save xmm0 .SAVEXMM128 xmm10, 060h movdqa OWORD PTR [rsp+070h],xmm11 ; save xmm11 .SAVEXMM128 xmm11, 070h movdqa OWORD PTR [rsp+080h],xmm12 ; save xmm12 .SAVEXMM128 xmm12, 080h movdqa OWORD PTR [rsp+090h],xmm13 ; save xmm13 .SAVEXMM128 xmm13, 090h mov QWORD PTR [rsp+save_r12],r12 ; save r12 .SAVEREG r12, save_r12 mov QWORD PTR [rsp+save_r13],r13 ; save r13 .SAVEREG r13, save_r13 .ENDPROLOG movups xmm0, XMMWORD PTR [rcx] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;STARTMAIN movhlps xmm8, xmm0 cvtps2pd xmm10,xmm0 ; convert input to double. cvtps2pd xmm1, xmm8 ; convert input to double. movdqa xmm6, xmm10 movdqa xmm7, xmm1 movapd xmm2, OWORD PTR __real_7fffffffffffffff ;movdqa OWORD PTR p_original[rsp], xmm10 ;movdqa OWORD PTR p_original1[rsp], xmm1 andpd xmm10, xmm2 ;Unsign andpd xmm1, xmm2 ;Unsign movd rax, xmm10 ;rax is lower arg movhpd QWORD PTR p_temp[rsp+8], xmm10 ; mov rcx, QWORD PTR p_temp[rsp+8] ;rcx = upper arg movd r8, xmm1 ;r8 is lower arg movhpd QWORD PTR p_temp1[rsp+8], xmm1 ; mov r9, QWORD PTR p_temp1[rsp+8] ;r9 = upper arg movdqa xmm12,xmm10 movdqa xmm13,xmm1 pcmpgtd xmm12, xmm6 pcmpgtd xmm13, xmm7 movdqa xmm6, xmm12 movdqa xmm7, xmm13 psrldq xmm12, 4 psrldq xmm13, 4 psrldq xmm6, 8 psrldq xmm7, 8 mov rdx, 3FE921FB54442D18h ;piby4 + mov r10, 411E848000000000h ;5e5 + movapd xmm4, OWORD PTR __real_3fe0000000000000 ;0.5 for later use + por xmm12, xmm6 por xmm13, xmm7 movd r12, xmm12 ;Move Sign to gpr ** movd r13, xmm13 ;Move Sign to gpr ** movapd xmm2, xmm10 ;x0 movapd xmm3, xmm1 ;x1 movapd xmm6, xmm10 ;x0 movapd xmm7, xmm1 ;x1 ;DEBUG ; movapd xmm4, xmm10 ; movapd xmm5, xmm1 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; xmm2 = x, xmm4 =0.5/t, xmm6 =x ; xmm3 = x, xmm5 =0.5/t, xmm7 =x align 16 either_or_both_arg_gt_than_piby4: cmp rax, r10 jae first_or_next3_arg_gt_5e5 cmp rcx, r10 jae second_or_next2_arg_gt_5e5 cmp r8, r10 jae third_or_fourth_arg_gt_5e5 cmp r9, r10 jae fourth_arg_gt_5e5 ; /* Find out what multiple of piby2 */ ; npi2 = (int)(x * twobypi + 0.5); movapd xmm10, XMMWORD PTR __real_3fe45f306dc9c883 mulpd xmm2, xmm10 ; * twobypi mulpd xmm3, xmm10 ; * twobypi addpd xmm2,xmm4 ; +0.5, npi2 addpd xmm3,xmm4 ; +0.5, npi2 movapd xmm10,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 movapd xmm1,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 cvttpd2dq xmm4,xmm2 ; convert packed double to packed integers cvttpd2dq xmm5,xmm3 ; convert packed double to packed integers movapd xmm8,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 movapd xmm9,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 cvtdq2pd xmm2,xmm4 ; and back to double. cvtdq2pd xmm3,xmm5 ; and back to double. ; /* Subtract the multiple from x to get an extra-precision remainder */ movd r8, xmm4 ; Region movd r9, xmm5 ; Region mov rdx, QWORD PTR __reald_one_zero ;compare value for cossin path mov r10, r8 mov r11, r9 ; rhead = x - npi2 * piby2_1; mulpd xmm10,xmm2 ; npi2 * piby2_1; mulpd xmm1,xmm3 ; npi2 * piby2_1; ; rtail = npi2 * piby2_2; mulpd xmm8,xmm2 ; rtail mulpd xmm9,xmm3 ; rtail ; rhead = x - npi2 * piby2_1; subpd xmm6,xmm10 ; rhead = x - npi2 * piby2_1; subpd xmm7,xmm1 ; rhead = x - npi2 * piby2_1; ; t = rhead; movapd xmm10, xmm6 ; t movapd xmm1, xmm7 ; t ; rhead = t - rtail; subpd xmm10, xmm8 ; rhead subpd xmm1, xmm9 ; rhead ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulpd xmm2,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail mulpd xmm3,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail subpd xmm6,xmm10 ; t-rhead subpd xmm7,xmm1 ; t-rhead subpd xmm8,xmm6 ; - ((t - rhead) - rtail) subpd xmm9,xmm7 ; - ((t - rhead) - rtail) addpd xmm8,xmm2 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); addpd xmm9,xmm3 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; xmm4 = npi2 (int), xmm10 =rhead, xmm8 =rtail ; xmm5 = npi2 (int), xmm1 =rhead, xmm9 =rtail and r8, QWORD PTR __reald_one_one ;odd/even region for cos/sin and r9, QWORD PTR __reald_one_one ;odd/even region for cos/sin shr r10, 1 ;~AB+A~B, A is sign and B is upper bit of region shr r11, 1 ;~AB+A~B, A is sign and B is upper bit of region mov rax, r10 mov rcx, r11 not r12 ;ADDED TO CHANGE THE LOGIC not r13 ;ADDED TO CHANGE THE LOGIC and r10, r12 and r11, r13 not rax not rcx not r12 not r13 and rax, r12 and rcx, r13 or r10, rax or r11, rcx and r10, __reald_one_one ;(~AB+A~B)&1 and r11, __reald_one_one ;(~AB+A~B)&1 mov r12, r10 mov r13, r11 and r12, rdx ;mask out the lower sign bit leaving the upper sign bit and r13, rdx ;mask out the lower sign bit leaving the upper sign bit shl r10, 63 ;shift lower sign bit left by 63 bits shl r11, 63 ;shift lower sign bit left by 63 bits shl r12, 31 ;shift upper sign bit left by 31 bits shl r13, 31 ;shift upper sign bit left by 31 bits mov QWORD PTR p_sign[rsp],r10 ;write out lower sign bit mov QWORD PTR p_sign[rsp+8],r12 ;write out upper sign bit mov QWORD PTR p_sign1[rsp],r11 ;write out lower sign bit mov QWORD PTR p_sign1[rsp+8],r13 ;write out upper sign bit ; GET_BITS_DP64(rhead-rtail, uy); ; originally only rhead ; xmm4 = Sign, xmm10 =rhead, xmm8 =rtail ; xmm5 = Sign, xmm1 =rhead, xmm9 =rtail movapd xmm6,xmm10 ; rhead movapd xmm7,xmm1 ; rhead subpd xmm10,xmm8 ; r = rhead - rtail subpd xmm1,xmm9 ; r = rhead - rtail ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; xmm4 = Sign, xmm10 = r, xmm6 =rhead, xmm8 =rtail ; xmm5 = Sign, xmm1 = r, xmm7 =rhead, xmm9 =rtail ; subpd xmm6, xmm10 ;rr=rhead-r ; subpd xmm7, xmm1 ;rr=rhead-r mov rax, r8 mov rcx, r9 movapd xmm2,xmm10 ; move r for r2 movapd xmm3,xmm1 ; move r for r2 mulpd xmm2,xmm10 ; r2 mulpd xmm3,xmm1 ; r2 ; subpd xmm6, xmm8 ;rr=(rhead-r) -rtail ; subpd xmm7, xmm9 ;rr=(rhead-r) -rtail and rax, QWORD PTR __reald_zero_one and rcx, QWORD PTR __reald_zero_one shr r8, 31 shr r9, 31 or rax, r8 or rcx, r9 shl rcx, 2 or rax, rcx lea rcx, QWORD PTR evensin_oddcos_tbl jmp QWORD PTR [rcx + rax*8] ;Jmp table for cos/sin calculation based on even/odd region ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 first_or_next3_arg_gt_5e5: ; rax, rcx, r8, r9 ;DEBUG ; movapd xmm4, xmm10 ; movapd xmm5, xmm1 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG cmp rcx, r10 ;is upper arg >= 5e5 jae both_arg_gt_5e5 lower_arg_gt_5e5: ; Upper Arg is < 5e5, Lower arg is >= 5e5 ; xmm10, xmm2, xmm6 = x, xmm4 = 0.5 ; Be sure not to use xmm1, xmm3 and xmm7 ; Use xmm5, xmm8, xmm0, xmm12 ; xmm9, xmm11, xmm13 ;DEBUG ; movapd xmm4, xmm10 ; movapd xmm5, xmm1 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG movlpd QWORD PTR r[rsp], xmm10 ;Save lower fp arg for remainder_piby2 call movhlps xmm10, xmm10 ;Needed since we want to work on upper arg movhlps xmm2, xmm2 movhlps xmm6, xmm6 ; Work on Upper arg ; Lower arg might contain nan/inf, to avoid exception use only scalar instructions on upper arg which has been moved to lower portions of fp regs mulsd xmm2,QWORD PTR __real_3fe45f306dc9c883 ; x*twobypi addsd xmm2,xmm4 ; xmm2 = npi2=(x*twobypi+0.5) movsd xmm8,QWORD PTR __real_3ff921fb54400000 ; xmm8 = piby2_1 cvttsd2si ecx,xmm2 ; ecx = npi2 trunc to ints movsd xmm0,QWORD PTR __real_3dd0b4611a600000 ; xmm0 = piby2_2 cvtsi2sd xmm2,ecx ; xmm2 = npi2 trunc to doubles ;/* Subtract the multiple from x to get an extra-precision remainder */ ;rhead = x - npi2 * piby2_1; mulsd xmm8,xmm2 ; npi2 * piby2_1 subsd xmm6,xmm8 ; xmm6 = rhead =(x-npi2*piby2_1) movsd xmm12,QWORD PTR __real_3ba3198a2e037073 ; xmm12 =piby2_2tail ;t = rhead; movsd xmm5, xmm6 ; xmm5 = t = rhead ;rtail = npi2 * piby2_2; mulsd xmm0,xmm2 ; xmm1 =rtail=(npi2*piby2_2) ;rhead = t - rtail subsd xmm6, xmm0 ; xmm6 =rhead=(t-rtail) ;rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulsd xmm12,xmm2 ; npi2 * piby2_2tail subsd xmm5,xmm6 ; t-rhead subsd xmm0,xmm5 ; (rtail-(t-rhead)) addsd xmm0,xmm12 ; rtail=npi2*piby2_2tail+(rtail-(t-rhead)); ;r = rhead - rtail ;rr = (rhead-r) -rtail mov DWORD PTR region[rsp+4], ecx ; store upper region movsd xmm10,xmm6 subsd xmm10,xmm0 ; xmm10 = r=(rhead-rtail) ; subsd xmm6, xmm10 ; rr=rhead-r ; subsd xmm6, xmm0 ; xmm6 = rr=((rhead-r) -rtail) movlpd QWORD PTR r[rsp+8], xmm10 ; store upper r ; movlpd QWORD PTR rr[rsp+8], xmm6 ; store upper rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Note that volatiles will be trashed by the call ;We will construct r, rr, region and sign ; Work on Lower arg mov r11,07ff0000000000000h ; is lower arg nan/inf mov r10,r11 and r10,rax cmp r10,r11 jz __vrs4_sinf_lower_naninf mov QWORD PTR p_temp[rsp], r8 mov QWORD PTR p_temp2[rsp], r9 movapd OWORD PTR p_temp1[rsp], xmm1 movapd OWORD PTR p_temp3[rsp], xmm3 movapd OWORD PTR p_temp5[rsp], xmm7 ; lea r9, QWORD PTR region[rsp] ; lower arg is **NOT** nan/inf ; lea r8, QWORD PTR rr[rsp] lea r8, QWORD PTR region[rsp] ; lower arg is **NOT** nan/inf lea rdx, QWORD PTR r[rsp] ; changed input from xmm10 to xmm0 ; movlpd xmm10, QWORD PTR r[rsp] ;Restore lower fp arg for remainder_piby2 call ; movlpd xmm0, QWORD PTR r[rsp] ;Restore lower fp arg for remainder_piby2 call mov rcx, QWORD PTR r[rsp] ;Restore lower fp arg for remainder_piby2 call ;change to MS ABI - shadow space sub rsp,020h call fname_remainder_piby2d2f ;change to MS ABI - shadow space add rsp,020h mov r8, QWORD PTR p_temp[rsp] mov r9, QWORD PTR p_temp2[rsp] movapd xmm1, OWORD PTR p_temp1[rsp] movapd xmm3, OWORD PTR p_temp3[rsp] movapd xmm7, OWORD PTR p_temp5[rsp] jmp @F __vrs4_sinf_lower_naninf: ; mov rax, QWORD PTR p_original[rsp] ; upper arg is nan/inf mov r11,00008000000000000h or rax,r11 mov QWORD PTR r[rsp],rax ; r = x | 0x0008000000000000 ; xor r10, r10 ; mov QWORD PTR rr[rsp], r10 ; rr = 0 mov DWORD PTR region[rsp], r10d ; region =0 align 16 @@: ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movapd xmm5, xmm1 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG jmp check_next2_args ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 both_arg_gt_5e5: ;Upper Arg is >= 5e5, Lower arg is >= 5e5 ; rax, rcx, r8, r9 ; xmm10, xmm2, xmm6 = x, xmm4 = 0.5 ;DEBUG ; movapd xmm4, xmm10 ; movapd xmm5, xmm1 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG movhlps xmm6, xmm10 ;Save upper fp arg for remainder_piby2 call mov r11,07ff0000000000000h ;is lower arg nan/inf mov r10,r11 and r10,rax cmp r10,r11 jz __vrs4_sinf_lower_naninf_of_both_gt_5e5 mov QWORD PTR p_temp[rsp], rcx ;Save upper arg mov QWORD PTR p_temp2[rsp], r8 mov QWORD PTR p_temp4[rsp], r9 movapd OWORD PTR p_temp1[rsp], xmm1 movapd OWORD PTR p_temp3[rsp], xmm3 movapd OWORD PTR p_temp5[rsp], xmm7 ; lea r9, QWORD PTR region[rsp] ;lower arg is **NOT** nan/inf ; lea r8, QWORD PTR rr[rsp] lea r8, QWORD PTR region[rsp] ;lower arg is **NOT** nan/inf lea rdx, QWORD PTR r[rsp] ; added ins- changed input from xmm10 to xmm0 ; movsd xmm0, xmm10 movd rcx, xmm10 ;change to MS ABI - shadow space sub rsp,020h call fname_remainder_piby2d2f ;change to MS ABI - shadow space add rsp,020h mov r8, QWORD PTR p_temp2[rsp] mov r9, QWORD PTR p_temp4[rsp] movapd xmm1, OWORD PTR p_temp1[rsp] movapd xmm3, OWORD PTR p_temp3[rsp] movapd xmm7, OWORD PTR p_temp5[rsp] mov rcx, QWORD PTR p_temp[rsp] ;Restore upper arg jmp @F __vrs4_sinf_lower_naninf_of_both_gt_5e5: ;lower arg is nan/inf ; mov rax, QWORD PTR p_original[rsp] mov r11,00008000000000000h or rax,r11 mov QWORD PTR r[rsp],rax ;r = x | 0x0008000000000000 ; xor r10, r10 ; mov QWORD PTR rr[rsp], r10 ;rr = 0 mov DWORD PTR region[rsp], r10d ;region = 0 align 16 @@: mov r11,07ff0000000000000h ;is upper arg nan/inf mov r10,r11 and r10,rcx cmp r10,r11 jz __vrs4_sinf_upper_naninf_of_both_gt_5e5 mov QWORD PTR p_temp2[rsp], r8 mov QWORD PTR p_temp4[rsp], r9 movapd OWORD PTR p_temp1[rsp], xmm1 movapd OWORD PTR p_temp3[rsp], xmm3 movapd OWORD PTR p_temp5[rsp], xmm7 ; lea r9, QWORD PTR region[rsp+4] ;upper arg is **NOT** nan/inf ; lea r8, QWORD PTR rr[rsp+8] lea r8, QWORD PTR region[rsp+4] ;upper arg is **NOT** nan/inf lea rdx, QWORD PTR r[rsp+8] ; changed input from xmm10 to xmm0 ; movapd xmm10, xmm6 ;Restore upper fp arg for remainder_piby2 call ; movsd xmm0, xmm6 ;Restore upper fp arg for remainder_piby2 call movd rcx, xmm6 ;change to MS ABI - shadow space sub rsp,020h call fname_remainder_piby2d2f ;change to MS ABI - shadow space add rsp,020h mov r8, QWORD PTR p_temp2[rsp] mov r9, QWORD PTR p_temp4[rsp] movapd xmm1, OWORD PTR p_temp1[rsp] movapd xmm3, OWORD PTR p_temp3[rsp] movapd xmm7,OWORD PTR p_temp5[rsp] jmp @F __vrs4_sinf_upper_naninf_of_both_gt_5e5: ; mov rcx, QWORD PTR p_original[rsp+8] ;upper arg is nan/inf ; movd rcx, xmm6 ;upper arg is nan/inf mov r11,00008000000000000h or rcx,r11 mov QWORD PTR r[rsp+8],rcx ;r = x | 0x0008000000000000 ; xor r10, r10 ; mov QWORD PTR rr[rsp+8], r10 ;rr = 0 mov DWORD PTR region[rsp+4], r10d ;region = 0 align 16 @@: jmp check_next2_args ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 second_or_next2_arg_gt_5e5: ; Upper Arg is >= 5e5, Lower arg is < 5e5 ; rax, rcx, r8, r9 ; xmm10, xmm2, xmm6 = x, xmm4 = 0.5 ; Do not use xmm1, xmm3, xmm7 ; Restore xmm4 and xmm1, xmm3, xmm7 ; Can use xmm8, xmm0, xmm12 ; xmm5, xmm9, xmm11, xmm13 movhpd QWORD PTR r[rsp+8], xmm10 ;Save upper fp arg for remainder_piby2 call ; movlhps xmm10, xmm10 ;Not needed since we want to work on lower arg, but done just to be safe and avoide exceptions due to nan/inf and to mirror the lower_arg_gt_5e5 case ; movlhps xmm2, xmm2 ; movlhps xmm6, xmm6 ; Work on Lower arg ; Upper arg might contain nan/inf, to avoid exception use only scalar instructions on lower arg mulsd xmm2,QWORD PTR __real_3fe45f306dc9c883 ; x*twobypi addsd xmm2,xmm4 ; xmm2 = npi2=(x*twobypi+0.5) movsd xmm8,QWORD PTR __real_3ff921fb54400000 ; xmm3 = piby2_1 cvttsd2si eax,xmm2 ; ecx = npi2 trunc to ints movsd xmm0,QWORD PTR __real_3dd0b4611a600000 ; xmm1 = piby2_2 cvtsi2sd xmm2,eax ; xmm2 = npi2 trunc to doubles ;/* Subtract the multiple from x to get an extra-precision remainder */ ;rhead = x - npi2 * piby2_1; mulsd xmm8,xmm2 ; npi2 * piby2_1 subsd xmm6,xmm8 ; xmm6 = rhead =(x-npi2*piby2_1) movsd xmm12,QWORD PTR __real_3ba3198a2e037073 ; xmm7 =piby2_2tail ;t = rhead; movsd xmm5, xmm6 ; xmm5 = t = rhead ;rtail = npi2 * piby2_2; mulsd xmm0,xmm2 ; xmm1 =rtail=(npi2*piby2_2) ;rhead = t - rtail subsd xmm6, xmm0 ; xmm6 =rhead=(t-rtail) ;rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulsd xmm12,xmm2 ; npi2 * piby2_2tail subsd xmm5,xmm6 ; t-rhead subsd xmm0,xmm5 ; (rtail-(t-rhead)) addsd xmm0,xmm12 ; rtail=npi2*piby2_2tail+(rtail-(t-rhead)); ;r = rhead - rtail ;rr = (rhead-r) -rtail mov DWORD PTR region[rsp], eax ; store upper region ; movsd xmm10,xmm6 ; subsd xmm10,xmm0 ; xmm10 = r=(rhead-rtail) ; subsd xmm6, xmm10 ; rr=rhead-r ; subsd xmm6, xmm0 ; xmm6 = rr=((rhead-r) -rtail) subsd xmm6,xmm0 ; xmm10 = r=(rhead-rtail) ; movlpd QWORD PTR r[rsp], xmm10 ; store upper r ; movlpd QWORD PTR rr[rsp], xmm6 ; store upper rr movlpd QWORD PTR r[rsp], xmm6 ; store upper r ;Work on Upper arg ;Note that volatiles will be trashed by the call ;We do not care since this is the last check ;We will construct r, rr, region and sign mov r11,07ff0000000000000h ; is upper arg nan/inf mov r10,r11 and r10,rcx cmp r10,r11 jz __vrs4_sinf_upper_naninf mov QWORD PTR p_temp[rsp], r8 mov QWORD PTR p_temp2[rsp], r9 movapd OWORD PTR p_temp1[rsp], xmm1 movapd OWORD PTR p_temp3[rsp], xmm3 movapd OWORD PTR p_temp5[rsp], xmm7 ; lea r9, QWORD PTR region[rsp+4] ; upper arg is **NOT** nan/inf ; lea r8, QWORD PTR rr[rsp+8] lea r8, QWORD PTR region[rsp+4] ; upper arg is **NOT** nan/inf lea rdx, QWORD PTR r[rsp+8] ; changed input from xmm10 to xmm0 ; movlpd xmm10, QWORD PTR r[rsp+8] ;Restore upper fp arg for remainder_piby2 call ; movlpd xmm0, QWORD PTR r[rsp+8] ;Restore upper fp arg for remainder_piby2 call mov rcx, QWORD PTR r[rsp+8] ;change to MS ABI - shadow space sub rsp,020h call fname_remainder_piby2d2f ;change to MS ABI - shadow space add rsp,020h mov r8, QWORD PTR p_temp[rsp] mov r9, QWORD PTR p_temp2[rsp] movapd xmm1, OWORD PTR p_temp1[rsp] movapd xmm3, OWORD PTR p_temp3[rsp] movapd xmm7, OWORD PTR p_temp5[rsp] jmp @F __vrs4_sinf_upper_naninf: ; mov rcx, QWORD PTR p_original[rsp+8] ; upper arg is nan/inf ; mov rcx, QWORD PTR r[rsp+8] ; upper arg is nan/inf mov r11,00008000000000000h or rcx,r11 mov QWORD PTR r[rsp+8],rcx ; r = x | 0x0008000000000000 ; xor r10, r10 ; mov QWORD PTR rr[rsp+8], r10 ; rr = 0 mov DWORD PTR region[rsp+4], r10d ; region =0 align 16 @@: jmp check_next2_args ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 check_next2_args: ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movapd xmm5, xmm1 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG mov r10, 411E848000000000h ;5e5 + cmp r8, r10 jae first_second_done_third_or_fourth_arg_gt_5e5 cmp r9, r10 jae first_second_done_fourth_arg_gt_5e5 ; Work on next two args, both < 5e5 ; xmm1, xmm3, xmm5 = x, xmm4 = 0.5 movapd xmm4, OWORD PTR __real_3fe0000000000000 ;Restore 0.5 mulpd xmm3, XMMWORD PTR __real_3fe45f306dc9c883 ; * twobypi addpd xmm3,xmm4 ; +0.5, npi2 movapd xmm1,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 cvttpd2dq xmm5,xmm3 ; convert packed double to packed integers movapd xmm9,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 cvtdq2pd xmm3,xmm5 ; and back to double. ; /* Subtract the multiple from x to get an extra-precision remainder */ movd QWORD PTR region1[rsp], xmm5 ; Region ; rhead = x - npi2 * piby2_1; mulpd xmm1,xmm3 ; npi2 * piby2_1; ; rtail = npi2 * piby2_2; mulpd xmm9,xmm3 ; rtail ; rhead = x - npi2 * piby2_1; subpd xmm7,xmm1 ; rhead = x - npi2 * piby2_1; ; t = rhead; movapd xmm1, xmm7 ; t ; rhead = t - rtail; subpd xmm1, xmm9 ; rhead ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulpd xmm3,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail subpd xmm7,xmm1 ; t-rhead subpd xmm9,xmm7 ; - ((t - rhead) - rtail) addpd xmm9,xmm3 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); ; movapd xmm7,xmm1 ; rhead subpd xmm1,xmm9 ; r = rhead - rtail movapd OWORD PTR r1[rsp], xmm1 ; subpd xmm7, xmm1 ; rr=rhead-r ; subpd xmm7, xmm9 ; rr=(rhead-r) -rtail ; movapd OWORD PTR rr1[rsp], xmm7 jmp __vrs4_sinf_reconstruct ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 third_or_fourth_arg_gt_5e5: ;first two args are < 5e5, third arg >= 5e5, fourth arg >= 5e5 or < 5e5 ; rax, rcx, r8, r9 ; xmm10, xmm2, xmm6 = x, xmm4 = 0.5 ; Do not use xmm1, xmm3, xmm7 ; Can use xmm9, xmm11, xmm13 ; xmm5, xmm8, xmm0, xmm12 ; Restore xmm4 ; Work on first two args, both < 5e5 mulpd xmm2, XMMWORD PTR __real_3fe45f306dc9c883 ; * twobypi addpd xmm2,xmm4 ; +0.5, npi2 movapd xmm10,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 cvttpd2dq xmm4,xmm2 ; convert packed double to packed integers movapd xmm8,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 cvtdq2pd xmm2,xmm4 ; and back to double. ; /* Subtract the multiple from x to get an extra-precision remainder */ movd QWORD PTR region[rsp], xmm4 ; Region ; rhead = x - npi2 * piby2_1; mulpd xmm10,xmm2 ; npi2 * piby2_1; ; rtail = npi2 * piby2_2; mulpd xmm8,xmm2 ; rtail ; rhead = x - npi2 * piby2_1; subpd xmm6,xmm10 ; rhead = x - npi2 * piby2_1; ; t = rhead; movapd xmm10, xmm6 ; t ; rhead = t - rtail; subpd xmm10, xmm8 ; rhead ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulpd xmm2,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail subpd xmm6,xmm10 ; t-rhead subpd xmm8,xmm6 ; - ((t - rhead) - rtail) addpd xmm8,xmm2 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); ; movapd xmm6,xmm10 ; rhead subpd xmm10,xmm8 ; r = rhead - rtail movapd OWORD PTR r[rsp], xmm10 ; subpd xmm6, xmm10 ; rr=rhead-r ; subpd xmm6, xmm8 ; rr=(rhead-r) -rtail ; movapd OWORD PTR rr[rsp], xmm6 ; Work on next two args, third arg >= 5e5, fourth arg >= 5e5 or < 5e5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; first_second_done_third_or_fourth_arg_gt_5e5: ; rax, rcx, r8, r9 ; xmm10, xmm2, xmm6 = x, xmm4 = 0.5 ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movapd xmm5, xmm1 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG mov r10, 411E848000000000h ;5e5 + cmp r9, r10 jae both_arg_gt_5e5_higher ; Upper Arg is <5e5, Lower arg is >= 5e5 ; r8, r9 ; xmm1, xmm3, xmm7 = x, xmm4 = 0.5 movlpd QWORD PTR r1[rsp], xmm1 ;Save lower fp arg for remainder_piby2 call movhlps xmm1, xmm1 ;Needed since we want to work on upper arg movhlps xmm3, xmm3 movhlps xmm7, xmm7 ; Work on Upper arg ; Lower arg might contain nan/inf, to avoid exception use only scalar instructions on upper arg which has been moved to lower portions of fp regs movapd xmm4, OWORD PTR __real_3fe0000000000000 ; Restore 0.5 mulsd xmm3,QWORD PTR __real_3fe45f306dc9c883 ; x*twobypi addsd xmm3,xmm4 ; xmm3 = npi2=(x*twobypi+0.5) movsd xmm2,QWORD PTR __real_3ff921fb54400000 ; xmm2 = piby2_1 cvttsd2si r9d,xmm3 ; r9d = npi2 trunc to ints movsd xmm10,QWORD PTR __real_3dd0b4611a600000 ; xmm10 = piby2_2 cvtsi2sd xmm3,r9d ; xmm3 = npi2 trunc to doubles ;/* Subtract the multiple from x to get an extra-precision remainder */ ;rhead = x - npi2 * piby2_1; mulsd xmm2,xmm3 ; npi2 * piby2_1 subsd xmm7,xmm2 ; xmm7 = rhead =(x-npi2*piby2_1) movsd xmm6,QWORD PTR __real_3ba3198a2e037073 ; xmm6 =piby2_2tail ;t = rhead; movsd xmm5, xmm7 ; xmm5 = t = rhead ;rtail = npi2 * piby2_2; mulsd xmm10,xmm3 ; xmm10 =rtail=(npi2*piby2_2) ;rhead = t - rtail subsd xmm7, xmm10 ; xmm7 =rhead=(t-rtail) ;rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulsd xmm6,xmm3 ; npi2 * piby2_2tail subsd xmm5,xmm7 ; t-rhead subsd xmm10,xmm5 ; (rtail-(t-rhead)) addsd xmm10,xmm6 ; rtail=npi2*piby2_2tail+(rtail-(t-rhead)); ;r = rhead - rtail ;rr = (rhead-r) -rtail mov DWORD PTR region1[rsp+4], r9d ; store upper region ; movsd xmm1,xmm7 ; subsd xmm1,xmm10 ; xmm1 = r=(rhead-rtail) ; subsd xmm7, xmm1 ; rr=rhead-r ; subsd xmm7, xmm10 ; xmm7 = rr=((rhead-r) -rtail) subsd xmm7,xmm10 ; xmm1 = r=(rhead-rtail) ; movlpd QWORD PTR r1[rsp+8], xmm1 ; store upper r ; movlpd QWORD PTR rr1[rsp+8], xmm7 ; store upper rr movlpd QWORD PTR r1[rsp+8], xmm7 ; store upper r ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Note that volatiles will be trashed by the call ;We do not care since this is the last check ;We will construct r, rr, region and sign ; Work on Lower arg mov r11,07ff0000000000000h ; is lower arg nan/inf mov r10,r11 and r10,r8 cmp r10,r11 jz __vrs4_sinf_lower_naninf_higher ; lea r9, QWORD PTR region1[rsp] ; lower arg is **NOT** nan/inf ; lea r8, QWORD PTR rr1[rsp] lea r8, QWORD PTR region1[rsp] ; lower arg is **NOT** nan/inf lea rdx, QWORD PTR r1[rsp] ; changed input from xmm10 to xmm0 ; movlpd xmm10, QWORD PTR r1[rsp] ;Restore lower fp arg for remainder_piby2 call ; movlpd xmm0, QWORD PTR r1[rsp] ;Restore lower fp arg for remainder_piby2 call mov rcx, QWORD PTR r1[rsp] ;change to MS ABI - shadow space sub rsp,020h call fname_remainder_piby2d2f ;change to MS ABI - shadow space add rsp,020h jmp @F __vrs4_sinf_lower_naninf_higher: ; mov r8, QWORD PTR p_original1[rsp] ; upper arg is nan/inf mov r11,00008000000000000h or r8,r11 mov QWORD PTR r1[rsp],r8 ; r = x | 0x0008000000000000 ; xor r10, r10 ; mov QWORD PTR rr1[rsp], r10 ; rr = 0 mov DWORD PTR region1[rsp], r10d ; region =0 align 16 @@: jmp __vrs4_sinf_reconstruct align 16 both_arg_gt_5e5_higher: ; Upper Arg is >= 5e5, Lower arg is >= 5e5 ; r8, r9 ; xmm1, xmm3, xmm7 = x, xmm4 = 0.5 ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movd xmm5, r8 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG movhlps xmm7, xmm1 ;Save upper fp arg for remainder_piby2 call mov r11,07ff0000000000000h ;is lower arg nan/inf mov r10,r11 and r10,r8 cmp r10,r11 jz __vrs4_sinf_lower_naninf_of_both_gt_5e5_higher mov QWORD PTR p_temp1[rsp], r9 ;Save upper arg ; lea r9, QWORD PTR region1[rsp] ;lower arg is **NOT** nan/inf ; lea r8, QWORD PTR rr1[rsp] lea r8, QWORD PTR region1[rsp] ;lower arg is **NOT** nan/inf lea rdx, QWORD PTR r1[rsp] ; changed input from xmm10 to xmm0 ; movapd xmm10, xmm1 ; movsd xmm0, xmm1 movd rcx, xmm1 ;change to MS ABI - shadow space sub rsp,020h call fname_remainder_piby2d2f ;change to MS ABI - shadow space add rsp,020h mov r9, QWORD PTR p_temp1[rsp] ;Restore upper arg ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; mov QWORD PTR r1[rsp+8], r9 ; movapd xmm5, OWORD PTR r1[rsp] ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG jmp @F __vrs4_sinf_lower_naninf_of_both_gt_5e5_higher: ;lower arg is nan/inf ; mov r8, QWORD PTR p_original1[rsp] mov r11,00008000000000000h or r8,r11 mov QWORD PTR r1[rsp],r8 ;r = x | 0x0008000000000000 ; xor r10, r10 ; mov QWORD PTR rr1[rsp], r10 ;rr = 0 mov DWORD PTR region1[rsp], r10d ;region = 0 align 16 @@: mov r11,07ff0000000000000h ;is upper arg nan/inf mov r10,r11 and r10,r9 cmp r10,r11 jz __vrs4_sinf_upper_naninf_of_both_gt_5e5_higher ; lea r9, QWORD PTR region1[rsp+4] ;upper arg is **NOT** nan/inf ; lea r8, QWORD PTR rr1[rsp+8] lea r8, QWORD PTR region1[rsp+4] ;upper arg is **NOT** nan/inf lea rdx, QWORD PTR r1[rsp+8] ; changed input from xmm10 to xmm0 ; movapd xmm10, xmm7 ;Restore upper fp arg for remainder_piby2 call ; movsd xmm0, xmm7 ;Restore upper fp arg for remainder_piby2 call movd rcx, xmm7 ;change to MS ABI - shadow space sub rsp,020h call fname_remainder_piby2d2f ;change to MS ABI - shadow space add rsp,020h jmp @F __vrs4_sinf_upper_naninf_of_both_gt_5e5_higher: ; mov r9, QWORD PTR p_original1[rsp+8] ;upper arg is nan/inf ; movd r9, xmm6 ;upper arg is nan/inf mov r11,00008000000000000h or r9,r11 mov QWORD PTR r1[rsp+8],r9 ;r = x | 0x0008000000000000 ; xor r10, r10 ; mov QWORD PTR rr1[rsp+8], r10 ;rr = 0 mov DWORD PTR region1[rsp+4], r10d ;region = 0 align 16 @@: ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movapd xmm5, OWORD PTR r1[rsp] ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG jmp __vrs4_sinf_reconstruct ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 fourth_arg_gt_5e5: ;first two args are < 5e5, third arg < 5e5, fourth arg >= 5e5 ;rax, rcx, r8, r9 ;xmm10, xmm2, xmm6 = x, xmm4 = 0.5 ; Work on first two args, both < 5e5 mulpd xmm2, XMMWORD PTR __real_3fe45f306dc9c883 ; * twobypi addpd xmm2,xmm4 ; +0.5, npi2 movapd xmm10,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 cvttpd2dq xmm4,xmm2 ; convert packed double to packed integers movapd xmm8,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 cvtdq2pd xmm2,xmm4 ; and back to double. ; /* Subtract the multiple from x to get an extra-precision remainder */ movd QWORD PTR region[rsp], xmm4 ; Region ; rhead = x - npi2 * piby2_1; mulpd xmm10,xmm2 ; npi2 * piby2_1; ; rtail = npi2 * piby2_2; mulpd xmm8,xmm2 ; rtail ; rhead = x - npi2 * piby2_1; subpd xmm6,xmm10 ; rhead = x - npi2 * piby2_1; ; t = rhead; movapd xmm10, xmm6 ; t ; rhead = t - rtail; subpd xmm10, xmm8 ; rhead ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulpd xmm2,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail subpd xmm6,xmm10 ; t-rhead subpd xmm8,xmm6 ; - ((t - rhead) - rtail) addpd xmm8,xmm2 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); ; movapd xmm6,xmm10 ; rhead subpd xmm10,xmm8 ; r = rhead - rtail movapd OWORD PTR r[rsp], xmm10 ; subpd xmm6, xmm10 ; rr=rhead-r ; subpd xmm6, xmm8 ; rr=(rhead-r) -rtail ; movapd OWORD PTR rr[rsp], xmm6 ; Work on next two args, third arg < 5e5, fourth arg >= 5e5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; first_second_done_fourth_arg_gt_5e5: ; Upper Arg is >= 5e5, Lower arg is < 5e5 ; r8, r9 ; xmm1, xmm3, xmm7 = x, xmm4 = 0.5 movhpd QWORD PTR r1[rsp+8], xmm1 ;Save upper fp arg for remainder_piby2 call ; movlhps xmm1, xmm1 ;Not needed since we want to work on lower arg, but done just to be safe and avoide exceptions due to nan/inf and to mirror the lower_arg_gt_5e5 case ; movlhps xmm3, xmm3 ; movlhps xmm7, xmm7 ; Work on Lower arg ; Upper arg might contain nan/inf, to avoid exception use only scalar instructions on lower arg movapd xmm4, OWORD PTR __real_3fe0000000000000 ; Restore 0.5 mulsd xmm3,QWORD PTR __real_3fe45f306dc9c883 ; x*twobypi addsd xmm3,xmm4 ; xmm3 = npi2=(x*twobypi+0.5) movsd xmm2,QWORD PTR __real_3ff921fb54400000 ; xmm2 = piby2_1 cvttsd2si r8d,xmm3 ; r8d = npi2 trunc to ints movsd xmm10,QWORD PTR __real_3dd0b4611a600000 ; xmm10 = piby2_2 cvtsi2sd xmm3,r8d ; xmm3 = npi2 trunc to doubles ;/* Subtract the multiple from x to get an extra-precision remainder */ ;rhead = x - npi2 * piby2_1; mulsd xmm2,xmm3 ; npi2 * piby2_1 subsd xmm7,xmm2 ; xmm7 = rhead =(x-npi2*piby2_1) movsd xmm6,QWORD PTR __real_3ba3198a2e037073 ; xmm6 =piby2_2tail ;t = rhead; movsd xmm5, xmm7 ; xmm5 = t = rhead ;rtail = npi2 * piby2_2; mulsd xmm10,xmm3 ; xmm10 =rtail=(npi2*piby2_2) ;rhead = t - rtail subsd xmm7, xmm10 ; xmm7 =rhead=(t-rtail) ;rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulsd xmm6,xmm3 ; npi2 * piby2_2tail subsd xmm5,xmm7 ; t-rhead subsd xmm10,xmm5 ; (rtail-(t-rhead)) addsd xmm10,xmm6 ; rtail=npi2*piby2_2tail+(rtail-(t-rhead)); ;r = rhead - rtail ;rr = (rhead-r) -rtail mov DWORD PTR region1[rsp], r8d ; store lower region ; movsd xmm1, xmm7 ; subsd xmm1, xmm10 ; xmm10 = r=(rhead-rtail) ; subsd xmm7, xmm1 ; rr=rhead-r ; subsd xmm7, xmm10 ; xmm6 = rr=((rhead-r) -rtail) subsd xmm7, xmm10 ; xmm10 = r=(rhead-rtail) ; movlpd QWORD PTR r1[rsp], xmm1 ; store upper r ; movlpd QWORD PTR rr1[rsp], xmm7 ; store upper rr movlpd QWORD PTR r1[rsp], xmm7 ; store upper r ;Work on Upper arg ;Note that volatiles will be trashed by the call ;We do not care since this is the last check ;We will construct r, rr, region and sign mov r11,07ff0000000000000h ; is upper arg nan/inf mov r10,r11 and r10,r9 cmp r10,r11 jz __vrs4_sinf_upper_naninf_higher ; lea r9, QWORD PTR region1[rsp+4] ; upper arg is **NOT** nan/inf ; lea r8, QWORD PTR rr1[rsp+8] lea r8, QWORD PTR region1[rsp+4] ; upper arg is **NOT** nan/inf lea rdx, QWORD PTR r1[rsp+8] ; changed input from xmm10 to xmm0 ; movlpd xmm10, QWORD PTR r1[rsp+8] ;Restore upper fp arg for remainder_piby2 call ; movlpd xmm0, QWORD PTR r1[rsp+8] ;Restore upper fp arg for remainder_piby2 call mov rcx, QWORD PTR r1[rsp+8] ;change to MS ABI - shadow space sub rsp,020h call fname_remainder_piby2d2f ;change to MS ABI - shadow space add rsp,020h jmp @F __vrs4_sinf_upper_naninf_higher: ; mov r9, QWORD PTR p_original1[rsp+8] ; upper arg is nan/inf ; mov r9, QWORD PTR r1[rsp+8] ; upper arg is nan/inf mov r11,00008000000000000h or r9,r11 mov QWORD PTR r1[rsp+8],r9 ; r = x | 0x0008000000000000 ; xor r10, r10 ; mov QWORD PTR rr1[rsp+8], r10 ; rr = 0 mov DWORD PTR region1[rsp+4], r10d ; region =0 align 16 @@: jmp __vrs4_sinf_reconstruct ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 __vrs4_sinf_reconstruct: ;Results ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm10 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;DEBUG ; movapd xmm4, OWORD PTR region[rsp] ; movapd xmm5, OWORD PTR region1[rsp] ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG movapd xmm10, OWORD PTR r[rsp] movapd xmm1, OWORD PTR r1[rsp] ; movapd xmm6, OWORD PTR rr[rsp] ; movapd xmm7, OWORD PTR rr1[rsp] ;DEBUG ; movapd xmm4, OWORD PTR region[rsp] ; movapd xmm5, OWORD PTR region1[rsp] ; movd xmm4, r12 ; movd xmm5, r13 ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG mov r8, QWORD PTR region[rsp] mov r9, QWORD PTR region1[rsp] mov rdx, QWORD PTR __reald_one_zero ;compare value for cossin path mov r10, r8 mov r11, r9 and r8, QWORD PTR __reald_one_one ;odd/even region for cos/sin and r9, QWORD PTR __reald_one_one ;odd/even region for cos/sin shr r10, 1 ;~AB+A~B, A is sign and B is upper bit of region shr r11, 1 ;~AB+A~B, A is sign and B is upper bit of region mov rax, r10 mov rcx, r11 not r12 ;ADDED TO CHANGE THE LOGIC not r13 ;ADDED TO CHANGE THE LOGIC and r10, r12 and r11, r13 not rax not rcx not r12 not r13 and rax, r12 and rcx, r13 or r10, rax or r11, rcx and r10, __reald_one_one ;(~AB+A~B)&1 and r11, __reald_one_one ;(~AB+A~B)&1 mov r12, r10 mov r13, r11 and r12, rdx ;mask out the lower sign bit leaving the upper sign bit and r13, rdx ;mask out the lower sign bit leaving the upper sign bit shl r10, 63 ;shift lower sign bit left by 63 bits shl r11, 63 ;shift lower sign bit left by 63 bits shl r12, 31 ;shift upper sign bit left by 31 bits shl r13, 31 ;shift upper sign bit left by 31 bits mov QWORD PTR p_sign[rsp],r10 ;write out lower sign bit mov QWORD PTR p_sign[rsp+8],r12 ;write out upper sign bit mov QWORD PTR p_sign1[rsp],r11 ;write out lower sign bit mov QWORD PTR p_sign1[rsp+8],r13 ;write out upper sign bit mov rax, r8 mov rcx, r9 movapd xmm2,xmm10 movapd xmm3,xmm1 mulpd xmm2,xmm10 ; r2 mulpd xmm3,xmm1 ; r2 and rax, QWORD PTR __reald_zero_one and rcx, QWORD PTR __reald_zero_one shr r8, 31 shr r9, 31 or rax, r8 or rcx, r9 shl rcx, 2 or rax, rcx ;DEBUG ; movapd xmm4, OWORD PTR p_sign[rsp] ; movapd xmm5, OWORD PTR p_sign1[rsp] ; xorpd xmm10, xmm10 ; xorpd xmm1, xmm1 ; jmp __vrs4_sinf_cleanup ;DEBUG lea rcx, QWORD PTR evensin_oddcos_tbl jmp QWORD PTR [rcx+rax*8] ;Jmp table for cos/sin calculation based on even/odd region ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 PUBLIC __vrs4_sinf_cleanup __vrs4_sinf_cleanup:: movapd xmm10, p_sign[rsp] movapd xmm1, p_sign1[rsp] xorpd xmm10, xmm4 ; (+) Sign xorpd xmm1, xmm5 ; (+) Sign ;DEBUG ; movapd xmm10, xmm4 ; movapd xmm1, xmm5 ;DEBUG cvtpd2ps xmm0, xmm10 cvtpd2ps xmm11, xmm1 movlhps xmm0, xmm11 movdqa xmm6, OWORD PTR [rsp+020h] ; restore xmm6 movdqa xmm7, OWORD PTR [rsp+030h] ; restore xmm7 movdqa xmm8, OWORD PTR [rsp+040h] ; restore xmm8 movdqa xmm9, OWORD PTR [rsp+050h] ; restore xmm9 movdqa xmm10,OWORD PTR [rsp+060h] ; restore xmm0 movdqa xmm11,OWORD PTR [rsp+070h] ; restore xmm11 movdqa xmm12,OWORD PTR [rsp+080h] ; restore xmm12 movdqa xmm13,OWORD PTR [rsp+090h] ; restore xmm13 mov r12,QWORD PTR [rsp+save_r12] ; restore r12 mov r13,QWORD PTR [rsp+save_r13] ; restore r13 add rsp,stack_size ret fname endp ;TEXT ENDS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;JUMP TABLE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm10 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 coscos_coscos_piby4: movapd xmm0, xmm2 ; r movapd xmm11, xmm3 ; r movdqa xmm4, OWORD PTR cosarray+30h ; c4 movdqa xmm5, OWORD PTR cosarray+30h ; c4 movapd xmm8, OWORD PTR cosarray+10h ; c2 movapd xmm9, OWORD PTR cosarray+10h ; c2 mulpd xmm0, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subpd xmm0, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 ;trash r subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 ;trash r mulpd xmm2, xmm2 ; x4 mulpd xmm3, xmm3 ; x4 addpd xmm4, OWORD PTR cosarray+20h ; c3+x2c4 addpd xmm5, OWORD PTR cosarray+20h ; c3+x2c4 addpd xmm8, OWORD PTR cosarray ; c1+x2c2 addpd xmm9, OWORD PTR cosarray ; c1+x2c2 mulpd xmm4, xmm2 ; x4(c3+x2c4) mulpd xmm5, xmm3 ; x4(c3+x2c4) addpd xmm4, xmm8 ; zc addpd xmm5, xmm9 ; zc mulpd xmm4, xmm2 ; x4 * zc mulpd xmm5, xmm3 ; x4 * zc subpd xmm4, xmm0 ; + t subpd xmm5, xmm11 ; + t jmp __vrs4_sinf_cleanup align 16 cossin_cossin_piby4: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm10 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; movdqa xmm4, OWORD PTR sincosarray+30h ; s4 movdqa xmm5, OWORD PTR sincosarray+30h ; s4 movapd xmm8, OWORD PTR sincosarray+10h ; s2 movapd xmm9, OWORD PTR sincosarray+10h ; s2 movapd xmm0, xmm2 ; move x2 for x4 movapd xmm11,xmm3 ; move x2 for x4 mulpd xmm4, xmm2 ; x2s4 mulpd xmm5, xmm3 ; x2s4 mulpd xmm8, xmm2 ; x2s2 mulpd xmm9, xmm3 ; x2s2 mulpd xmm0, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR sincosarray+20h ; s4+x2s3 addpd xmm5, OWORD PTR sincosarray+20h ; s4+x2s3 addpd xmm8, OWORD PTR sincosarray ; s2+x2s1 addpd xmm9, OWORD PTR sincosarray ; s2+x2s1 mulpd xmm4, xmm0 ; x4(s3+x2s4) mulpd xmm5, xmm11 ; x4(s3+x2s4) movhlps xmm0, xmm0 ; move high x4 for cos term movhlps xmm11, xmm11 ; move high x4 for cos term movsd xmm6, xmm2 ; move low x2 for x3 for sin term movsd xmm7, xmm3 ; move low x2 for x3 for sin term mulsd xmm6, xmm10 ; get low x3 for sin term mulsd xmm7, xmm1 ; get low x3 for sin term mulpd xmm2, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms mulpd xmm3, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms addpd xmm4, xmm8 ; z addpd xmm5, xmm9 ; z movhlps xmm12, xmm2 ; move high r for cos movhlps xmm13, xmm3 ; move high r for cos movhlps xmm8, xmm4 ; xmm4 = sin , xmm8 = cos movhlps xmm9, xmm5 ; xmm4 = sin , xmm8 = cos mulsd xmm4, xmm6 ; sin *x3 mulsd xmm5, xmm7 ; sin *x3 mulsd xmm8, xmm0 ; cos *x4 mulsd xmm9, xmm11 ; cos *x4 subsd xmm12, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm13, QWORD PTR __real_3ff0000000000000; -t=r-1.0 addsd xmm4, xmm10 ; sin + x addsd xmm5, xmm1 ; sin + x subsd xmm8, xmm12 ; cos+t subsd xmm9, xmm13 ; cos+t movlhps xmm4, xmm8 movlhps xmm5, xmm9 jmp __vrs4_sinf_cleanup align 16 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm10 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; sincos_cossin_piby4: movapd xmm4, OWORD PTR sincosarray+30h ; s4 movapd xmm5, OWORD PTR cossinarray+30h ; s4 movdqa xmm8, OWORD PTR sincosarray+10h ; s2 movdqa xmm9, OWORD PTR cossinarray+10h ; s2 movapd xmm0, xmm2 ; move x2 for x4 movapd xmm11, xmm3 ; move x2 for x4 movapd xmm7, xmm3 ; sincos term upper x2 for x3 mulpd xmm4, xmm2 ; x2s4 mulpd xmm5, xmm3 ; x2s4 mulpd xmm8, xmm2 ; x2s2 mulpd xmm9, xmm3 ; x2s2 mulpd xmm0, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR sincosarray+20h ; s3+x2s4 addpd xmm5, OWORD PTR cossinarray+20h ; s3+x2s4 addpd xmm8, OWORD PTR sincosarray ; s1+x2s2 addpd xmm9, OWORD PTR cossinarray ; s1+x2s2 mulpd xmm4, xmm0 ; x4(s3+x2s4) mulpd xmm5, xmm11 ; x4(s3+x2s4) movhlps xmm0, xmm0 ; move high x4 for cos term movsd xmm6, xmm2 ; move low x2 for x3 for sin term (cossin) mulpd xmm7, xmm1 mulsd xmm6, xmm10 ; get low x3 for sin term (cossin) movhlps xmm7, xmm7 ; get high x3 for sin term (sincos) mulpd xmm2, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for cos term mulpd xmm3, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for cos term addpd xmm4, xmm8 ; z addpd xmm5, xmm9 ; z movhlps xmm12, xmm2 ; move high r for cos (cossin) movhlps xmm8, xmm4 ; xmm8 = cos , xmm4 = sin (cossin) movhlps xmm9, xmm5 ; xmm9 = sin , xmm5 = cos (sincos) mulsd xmm4, xmm6 ; sin *x3 mulsd xmm5, xmm11 ; cos *x4 mulsd xmm8, xmm0 ; cos *x4 mulsd xmm9, xmm7 ; sin *x3 subsd xmm12, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm3, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 movhlps xmm11, xmm1 ; move high x for x for sin term (sincos) addsd xmm4, xmm10 ; sin + x + addsd xmm9, xmm11 ; sin + x + subsd xmm8, xmm12 ; cos+t subsd xmm5, xmm3 ; cos+t movlhps xmm4, xmm8 ; cossin movlhps xmm5, xmm9 ; sincos jmp __vrs4_sinf_cleanup align 16 sincos_sincos_piby4: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm10 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; movapd xmm4, OWORD PTR cossinarray+30h ; s4 movapd xmm5, OWORD PTR cossinarray+30h ; s4 movdqa xmm8, OWORD PTR cossinarray+10h ; s2 movdqa xmm9, OWORD PTR cossinarray+10h ; s2 movapd xmm0, xmm2 ; move x2 for x4 movapd xmm11, xmm3 ; move x2 for x4 movapd xmm6, xmm2 ; move x2 for x4 movapd xmm7, xmm3 ; move x2 for x4 mulpd xmm4, xmm2 ; x2s6 mulpd xmm5, xmm3 ; x2s6 mulpd xmm8, xmm2 ; x2s3 mulpd xmm9, xmm3 ; x2s3 mulpd xmm0, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR cossinarray+20h ; s4+x2s3 addpd xmm5, OWORD PTR cossinarray+20h ; s4+x2s3 addpd xmm8, OWORD PTR cossinarray ; s2+x2s1 addpd xmm9, OWORD PTR cossinarray ; s2+x2s1 mulpd xmm4, xmm0 ; x4(s4+x2s3) mulpd xmm5, xmm11 ; x4(s4+x2s3) mulpd xmm6, xmm10 ; get low x3 for sin term mulpd xmm7, xmm1 ; get low x3 for sin term movhlps xmm6, xmm6 ; move low x2 for x3 for sin term movhlps xmm7, xmm7 ; move low x2 for x3 for sin term mulsd xmm2, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for cos terms mulsd xmm3, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for cos terms addpd xmm4, xmm8 ; z addpd xmm5, xmm9 ; z movhlps xmm12, xmm4 ; xmm8 = sin , xmm4 = cos movhlps xmm13, xmm5 ; xmm9 = sin , xmm5 = cos mulsd xmm12, xmm6 ; sin *x3 mulsd xmm13, xmm7 ; sin *x3 mulsd xmm4, xmm0 ; cos *x4 mulsd xmm5, xmm11 ; cos *x4 subsd xmm2, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm3, QWORD PTR __real_3ff0000000000000; -t=r-1.0 movhlps xmm0, xmm10 ; move high x for x for sin term movhlps xmm11, xmm1 ; move high x for x for sin term ; Reverse 10 and 0 addsd xmm12, xmm0 ; sin + x addsd xmm13, xmm11 ; sin + x subsd xmm4, xmm2 ; cos+t subsd xmm5, xmm3 ; cos+t movlhps xmm4, xmm12 movlhps xmm5, xmm13 jmp __vrs4_sinf_cleanup align 16 cossin_sincos_piby4: movapd xmm4, OWORD PTR cossinarray+30h ; s4 movapd xmm5, OWORD PTR sincosarray+30h ; s4 movdqa xmm8, OWORD PTR cossinarray+10h ; s2 movdqa xmm9, OWORD PTR sincosarray+10h ; s2 movapd xmm0, xmm2 ; move x2 for x4 movapd xmm11, xmm3 ; move x2 for x4 movapd xmm7, xmm2 ; upper x2 for x3 for sin term (sincos) mulpd xmm4, xmm2 ; x2s4 mulpd xmm5, xmm3 ; x2s4 mulpd xmm8, xmm2 ; x2s2 mulpd xmm9, xmm3 ; x2s2 mulpd xmm0, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR cossinarray+20h ; s3+x2s4 addpd xmm5, OWORD PTR sincosarray+20h ; s3+x2s4 addpd xmm8, OWORD PTR cossinarray ; s1+x2s2 addpd xmm9, OWORD PTR sincosarray ; s1+x2s2 mulpd xmm4, xmm0 ; x4(s3+x2s4) mulpd xmm5, xmm11 ; x4(s3+x2s4) movhlps xmm11, xmm11 ; move high x4 for cos term movsd xmm6, xmm3 ; move low x2 for x3 for sin term (cossin) mulpd xmm7, xmm10 mulsd xmm6, xmm1 ; get low x3 for sin term (cossin) movhlps xmm7, xmm7 ; get high x3 for sin term (sincos) mulsd xmm2, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for cos term mulpd xmm3, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for cos term addpd xmm4, xmm8 ; z addpd xmm5, xmm9 ; z movhlps xmm12, xmm3 ; move high r for cos (cossin) movhlps xmm8, xmm4 ; xmm8 = sin , xmm4 = cos (sincos) movhlps xmm9, xmm5 ; xmm9 = cos , xmm5 = sin (cossin) mulsd xmm4, xmm0 ; cos *x4 mulsd xmm5, xmm6 ; sin *x3 mulsd xmm8, xmm7 ; sin *x3 mulsd xmm9, xmm11 ; cos *x4 subsd xmm2, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 subsd xmm12, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 movhlps xmm11, xmm10 ; move high x for x for sin term (sincos) subsd xmm4, xmm2 ; cos-(-t) subsd xmm9, xmm12 ; cos-(-t) addsd xmm8, xmm11 ; sin + x addsd xmm5, xmm1 ; sin + x movlhps xmm4, xmm8 ; cossin movlhps xmm5, xmm9 ; sincos jmp __vrs4_sinf_cleanup ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 coscos_sinsin_piby4: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm10 = r, xmm2 = r2, xmm6 =rr: SIN ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr: COS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; movapd xmm0, xmm2 ; x2 ; SIN movapd xmm11, xmm3 ; x2 ; COS movapd xmm1, xmm3 ; copy of x2 for x4 movdqa xmm4, OWORD PTR sinarray+30h ; c4 movdqa xmm5, OWORD PTR cosarray+30h ; c4 movapd xmm8, OWORD PTR sinarray+10h ; c2 movapd xmm9, OWORD PTR cosarray+10h ; c2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 mulpd xmm0, xmm2 ; x4 subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 mulpd xmm1, xmm3 ; x4 addpd xmm4, OWORD PTR sinarray+20h ; c3+x2c4 addpd xmm5, OWORD PTR cosarray+20h ; c3+x2c4 addpd xmm8, OWORD PTR sinarray ; c1+x2c2 addpd xmm9, OWORD PTR cosarray ; c1+x2c2 mulpd xmm2, xmm10 ; x3 mulpd xmm4, xmm0 ; x4(c3+x2c4) mulpd xmm5, xmm1 ; x4(c3+x2c4) addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zc mulpd xmm4, xmm2 ; x3 * zs mulpd xmm5, xmm1 ; x4 * zc addpd xmm4, xmm10 ; +x subpd xmm5, xmm11 ; +t jmp __vrs4_sinf_cleanup align 16 sinsin_coscos_piby4: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm10 = r, xmm2 = r2, xmm6 =rr: COS ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr: SIN ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; movapd xmm0, xmm2 ; x2 ; COS movapd xmm11, xmm3 ; x2 ; SIN movapd xmm10, xmm2 ; copy of x2 for x4 movdqa xmm4, OWORD PTR cosarray+30h ; c4 movdqa xmm5, OWORD PTR sinarray+30h ; s4 movapd xmm8, OWORD PTR cosarray+10h ; c2 movapd xmm9, OWORD PTR sinarray+10h ; s2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; s4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; s2*x2 mulpd xmm10, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR cosarray+20h ; c3+x2c4 addpd xmm5, OWORD PTR sinarray+20h ; s3+x2c4 addpd xmm8, OWORD PTR cosarray ; c1+x2c2 addpd xmm9, OWORD PTR sinarray ; s1+x2c2 mulpd xmm3, xmm1 ; x3 mulpd xmm0, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm10 ; x4(c3+x2c4) mulpd xmm5, xmm11 ; x4(s3+x2s4) subpd xmm0, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 addpd xmm4, xmm8 ; zc addpd xmm5, xmm9 ; zs mulpd xmm4, xmm10 ; x4 * zc mulpd xmm5, xmm3 ; x3 * zc subpd xmm4, xmm0 ; +t addpd xmm5, xmm1 ; +x jmp __vrs4_sinf_cleanup ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 coscos_cossin_piby4: ;Derive from cossin_coscos movhlps xmm0, xmm2 ; x2 for 0.5x2 for upper cos movsd xmm6, xmm2 ; lower x2 for x3 for lower sin movapd xmm11, xmm3 ; x2 for 0.5x2 movapd xmm12, xmm2 ; x2 for x4 movapd xmm13, xmm3 ; x2 for x4 movsd xmm7, QWORD PTR __real_3ff0000000000000 movdqa xmm4, OWORD PTR sincosarray+30h ; c4 movdqa xmm5, OWORD PTR cosarray+30h ; c4 movapd xmm8, OWORD PTR sincosarray+10h ; c2 movapd xmm9, OWORD PTR cosarray+10h ; c2 mulsd xmm0, QWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 subsd xmm7, xmm0 ; t=1.0-r for cos subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 addpd xmm4, OWORD PTR sincosarray+20h ; c4+x2c3 addpd xmm5, OWORD PTR cosarray+20h ; c4+x2c3 addpd xmm8, OWORD PTR sincosarray ; c2+x2c1 addpd xmm9, OWORD PTR cosarray ; c2+x2c1 movapd xmm2, xmm12 ; upper=x4 movsd xmm2, xmm6 ; lower=x2 mulsd xmm2, xmm10 ; lower=x2*x mulpd xmm4, xmm12 ; x4(c3+x2c4) mulpd xmm5, xmm13 ; x4(c3+x2c4) addpd xmm4, xmm8 ; zczs addpd xmm5, xmm9 ; zc mulpd xmm4, xmm2 ; upper= x4 * zc ; lower=x3 * zs mulpd xmm5, xmm13 ; x4 * zc movlhps xmm10, xmm7 ; addpd xmm4, xmm10 ; +x for lower sin, +t for upper cos subpd xmm5, xmm11 ; -(-t) jmp __vrs4_sinf_cleanup align 16 coscos_sincos_piby4: ;Derive from cossin_coscos movsd xmm0, xmm2 ; x2 for 0.5x2 for lower cos movapd xmm11, xmm3 ; x2 for 0.5x2 movapd xmm12, xmm2 ; x2 for x4 movapd xmm13, xmm3 ; x2 for x4 movsd xmm7, QWORD PTR __real_3ff0000000000000 movdqa xmm4, OWORD PTR cossinarray+30h ; cs4 movdqa xmm5, OWORD PTR cosarray+30h ; c4 movapd xmm8, OWORD PTR cossinarray+10h ; cs2 movapd xmm9, OWORD PTR cosarray+10h ; c2 mulsd xmm0, QWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 subsd xmm7, xmm0 ; t=1.0-r for cos subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 addpd xmm4, OWORD PTR cossinarray+20h ; c4+x2c3 addpd xmm5, OWORD PTR cosarray+20h ; c4+x2c3 addpd xmm8, OWORD PTR cossinarray ; c2+x2c1 addpd xmm9, OWORD PTR cosarray ; c2+x2c1 mulpd xmm2, xmm10 ; upper=x3 for sin mulsd xmm2, xmm10 ; lower=x4 for cos mulpd xmm4, xmm12 ; x4(c3+x2c4) mulpd xmm5, xmm13 ; x4(c3+x2c4) addpd xmm4, xmm8 ; zczs addpd xmm5, xmm9 ; zc mulpd xmm4, xmm2 ; lower= x4 * zc ; upper= x3 * zs mulpd xmm5, xmm13 ; x4 * zc movsd xmm10, xmm7 addpd xmm4, xmm10 ; +x for upper sin, +t for lower cos subpd xmm5, xmm11 ; -(-t) jmp __vrs4_sinf_cleanup align 16 cossin_coscos_piby4: movhlps xmm0, xmm3 ; x2 for 0.5x2 for upper cos movapd xmm11, xmm2 ; x2 for 0.5x2 movapd xmm12, xmm2 ; x2 for x4 movapd xmm13, xmm3 ; x2 for x4 movsd xmm6, xmm3 ; lower x2 for x3 for sin movsd xmm7, QWORD PTR __real_3ff0000000000000 movdqa xmm4, OWORD PTR cosarray+30h ; cs4 movdqa xmm5, OWORD PTR sincosarray+30h ; c4 movapd xmm8, OWORD PTR cosarray+10h ; cs2 movapd xmm9, OWORD PTR sincosarray+10h ; c2 mulsd xmm0, QWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 subsd xmm7, xmm0 ; t=1.0-r for cos subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 addpd xmm4, OWORD PTR cosarray+20h ; c4+x2c3 addpd xmm5, OWORD PTR sincosarray+20h ; c4+x2c3 addpd xmm8, OWORD PTR cosarray ; c2+x2c1 addpd xmm9, OWORD PTR sincosarray ; c2+x2c1 movapd xmm3, xmm13 ; upper=x4 movsd xmm3, xmm6 ; lower x2 mulsd xmm3, xmm1 ; lower x2*x mulpd xmm4, xmm12 ; x4(c3+x2c4) mulpd xmm5, xmm13 ; x4(c3+x2c4) addpd xmm4, xmm8 ; zczs addpd xmm5, xmm9 ; zc mulpd xmm4, xmm12 ; x4 * zc mulpd xmm5, xmm3 ; upper= x4 * zc ; lower=x3 * zs movlhps xmm1, xmm7 addpd xmm5, xmm1 ; +x for lower sin, +t for upper cos subpd xmm4, xmm11 ; -(-t) jmp __vrs4_sinf_cleanup align 16 cossin_sinsin_piby4: ; Derived from sincos_coscos movhlps xmm0, xmm3 ; x2 movapd xmm7, xmm3 movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 movsd xmm11, QWORD PTR __real_3ff0000000000000 movdqa xmm4, OWORD PTR sinarray+30h ; c4 movdqa xmm5, OWORD PTR sincosarray+30h ; c4 movapd xmm8, OWORD PTR sinarray+10h ; c2 movapd xmm9, OWORD PTR sincosarray+10h ; c2 mulsd xmm0, QWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 mulpd xmm12, xmm2 ; x4 subsd xmm11, xmm0 ; t=1.0-r for cos mulpd xmm13, xmm3 ; x4 addpd xmm4, OWORD PTR sinarray+20h ; c3+x2c4 addpd xmm5, OWORD PTR sincosarray+20h ; c3+x2c4 addpd xmm8, OWORD PTR sinarray ; c1+x2c2 addpd xmm9, OWORD PTR sincosarray ; c1+x2c2 mulpd xmm2, xmm10 ; x3 movapd xmm3, xmm13 ; upper x4 for cos movsd xmm3, xmm7 ; lower x2 for sin mulsd xmm3, xmm1 ; lower x3=x2*x for sin mulpd xmm4, xmm12 ; x4(c3+x2c4) mulpd xmm5, xmm13 ; x4(c3+x2c4) movlhps xmm1, xmm11 ; t for upper cos and x for lower sin addpd xmm4, xmm8 ; zczs addpd xmm5, xmm9 ; zs mulpd xmm4, xmm2 ; x3 * zs mulpd xmm5, xmm3 ; upper=x4 * zc ; lower=x3 * zs addpd xmm4, xmm10 ; +x addpd xmm5, xmm1 ; +t upper, +x lower jmp __vrs4_sinf_cleanup align 16 sincos_coscos_piby4: movsd xmm0, xmm3 ; x2 for 0.5x2 for lower cos movapd xmm11, xmm2 ; x2 for 0.5x2 movapd xmm12, xmm2 ; x2 for x4 movapd xmm13, xmm3 ; x2 for x4 movsd xmm7, QWORD PTR __real_3ff0000000000000 movdqa xmm4, OWORD PTR cosarray+30h ; cs4 movdqa xmm5, OWORD PTR cossinarray+30h ; c4 movapd xmm8, OWORD PTR cosarray+10h ; cs2 movapd xmm9, OWORD PTR cossinarray+10h ; c2 mulsd xmm0, QWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 subsd xmm7, xmm0 ; t=1.0-r for cos subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 addpd xmm4, OWORD PTR cosarray+20h ; c4+x2c3 addpd xmm5, OWORD PTR cossinarray+20h ; c4+x2c3 addpd xmm8, OWORD PTR cosarray ; c2+x2c1 addpd xmm9, OWORD PTR cossinarray ; c2+x2c1 mulpd xmm3, xmm1 ; upper=x3 for sin mulsd xmm3, xmm1 ; lower=x4 for cos mulpd xmm4, xmm12 ; x4(c3+x2c4) mulpd xmm5, xmm13 ; x4(c3+x2c4) addpd xmm4, xmm8 ; zczs addpd xmm5, xmm9 ; zc mulpd xmm4, xmm12 ; x4 * zc mulpd xmm5, xmm3 ; lower= x4 * zc ; upper= x3 * zs movsd xmm1, xmm7 subpd xmm4, xmm11 ; -(-t) addpd xmm5, xmm1 ; +x for upper sin, +t for lower cos jmp __vrs4_sinf_cleanup align 16 sincos_sinsin_piby4: ; Derived from sincos_coscos movsd xmm0, xmm3 ; x2 movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 movsd xmm11, QWORD PTR __real_3ff0000000000000 movdqa xmm4, OWORD PTR sinarray+30h ; c4 movdqa xmm5, OWORD PTR cossinarray+30h ; c4 movapd xmm8, OWORD PTR sinarray+10h ; c2 movapd xmm9, OWORD PTR cossinarray+10h ; c2 mulsd xmm0, QWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 mulpd xmm12, xmm2 ; x4 subsd xmm11, xmm0 ; t=1.0-r for cos mulpd xmm13, xmm3 ; x4 addpd xmm4, OWORD PTR sinarray+20h ; c3+x2c4 addpd xmm5, OWORD PTR cossinarray+20h ; c3+x2c4 addpd xmm8, OWORD PTR sinarray ; c1+x2c2 addpd xmm9, OWORD PTR cossinarray ; c1+x2c2 mulpd xmm2, xmm10 ; x3 mulpd xmm3, xmm1 ; upper x3 for sin mulsd xmm3, xmm1 ; lower x4 for cos movhlps xmm6, xmm1 mulpd xmm4, xmm12 ; x4(c3+x2c4) mulpd xmm5, xmm13 ; x4(c3+x2c4) movlhps xmm11, xmm6 ; upper =t ; lower =x addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zszc mulpd xmm4, xmm2 ; x3 * zs mulpd xmm5, xmm3 ; lower=x4 * zc ; upper=x3 * zs addpd xmm4, xmm10 ; +x addpd xmm5, xmm11 ; +t lower, +x upper jmp __vrs4_sinf_cleanup align 16 sinsin_cossin_piby4: ; Derived from sincos_coscos movhlps xmm0, xmm2 ; x2 movapd xmm7, xmm2 movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 movsd xmm11, QWORD PTR __real_3ff0000000000000 movdqa xmm4, OWORD PTR sincosarray+30h ; c4 movdqa xmm5, OWORD PTR sinarray+30h ; c4 movapd xmm8, OWORD PTR sincosarray+10h ; c2 movapd xmm9, OWORD PTR sinarray+10h ; c2 mulsd xmm0, QWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 mulpd xmm12, xmm2 ; x4 subsd xmm11, xmm0 ; t=1.0-r for cos mulpd xmm13, xmm3 ; x4 addpd xmm4, OWORD PTR sincosarray+20h ; c3+x2c4 addpd xmm5, OWORD PTR sinarray+20h ; c3+x2c4 addpd xmm8, OWORD PTR sincosarray ; c1+x2c2 addpd xmm9, OWORD PTR sinarray ; c1+x2c2 mulpd xmm3, xmm1 ; x3 movapd xmm2, xmm12 ; upper x4 for cos movsd xmm2, xmm7 ; lower x2 for sin mulsd xmm2, xmm10 ; lower x3=x2*x for sin mulpd xmm4, xmm12 ; x4(c3+x2c4) mulpd xmm5, xmm13 ; x4(c3+x2c4) movlhps xmm10, xmm11 ; t for upper cos and x for lower sin addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zszc mulpd xmm5, xmm3 ; x3 * zs mulpd xmm4, xmm2 ; upper=x4 * zc ; lower=x3 * zs addpd xmm5, xmm1 ; +x addpd xmm4, xmm10 ; +t upper, +x lower jmp __vrs4_sinf_cleanup align 16 sinsin_sincos_piby4: ; Derived from sincos_coscos movsd xmm0, xmm2 ; x2 movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 movsd xmm11, QWORD PTR __real_3ff0000000000000 movdqa xmm4, OWORD PTR cossinarray+30h ; c4 movdqa xmm5, OWORD PTR sinarray+30h ; c4 movapd xmm8, OWORD PTR cossinarray+10h ; c2 movapd xmm9, OWORD PTR sinarray+10h ; c2 mulsd xmm0, QWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 mulpd xmm12, xmm2 ; x4 subsd xmm11, xmm0 ; t=1.0-r for cos mulpd xmm13, xmm3 ; x4 addpd xmm4, OWORD PTR cossinarray+20h ; c3+x2c4 addpd xmm5, OWORD PTR sinarray+20h ; c3+x2c4 addpd xmm8, OWORD PTR cossinarray ; c1+x2c2 addpd xmm9, OWORD PTR sinarray ; c1+x2c2 mulpd xmm3, xmm1 ; x3 mulpd xmm2, xmm10 ; upper x3 for sin mulsd xmm2, xmm10 ; lower x4 for cos movhlps xmm6, xmm10 mulpd xmm4, xmm12 ; x4(c3+x2c4) mulpd xmm5, xmm13 ; x4(c3+x2c4) movlhps xmm11, xmm6 addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zszc mulpd xmm5, xmm3 ; x3 * zs mulpd xmm4, xmm2 ; lower=x4 * zc ; upper=x3 * zs addpd xmm5, xmm1 ; +x addpd xmm4, xmm11 ; +t lower, +x upper jmp __vrs4_sinf_cleanup align 16 sinsin_sinsin_piby4: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm10 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;x2 = x * x; ;(x + x * x2 * (c1 + x2 * (c2 + x2 * (c3 + x2 * c4)))); ;x + x3 * ((c1 + x2 *c2) + x4 * (c3 + x2 * c4)); movapd xmm0, xmm2 ; x2 movapd xmm11, xmm3 ; x2 movdqa xmm4, OWORD PTR sinarray+30h ; c4 movdqa xmm5, OWORD PTR sinarray+30h ; c4 mulpd xmm0, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 movapd xmm8, OWORD PTR sinarray+10h ; c2 movapd xmm9, OWORD PTR sinarray+10h ; c2 mulpd xmm4, xmm2 ; c4*x2 mulpd xmm5, xmm3 ; c4*x2 mulpd xmm8, xmm2 ; c2*x2 mulpd xmm9, xmm3 ; c2*x2 addpd xmm4, OWORD PTR sinarray+20h ; c3+x2c4 addpd xmm5, OWORD PTR sinarray+20h ; c3+x2c4 mulpd xmm2, xmm10 ; x3 mulpd xmm3, xmm1 ; x3 addpd xmm8, OWORD PTR sinarray ; c1+x2c2 addpd xmm9, OWORD PTR sinarray ; c1+x2c2 mulpd xmm4, xmm0 ; x4(c3+x2c4) mulpd xmm5, xmm11 ; x4(c3+x2c4) addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zs mulpd xmm4, xmm2 ; x3 * zs mulpd xmm5, xmm3 ; x3 * zs addpd xmm4, xmm10 ; +x addpd xmm5, xmm1 ; +x jmp __vrs4_sinf_cleanup END
; Startup fo SAM Coupe ; ; Stefano 26/3/2001 ; ; If an error occurs eg break we just drop back to BASIC ; ; $Id: sam_crt0.asm,v 1.20 2016-06-21 20:49:06 dom Exp $ ; MODULE sam_crt0 ; ; Initially include the zcc_opt.def file to find out lots of lovely ; information about what we should do.. ; defc crt0 = 1 INCLUDE "zcc_opt.def" ; No matter what set up we have, main is always, always external to ; this fileb EXTERN _main ; ; Some variables which are needed for both app and basic startup ; PUBLIC cleanup PUBLIC l_dcal PUBLIC SCREEN_BASE defc CLIB_ZX_CONIO32 = 0 defc CONSOLE_COLUMNS = 32 PUBLIC __CLIB_ZX_CONIO32 defc __CLIB_ZX_CONIO32 = CLIB_ZX_CONIO32 defc CONSOLE_ROWS = 24 IFNDEF CLIB_FGETC_CONS_DELAY defc CLIB_FGETC_CONS_DELAY = 150 ENDIF IFNDEF CLIB_KBHIT_DELAY defc CLIB_KBHIT_DELAY = 100 ENDIF defc CRT_KEY_DEL = 12 PUBLIC CLIB_SAM_IS_BASIC defc __CPU_CLOCK = 6000000 IFNDEF CLIB_DEFAULT_SCREEN_MODE defc CLIB_DEFAULT_SCREEN_MODE = 4 ENDIF INCLUDE "target/sam/def/sam.def" IF (!DEFINED_startup || (startup=1)) INCLUDE "target/sam/classic/basic.asm" ELIF (startup=2) INCLUDE "target/sam/classic/allram.asm" ELIF (startup=3) INCLUDE "target/sam/classic/highram.asm" ENDIF
; A016905: a(n) = (5*n + 4)^9. ; 262144,387420489,20661046784,322687697779,2641807540224,14507145975869,60716992766464,208728361158759,618121839509504,1628413597910449,3904305912313344,8662995818654939,18014398509481984,35452087835576229,66540410775079424,119851595982618319,208215748530929664,350356403707485209,572994802228616704,913517247483640899,1423311812421484544,2171893279442309389,3251948521156637184,4785448563124474679,6930988311686938624,9892530380752880769,13929745610903012864,19370159742424031659,26623333280885243904,36197319879620191349,48717667557975775744,64949246777441383839,85821209809770512384,112455406951957393129,146198606972431117824,188658891711079763219,241746618002717016064,307720364049353798109,389238302031137391104,489415464119070561799,611887395134623186944,760880711892098878289,941291116759119107584,1158769441178837331579,1419816323814495617024,1731886157602686265669,2103500970336180939264,2544374934440439784559,3065550233359913058304,3679545044430997752249,4400514431288011718144,5244424972726797792739,6229243989537570422784,7375144266114367290029,8704725199652968436224,10243251346462395388119,12018909372337102782464,14063084452067724991009,16410657202007740245504,19100322269161664762699,22174929740517389369344,25681850577311021127189,29673367320587092457984,34207091356800250268479,39346408075296537575424,45160951293313130130569,51727108368644890545664,59128557465344352417459,67456838483748746952704,76811959212763434593149,87303038309675604140544,99048986760825351881639,112179229525223253213184,126834469112674289266929,143167492898147491034624,161344026025018913493019,181543631801412552228864,203960661546169565063909,228805255893990661179904,256304399623019770243599,286703032122569104031744,320265215673826473056089,357275363772235220688384,398039531776795387285379,442886772228801716813824,492170557240509868475469,546270270412906695832064,605592770801153705930359,670574031506374810927104,741680855533270234714049,819412671614557937042944,904303412765472167650539,996923480394485762883584,1097881796860068547323829,1207827949427648702913024,1327454428646007218077919,1457498964228107529355264,1598746961587843218016809,1752034042251376124194304,1918248691429635491004499 mul $0,5 add $0,4 pow $0,9
#include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> // Simplification function #include <CGAL/Surface_mesh_simplification/edge_collapse.h> // Visitor base #include <CGAL/Surface_mesh_simplification/Edge_collapse_visitor_base.h> // Stop-condition policy #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_ratio_stop_predicate.h> #include <iostream> #include <fstream> typedef CGAL::Simple_cartesian<double> Kernel; typedef Kernel::Point_3 Point_3; typedef CGAL::Surface_mesh<Point_3> Surface_mesh; typedef boost::graph_traits<Surface_mesh>::halfedge_descriptor halfedge_descriptor; typedef boost::graph_traits<Surface_mesh>::vertex_descriptor vertex_descriptor; namespace SMS = CGAL::Surface_mesh_simplification; typedef SMS::Edge_profile<Surface_mesh> Profile; // The following is a Visitor that keeps track of the simplification process. // In this example the progress is printed real-time and a few statistics are // recorded (and printed in the end). // struct Stats { std::size_t collected = 0; std::size_t processed = 0; std::size_t collapsed = 0; std::size_t non_collapsable = 0; std::size_t cost_uncomputable = 0; std::size_t placement_uncomputable = 0; }; struct My_visitor : SMS::Edge_collapse_visitor_base<Surface_mesh> { My_visitor(Stats* s) : stats(s) {} // Called during the collecting phase for each edge collected. void OnCollected(const Profile&, const boost::optional<double>&) { ++(stats->collected); std::cerr << "\rEdges collected: " << stats->collected << std::flush; } // Called during the processing phase for each edge selected. // If cost is absent the edge won't be collapsed. void OnSelected(const Profile&, boost::optional<double> cost, std::size_t initial, std::size_t current) { ++(stats->processed); if(!cost) ++(stats->cost_uncomputable); if(current == initial) std::cerr << "\n" << std::flush; std::cerr << "\r" << current << std::flush; } // Called during the processing phase for each edge being collapsed. // If placement is absent the edge is left uncollapsed. void OnCollapsing(const Profile&, boost::optional<Point> placement) { if(!placement) ++(stats->placement_uncomputable); } // Called for each edge which failed the so called link-condition, // that is, which cannot be collapsed because doing so would // turn the surface mesh into a non-manifold. void OnNonCollapsable(const Profile&) { ++(stats->non_collapsable); } // Called after each edge has been collapsed void OnCollapsed(const Profile&, vertex_descriptor) { ++(stats->collapsed); } Stats* stats; }; int main(int argc, char** argv) { Surface_mesh surface_mesh; const char* filename = (argc > 1) ? argv[1] : "data/cube.off"; std::ifstream is(filename); if(!is || !(is >> surface_mesh)) { std::cerr << "Failed to read input mesh: " << filename << std::endl; return EXIT_FAILURE; } if(!CGAL::is_triangle_mesh(surface_mesh)) { std::cerr << "Input geometry is not triangulated." << std::endl; return EXIT_FAILURE; } // In this example, the simplification stops when the number of undirected edges // drops below xx% of the initial count const double ratio = (argc > 2) ? std::stod(argv[2]) : 0.1; SMS::Count_ratio_stop_predicate<Surface_mesh> stop(ratio); Stats stats; My_visitor vis(&stats); // The index maps are not explicitelty passed as in the previous // example because the surface mesh items have a proper id() field. // On the other hand, we pass here explicit cost and placement // function which differ from the default policies, ommited in // the previous example. int r = SMS::edge_collapse(surface_mesh, stop, CGAL::parameters::visitor(vis)); std::cout << "\nEdges collected: " << stats.collected << "\nEdges proccessed: " << stats.processed << "\nEdges collapsed: " << stats.collapsed << std::endl << "\nEdges not collapsed due to topological constraints: " << stats.non_collapsable << "\nEdge not collapsed due to cost computation constraints: " << stats.cost_uncomputable << "\nEdge not collapsed due to placement computation constraints: " << stats.placement_uncomputable << std::endl; std::cout << "\nFinished!\n" << r << " edges removed.\n" << surface_mesh.number_of_edges() << " final edges.\n"; CGAL::write_polygon_mesh((argc > 3) ? argv[3] : "out.off", surface_mesh, CGAL::parameters::stream_precision(17)); return EXIT_SUCCESS; }
page ,132 ;-----------------------------Module-Header-----------------------------; ; Module Name: LIBINIT.ASM ; ; library stub to do local init for a Dynamic linked library ; ; Created: 06-27-89 ; Author: Todd Laney [ToddLa] ; ; Exported Functions: none ; ; Public Functions: none ; ; Public Data: none ; ; General Description: ; ; Restrictions: ; ; This must be the first object file in the LINK line, this assures ; that the reserved parameter block is at the *base* of DGROUP ; ;-----------------------------------------------------------------------; ?PLM=1 ; PASCAL Calling convention is DEFAULT ?WIN=1 ; Windows calling convention .286p .xlist include cmacros.inc .list ifndef SEGNAME SEGNAME equ <_TEXT> endif createSeg %SEGNAME, CodeSeg, word, public, CODE ;-----------------------------------------------------------------------; ; external functions ; externFP LocalInit ; in KERNEL externFP LibMain ; C code to do DLL init ;-----------------------------------------------------------------------; ; ; Stuff needed to avoid the C runtime coming in, and init the windows ; reserved parameter block at the base of DGROUP ; %out link me first!! sBegin Data assumes DS,Data org 0 ; base of DATA segment! DD 0 ; So null pointers get 0 maxRsrvPtrs = 5 DW maxRsrvPtrs usedRsrvPtrs = 0 labelDP <PUBLIC,rsrvptrs> DefRsrvPtr MACRO name globalW name,0 usedRsrvPtrs = usedRsrvPtrs + 1 ENDM DefRsrvPtr pLocalHeap ; Local heap pointer DefRsrvPtr pAtomTable ; Atom table pointer DefRsrvPtr pStackTop ; top of stack DefRsrvPtr pStackMin ; minimum value of SP DefRsrvPtr pStackBot ; bottom of stack if maxRsrvPtrs-usedRsrvPtrs DW maxRsrvPtrs-usedRsrvPtrs DUP (0) endif public __acrtused __acrtused = 1 sEnd Data ;-----------------------------------------------------------------------; sBegin CodeSeg assumes cs,CodeSeg ;--------------------------Private-Routine-----------------------------; ; ; LibEntry - called when DLL is loaded ; ; Entry: ; CX = size of heap ; DI = module handle ; DS = automatic data segment ; ES:SI = address of command line (not used) ; ; Returns: ; AX = TRUE if success ; Error Returns: ; AX = FALSE if error (ie fail load process) ; Registers Preserved: ; SI,DI,DS,BP ; Registers Destroyed: ; AX,BX,CX,DX,ES,FLAGS ; Calls: ; None ; History: ; ; 06-27-89 -by- Todd Laney [ToddLa] ; Created. ;-----------------------------------------------------------------------; cProc LibEntry,<FAR,PUBLIC,NODATA>,<> cBegin ; ; Push frame for LibMain (hModule,cbHeap,lpszCmdLine) ; push di push cx push es push si ; ; Init the local heap (if one is declared in the .def file) ; jcxz no_heap cCall LocalInit,<0,0,cx> no_heap: cCall LibMain cEnd sEnd CodeSeg end LibEntry
/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <memory> #include <vector> #include <utility> #include <algorithm> #include <numeric> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "TreeComm.hpp" #include "TreeCommLevel.hpp" #include "MockComm.hpp" #include "MockTreeCommLevel.hpp" #include "geopm_test.hpp" #include "config.h" using geopm::TreeCommLevel; using geopm::TreeComm; using geopm::TreeCommImp; using testing::_; using testing::Return; using testing::DoAll; using testing::SetArgReferee; class TreeCommTest : public ::testing::Test { protected: void SetUp(); void root_setup(); void nonroot_setup(); std::shared_ptr<MockComm> m_mock_comm; std::vector<int> m_fan_out; std::vector<MockTreeCommLevel *> m_level_ptr; std::unique_ptr<TreeComm> m_tree_comm; int m_num_send_up = 3; int m_num_send_down = 2; }; void TreeCommTest::SetUp() { m_mock_comm = std::make_shared<MockComm>(); } void TreeCommTest::root_setup() { m_fan_out = {2, 3, 4, 5}; std::vector<std::unique_ptr<TreeCommLevel> > temp; for (size_t lvl = 0; lvl < m_fan_out.size(); ++lvl) { m_level_ptr.push_back(new MockTreeCommLevel); temp.emplace_back(m_level_ptr[lvl]); } EXPECT_CALL(*m_mock_comm, barrier()); EXPECT_CALL(*m_mock_comm, num_rank()).WillOnce(Return(120)); m_tree_comm.reset(new TreeCommImp(m_mock_comm, m_fan_out, m_fan_out.size(), m_num_send_down, m_num_send_up, std::move(temp))); } void TreeCommTest::nonroot_setup() { m_fan_out = {2, 3, 4, 5}; std::vector<std::unique_ptr<TreeCommLevel> > temp; for (size_t lvl = 0; lvl < m_fan_out.size(); ++lvl) { m_level_ptr.push_back(new MockTreeCommLevel); temp.emplace_back(m_level_ptr[lvl]); } EXPECT_CALL(*m_mock_comm, barrier()); EXPECT_CALL(*m_mock_comm, num_rank()).WillOnce(Return(120)); m_tree_comm.reset(new TreeCommImp(m_mock_comm, m_fan_out, m_fan_out.size() - 1, m_num_send_down, m_num_send_up, std::move(temp))); } TEST_F(TreeCommTest, geometry) { // tree comm controlling up to root root_setup(); EXPECT_EQ(4, m_tree_comm->num_level_controlled()); EXPECT_EQ(4, m_tree_comm->root_level()); EXPECT_EQ(4, m_tree_comm->max_level()); for (size_t level = 0; level < m_fan_out.size(); ++level) { int rank = 5 - level; EXPECT_CALL(*(m_level_ptr[level]), level_rank()).WillOnce(Return(rank)); EXPECT_EQ(rank, m_tree_comm->level_rank(level)); EXPECT_EQ(m_fan_out[m_fan_out.size() - level - 1], m_tree_comm->level_size(level)); } // errors GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->level_rank(-1), GEOPM_ERROR_LEVEL_RANGE, "level_rank"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->level_rank(10), GEOPM_ERROR_LEVEL_RANGE, "level_rank"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->level_size(-1), GEOPM_ERROR_LEVEL_RANGE, "level_size"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->level_size(10), GEOPM_ERROR_LEVEL_RANGE, "level_size"); } TEST_F(TreeCommTest, geometry_nonroot) { nonroot_setup(); EXPECT_EQ(3, m_tree_comm->num_level_controlled()); EXPECT_EQ(4, m_tree_comm->root_level()); EXPECT_EQ(4, m_tree_comm->max_level()); for (size_t level = 0; level < m_fan_out.size(); ++level) { int rank = 5 - level; EXPECT_CALL(*(m_level_ptr[level]), level_rank()).WillOnce(Return(rank)); EXPECT_EQ(rank, m_tree_comm->level_rank(level)); EXPECT_EQ(m_fan_out[m_fan_out.size() - level - 1], m_tree_comm->level_size(level)); } } TEST_F(TreeCommTest, send_receive) { root_setup(); std::vector<double> sample {10.0, 11.0, 12.0}; std::vector<std::vector<double> > expected_sample {sample, sample}; std::vector<std::vector<double> > recv_sample(2, std::vector<double>(3)); std::vector<std::vector<double> > policy {{9.0}, {8.0}}; std::vector<double> recv_policy(1); for (size_t level = 0; level < m_level_ptr.size(); ++level) { EXPECT_CALL(*(m_level_ptr[level]), send_up(sample)); m_tree_comm->send_up(level, sample); EXPECT_CALL(*(m_level_ptr[level]), send_down(policy)); m_tree_comm->send_down(level, policy); if (level) { EXPECT_CALL(*(m_level_ptr[level]), receive_up(_)).WillOnce( DoAll(SetArgReferee<0>(expected_sample), Return(true))); EXPECT_TRUE(m_tree_comm->receive_up(level, recv_sample)); EXPECT_EQ(expected_sample, recv_sample); } EXPECT_CALL(*(m_level_ptr[level]), receive_down(_)).WillOnce( DoAll(SetArgReferee<0>(policy[0]), Return(true))); EXPECT_TRUE(m_tree_comm->receive_down(level, recv_policy)); EXPECT_EQ(policy[0], recv_policy); } GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->send_up(-1, sample), GEOPM_ERROR_LEVEL_RANGE, "send_up"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->send_down(-1, policy), GEOPM_ERROR_LEVEL_RANGE, "send_down"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->receive_up(-1, recv_sample), GEOPM_ERROR_LEVEL_RANGE, "receive_up"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->receive_down(-1, recv_policy), GEOPM_ERROR_LEVEL_RANGE, "receive_down"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->send_up(10, sample), GEOPM_ERROR_LEVEL_RANGE, "send_up"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->send_down(10, policy), GEOPM_ERROR_LEVEL_RANGE, "send_down"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->receive_up(10, recv_sample), GEOPM_ERROR_LEVEL_RANGE, "receive_up"); GEOPM_EXPECT_THROW_MESSAGE(m_tree_comm->receive_down(10, recv_policy), GEOPM_ERROR_LEVEL_RANGE, "receive_down"); } TEST_F(TreeCommTest, overhead_send) { root_setup(); std::vector<size_t> overhead{67, 78, 89, 90}; size_t expected_overhead = std::accumulate(overhead.begin(), overhead.end(), 0); for (size_t level = 0; level < m_level_ptr.size(); ++level) { EXPECT_CALL(*(m_level_ptr[level]), overhead_send()) .WillOnce(Return(overhead[level])); } EXPECT_EQ(expected_overhead, m_tree_comm->overhead_send()); }
; ///////////////////////////////////////////////////////////////////////////// ; Znake (ZX Spectrum 48K) ; ----------------------------------------------------------------------------- ; 8_loop_draw_graphics.asm ; ----------------------------------------------------------------------------- ; Copyright (C) 2016, Chris Wyatt ; All rights reserved ; Distributed under the Apache 2 license (see LICENSE) ; ///////////////////////////////////////////////////////////////////////////// update_graphics_init: ld hl,str_score ld de,0x0b02 call print ; If food eaten flag is not set, loop 4 times to update grid locations: ; new head, existing head, new tail, existing tail (c = 5) ; Otherwise, draw current score and loop 2 times to update grid locations: ; new head, existing head (c = 3) ld a,(flags) cpl and 0x01 add a,a add a,3 ld c,a ld iy,draw_line halt update_graphics_next: dec c jp z,next_game_loop pop hl ld b,0x0f ; Load x-coordinate into register d ld a,h rrca rrca rrca rrca and b add a,8 ld d,a ; Load y-coordinate into register e ld a,h and b add a,4 ld e,a ld h,0x81 call draw_char jp update_graphics_next
// file : libbuild2/script/parser.cxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #include <libbuild2/script/parser.hxx> #include <libbuild2/variable.hxx> #include <libbuild2/script/run.hxx> // exit #include <libbuild2/script/lexer.hxx> using namespace std; namespace build2 { namespace script { using type = token_type; value parser:: parse_variable_line (token& t, type& tt) { // enter: assignment // leave: newline or unknown token next_with_attributes (t, tt); // Parse value attributes if any. Note that it's ok not to have // anything after the attributes (e.g., foo=[null]). // attributes_push (t, tt, true); // @@ PAT: Should we expand patterns? Note that it will only be // simple ones since we have disabled {}. Also, what would be the // pattern base directory? // return tt != type::newline && start_names (tt) ? parse_value (t, tt, pattern_mode::ignore, "variable value", nullptr) : value (names ()); } // Parse the regular expression representation (non-empty string value // framed with introducer characters and optionally followed by flag // characters from the {di} set, for example '/foo/id') into // components. Also return end-of-parsing position if requested, // otherwise treat any unparsed characters left as an error. // struct regex_parts { string value; char intro; string flags; // Combination of characters from {di} set. // Create a special empty object. // regex_parts (): intro ('\0') {} regex_parts (string v, char i, string f) : value (move (v)), intro (i), flags (move (f)) {} }; static regex_parts parse_regex (const string& s, const location& l, const char* what, size_t* end = nullptr) { if (s.empty ()) fail (l) << "no introducer character in " << what; size_t p (s.find (s[0], 1)); // Find terminating introducer. if (p == string::npos) fail (l) << "no closing introducer character in " << what; size_t rn (p - 1); // Regex length. if (rn == 0) fail (l) << what << " is empty"; // Find end-of-flags position. // size_t fp (++p); // Save flags starting position. for (char c; (c = s[p]) == 'd' || c == 'i'; ++p) ; // If string end is not reached then report invalid flags, unless // end-of-parsing position is requested (which means regex is just a // prefix). // if (s[p] != '\0' && end == nullptr) fail (l) << "junk at the end of " << what; if (end != nullptr) *end = p; return regex_parts (string (s, 1, rn), s[0], string (s, fp, p - fp)); } optional<process_path> parser:: parse_program (token& t, type& tt, bool, bool, names& ns, parse_names_result& pr) { pr = parse_names (t, tt, ns, pattern_mode::ignore, true /* chunk */, "command line", nullptr); return nullopt; } pair<command_expr, parser::here_docs> parser:: parse_command_expr (token& t, type& tt, const redirect_aliases& ra) { // enter: first token of the command line // leave: <newline> or unknown token command_expr expr; // OR-ed to an implied false for the first term. // expr.push_back ({expr_operator::log_or, command_pipe ()}); command c; // Command being assembled. // Make sure the command makes sense. // auto check_command = [&c, this] (const location& l, bool last) { if (c.out && c.out->type == redirect_type::merge && c.err && c.err->type == redirect_type::merge) fail (l) << "stdout and stderr redirected to each other"; if (!last && c.out) fail (l) << "stdout is both redirected and piped"; }; // Check that the introducer character differs from '/' if the // portable path modifier is specified. Must be called before // parse_regex() (see below) to make sure its diagnostics is // meaningful. // // Note that the portable path modifier assumes '/' to be a valid // regex character and so makes it indistinguishable from the // terminating introducer. // auto check_regex_mod = [this] (const string& mod, const string& re, const location& l, const char* what) { // Handles empty regex properly. // if (mod.find ('/') != string::npos && re[0] == '/') fail (l) << "portable path modifier and '/' introducer in " << what; }; // Pending positions where the next word should go. // enum class pending { none, program_first, program_next, in_string, in_document, in_file, out_merge, out_string, out_str_regex, out_document, out_doc_regex, out_file, err_merge, err_string, err_str_regex, err_document, err_doc_regex, err_file, clean }; pending p (pending::program_first); string mod; // Modifiers for pending in_* and out_* positions. here_docs hd; // Expected here-documents. // Add the next word to either one of the pending positions or to // program arguments by default. // auto add_word = [&c, &p, &mod, &check_regex_mod, this] ( string&& w, const location& l) { auto add_merge = [&l, this] (optional<redirect>& r, const string& w, int fd) { assert (r); // Must already be present. try { size_t n; if (stoi (w, &n) == fd && n == w.size ()) { r->fd = fd; return; } } catch (const exception&) {} // Fall through. fail (l) << (fd == 1 ? "stderr" : "stdout") << " merge redirect " << "file descriptor must be " << fd; }; auto add_here_str = [] (optional<redirect>& r, string&& w) { assert (r); // Must already be present. if (r->modifiers ().find (':') == string::npos) w += '\n'; r->str = move (w); }; auto add_here_str_regex = [&l, &check_regex_mod] ( optional<redirect>& r, int fd, string&& w) { assert (r); // Must already be present. const char* what (nullptr); switch (fd) { case 1: what = "stdout regex redirect"; break; case 2: what = "stderr regex redirect"; break; } check_regex_mod (r->modifiers (), w, l, what); regex_parts rp (parse_regex (w, l, what)); regex_lines& re (r->regex); re.intro = rp.intro; re.lines.emplace_back ( l.line, l.column, move (rp.value), move (rp.flags)); // Add final blank line unless suppressed. // // Note that the position is synthetic, but that's ok as we don't // expect any diagnostics to refer this line. // if (r->modifiers ().find (':') == string::npos) re.lines.emplace_back (l.line, l.column, string (), false); }; auto parse_path = [&l, this] (string&& w, const char* what) -> path { try { path p (move (w)); if (!p.empty ()) { p.normalize (); return p; } fail (l) << "empty " << what << endf; } catch (const invalid_path& e) { fail (l) << "invalid " << what << " '" << e.path << "'" << endf; } }; auto add_file = [&parse_path] (optional<redirect>& r, int fd, string&& w) { assert (r); // Must already be present. const char* what (nullptr); switch (fd) { case 0: what = "stdin redirect path"; break; case 1: what = "stdout redirect path"; break; case 2: what = "stderr redirect path"; break; } r->file.path = parse_path (move (w), what); }; switch (p) { case pending::none: c.arguments.push_back (move (w)); break; case pending::program_first: case pending::program_next: c.program = process_path (nullptr /* initial */, parse_path (move (w), "program path"), path () /* effect */); break; case pending::out_merge: add_merge (c.out, w, 2); break; case pending::err_merge: add_merge (c.err, w, 1); break; case pending::in_string: add_here_str (c.in, move (w)); break; case pending::out_string: add_here_str (c.out, move (w)); break; case pending::err_string: add_here_str (c.err, move (w)); break; case pending::out_str_regex: { add_here_str_regex (c.out, 1, move (w)); break; } case pending::err_str_regex: { add_here_str_regex (c.err, 2, move (w)); break; } // These are handled specially below. // case pending::in_document: case pending::out_document: case pending::err_document: case pending::out_doc_regex: case pending::err_doc_regex: assert (false); break; case pending::in_file: add_file (c.in, 0, move (w)); break; case pending::out_file: add_file (c.out, 1, move (w)); break; case pending::err_file: add_file (c.err, 2, move (w)); break; case pending::clean: { cleanup_type t; switch (mod[0]) // Ok, if empty { case '!': t = cleanup_type::never; break; case '?': t = cleanup_type::maybe; break; default: t = cleanup_type::always; break; } c.cleanups.push_back ( {t, parse_path (move (w), "cleanup path")}); break; } } p = pending::none; mod.clear (); }; // Make sure we don't have any pending positions to fill. // auto check_pending = [&p, this] (const location& l) { const char* what (nullptr); switch (p) { case pending::none: break; case pending::program_first: case pending::program_next: what = "program"; break; case pending::in_string: what = "stdin here-string"; break; case pending::in_document: what = "stdin here-document end"; break; case pending::in_file: what = "stdin file"; break; case pending::out_merge: what = "stdout file descriptor"; break; case pending::out_string: what = "stdout here-string"; break; case pending::out_document: what = "stdout here-document end"; break; case pending::out_file: what = "stdout file"; break; case pending::err_merge: what = "stderr file descriptor"; break; case pending::err_string: what = "stderr here-string"; break; case pending::err_document: what = "stderr here-document end"; break; case pending::err_file: what = "stderr file"; break; case pending::clean: what = "cleanup path"; break; case pending::out_str_regex: { what = "stdout here-string regex"; break; } case pending::err_str_regex: { what = "stderr here-string regex"; break; } case pending::out_doc_regex: { what = "stdout here-document regex end"; break; } case pending::err_doc_regex: { what = "stderr here-document regex end"; break; } } if (what != nullptr) fail (l) << "missing " << what; }; // Parse the redirect operator. // // If the token type is the redirect alias then tt must contain the type // the alias resolves to and the token type otherwise. Note that this // argument defines the redirect semantics. Also note that the token is // saved into the redirect to keep the modifiers and the original // representation. // auto parse_redirect = [&c, &expr, &p, &mod, &hd, this] (token&& t, type tt, const location& l) { // The redirect alias token type must be resolved. // assert (tt != type::in_l && tt != type::in_ll && tt != type::in_lll && tt != type::out_g && tt != type::out_gg && tt != type::out_ggg); // Our semantics is the last redirect seen takes effect. // assert (p == pending::none && mod.empty ()); // See if we have the file descriptor. // unsigned long fd (3); if (!t.separated) { if (c.arguments.empty ()) fail (l) << "missing redirect file descriptor"; const string& s (c.arguments.back ()); try { size_t n; fd = stoul (s, &n); if (n != s.size () || fd > 2) throw invalid_argument (string ()); } catch (const exception&) { fail (l) << "invalid redirect file descriptor '" << s << "'"; } c.arguments.pop_back (); } // Validate/set default file descriptor. // switch (tt) { case type::in_pass: case type::in_null: case type::in_str: case type::in_doc: case type::in_file: { if ((fd = fd == 3 ? 0 : fd) != 0) fail (l) << "invalid in redirect file descriptor " << fd; if (!expr.back ().pipe.empty ()) fail (l) << "stdin is both piped and redirected"; break; } case type::out_pass: case type::out_null: case type::out_trace: case type::out_merge: case type::out_str: case type::out_doc: case type::out_file_cmp: case type::out_file_ovr: case type::out_file_app: { if ((fd = fd == 3 ? 1 : fd) == 0) fail (l) << "invalid out redirect file descriptor " << fd; break; } } // Don't move as we will save the token into the redirect object. // mod = t.value; // Handle the none redirect (no data allowed) in the switch construct // if/when the respective syntax is invented. // redirect_type rt (redirect_type::none); switch (tt) { case type::in_pass: case type::out_pass: rt = redirect_type::pass; break; case type::in_null: case type::out_null: rt = redirect_type::null; break; case type::out_trace: rt = redirect_type::trace; break; case type::out_merge: rt = redirect_type::merge; break; case type::in_str: case type::out_str: { bool re (mod.find ('~') != string::npos); assert (tt == type::out_str || !re); rt = re ? redirect_type::here_str_regex : redirect_type::here_str_literal; break; } case type::in_doc: case type::out_doc: { bool re (mod.find ('~') != string::npos); assert (tt == type::out_doc || !re); rt = re ? redirect_type::here_doc_regex : redirect_type::here_doc_literal; break; } case type::in_file: case type::out_file_cmp: case type::out_file_ovr: case type::out_file_app: rt = redirect_type::file; break; } optional<redirect>& r (fd == 0 ? c.in : fd == 1 ? c.out : c.err); optional<redirect_type> overriden; if (r) overriden = r->type; r = redirect (rt); // Don't move as still may be used for pending here-document end // marker processing. // r->token = move (t); switch (rt) { case redirect_type::none: // Remove the assertion if/when the none redirect syntax is // invented. // assert (false); // Fall through. case redirect_type::pass: case redirect_type::null: case redirect_type::trace: break; case redirect_type::merge: switch (fd) { case 0: assert (false); break; case 1: p = pending::out_merge; break; case 2: p = pending::err_merge; break; } break; case redirect_type::here_str_literal: switch (fd) { case 0: p = pending::in_string; break; case 1: p = pending::out_string; break; case 2: p = pending::err_string; break; } break; case redirect_type::here_str_regex: switch (fd) { case 0: assert (false); break; case 1: p = pending::out_str_regex; break; case 2: p = pending::err_str_regex; break; } break; case redirect_type::here_doc_literal: switch (fd) { case 0: p = pending::in_document; break; case 1: p = pending::out_document; break; case 2: p = pending::err_document; break; } break; case redirect_type::here_doc_regex: switch (fd) { case 0: assert (false); break; case 1: p = pending::out_doc_regex; break; case 2: p = pending::err_doc_regex; break; } break; case redirect_type::file: switch (fd) { case 0: p = pending::in_file; break; case 1: p = pending::out_file; break; case 2: p = pending::err_file; break; } // Also sets for stdin, but this is harmless. // r->file.mode = tt == type::out_file_ovr ? redirect_fmode::overwrite : tt == type::out_file_app ? redirect_fmode::append : redirect_fmode::compare; break; case redirect_type::here_doc_ref: assert (false); break; } // If we are overriding a here-document, then remove the reference // to this command redirect from the corresponding here_doc object. // if (!pre_parse_ && overriden && (*overriden == redirect_type::here_doc_literal || *overriden == redirect_type::here_doc_regex)) { size_t e (expr.size () - 1); size_t p (expr.back ().pipe.size ()); int f (static_cast<int> (fd)); for (here_doc& d: hd) { small_vector<here_redirect, 2>& rs (d.redirects); auto i (find_if (rs.begin (), rs.end (), [e, p, f] (const here_redirect& r) { return r.expr == e && r.pipe == p && r.fd == f; })); if (i != rs.end ()) { rs.erase (i); break; } } } }; // Set pending cleanup type. // auto parse_clean = [&p, &mod] (token& t) { p = pending::clean; mod = move (t.value); }; const location ll (get_location (t)); // Line location. // Keep parsing chunks of the command line until we see one of the // "terminators" (newline, exit status comparison, etc). // location l (ll); names ns; // Reuse to reduce allocations. for (bool done (false); !done; l = get_location (t)) { tt = ra.resolve (tt); switch (tt) { case type::newline: { done = true; break; } case type::equal: case type::not_equal: { if (!pre_parse_) check_pending (l); c.exit = parse_command_exit (t, tt); // Only a limited set of things can appear after the exit status // so we check this here. // switch (tt) { case type::newline: case type::pipe: case type::log_or: case type::log_and: break; default: { // Bail out if this is one of the unknown/unexpected tokens. // done = true; break; } } break; } case type::pipe: case type::log_or: case type::log_and: case type::in_pass: case type::out_pass: case type::in_null: case type::out_null: case type::out_trace: case type::out_merge: case type::in_str: case type::in_doc: case type::out_str: case type::out_doc: case type::in_file: case type::out_file_cmp: case type::out_file_ovr: case type::out_file_app: case type::clean: { if (pre_parse_) { // The only things we need to handle here are the tokens that // introduce the next command, since we handle the command // leading name chunks specially, and the here-document and // here-document regex end markers, since we need to know how // many of them to pre-parse after the command. // switch (tt) { case type::pipe: case type::log_or: case type::log_and: p = pending::program_next; break; case type::in_doc: case type::out_doc: mod = move (t.value); bool re (mod.find ('~') != string::npos); const char* what (re ? "here-document regex end marker" : "here-document end marker"); // We require the end marker to be a literal, unquoted word. // In particularm, we don't allow quoted because of cases // like foo"$bar" (where we will see word 'foo'). // next (t, tt); // We require the end marker to be an unquoted or completely // quoted word. The complete quoting becomes important for // cases like foo"$bar" (where we will see word 'foo'). // // For good measure we could have also required it to be // separated from the following token, but out grammar // allows one to write >>EOO;. The problematic sequence // would be >>FOO$bar -- on reparse it will be expanded // as a single word. // if (tt != type::word || t.value.empty ()) fail (t) << "expected " << what; peek (); const token& p (peeked ()); if (!p.separated) { switch (p.type) { case type::dollar: case type::lparen: fail (p) << what << " must be literal"; } } quote_type qt (t.qtype); switch (qt) { case quote_type::unquoted: qt = quote_type::single; // Treat as single-quoted. break; case quote_type::single: case quote_type::double_: if (t.qcomp) break; // Fall through. case quote_type::mixed: fail (t) << "partially-quoted " << what; } regex_parts r; string end (move (t.value)); if (re) { check_regex_mod (mod, end, l, what); r = parse_regex (end, l, what); end = move (r.value); // The "cleared" end marker. } bool literal (qt == quote_type::single); bool shared (false); for (const auto& d: hd) { if (d.end == end) { auto check = [&t, &end, &re, this] (bool c, const char* what) { if (!c) fail (t) << "different " << what << " for shared here-document " << (re ? "regex '" : "'") << end << "'"; }; check (d.modifiers == mod, "modifiers"); check (d.literal == literal, "quoting"); if (re) { check (d.regex == r.intro, "introducers"); check (d.regex_flags == r.flags, "global flags"); } shared = true; break; } } if (!shared) hd.push_back ( here_doc { {}, move (end), literal, move (mod), r.intro, move (r.flags)}); break; } next (t, tt); break; } // If this is one of the operators/separators, check that we // don't have any pending locations to be filled. // check_pending (l); // Note: there is another one in the inner loop below. // switch (tt) { case type::pipe: case type::log_or: case type::log_and: { // Check that the previous command makes sense. // check_command (l, tt != type::pipe); expr.back ().pipe.push_back (move (c)); c = command (); p = pending::program_next; if (tt != type::pipe) { expr_operator o (tt == type::log_or ? expr_operator::log_or : expr_operator::log_and); expr.push_back ({o, command_pipe ()}); } break; } case type::in_pass: case type::out_pass: case type::in_null: case type::out_null: case type::out_trace: case type::out_merge: case type::in_str: case type::in_doc: case type::out_str: case type::out_doc: case type::in_file: case type::out_file_cmp: case type::out_file_ovr: case type::out_file_app: { parse_redirect (move (t), tt, l); break; } case type::clean: { parse_clean (t); break; } default: assert (false); break; } next (t, tt); break; } default: { // Bail out if this is one of the unknown tokens. // if (!start_names (tt)) { done = true; break; } // Here-document end markers are literal (we verified that above // during pre-parsing) and we need to know whether they were // quoted. So handle this case specially. // { int fd; switch (p) { case pending::in_document: fd = 0; break; case pending::out_document: case pending::out_doc_regex: fd = 1; break; case pending::err_document: case pending::err_doc_regex: fd = 2; break; default: fd = -1; break; } if (fd != -1) { if (tt != type::word || t.value.empty ()) fail (t) << "expected here-document end marker"; here_redirect rd { expr.size () - 1, expr.back ().pipe.size (), fd}; string end (move (t.value)); regex_parts r; if (p == pending::out_doc_regex || p == pending::err_doc_regex) { // We can't fail here as we already parsed all the end // markers during pre-parsing stage, and so no need in the // description. // r = parse_regex (end, l, ""); end = move (r.value); // The "cleared" end marker. } bool shared (false); for (auto& d: hd) { // No need to check that redirects that share here-document // have the same modifiers, etc. That have been done during // pre-parsing. // if (d.end == end) { d.redirects.emplace_back (rd); shared = true; break; } } if (!shared) hd.push_back ( here_doc { {rd}, move (end), (t.qtype == quote_type::unquoted || t.qtype == quote_type::single), move (mod), r.intro, move (r.flags)}); p = pending::none; mod.clear (); next (t, tt); break; } } bool prog (p == pending::program_first || p == pending::program_next); // Check if this is the env pseudo-builtin. // bool env (false); if (prog && tt == type::word && t.value == "env") { parsed_env r (parse_env_builtin (t, tt)); c.cwd = move (r.cwd); c.variables = move (r.variables); c.timeout = r.timeout; env = true; } // Parse the next chunk as names to get expansion, etc. Note that // we do it in the chunking mode to detect whether anything in // each chunk is quoted. If we are waiting for the command // program, then delegate the parsing to the derived parser, so it // can translate complex program names (targets, process_paths) // during execution and perform some static analysis during // pre-parsing. // // @@ PAT: should we support pattern expansion? This is even // fuzzier than the variable case above. Though this is the // shell semantics. Think what happens when we do rm *.txt? // reset_quoted (t); parse_names_result pr; if (prog) { optional<process_path> pp ( parse_program (t, tt, p == pending::program_first, env, ns, pr)); // During pre-parsing we are not interested in the // parse_program() call result, so just discard the potentially // unhandled program chunk names. // if (!pre_parse_) { if (pp) { c.program = move (*pp); p = pending::none; } } else { ns.clear (); p = pending::none; } } else pr = parse_names (t, tt, ns, pattern_mode::ignore, true /* chunk */, "command line", nullptr); // Nothing else to do if we are pre-parsing (or if parse_program() // took care of this chunk). // if (pre_parse_ || ns.empty ()) break; // Process what we got. // // First see if this is a value that should not be re-lexed. The // long term plan is to only re-lex values of a special type // representing a canned command line. // // Otherwise, determine whether anything inside was quoted (note // that the current token is "next" and is not part of this). // bool q ( (pr.value && !relex_) || (quoted () - (t.qtype != quote_type::unquoted ? 1 : 0)) != 0); for (name& n: ns) { string s; try { s = value_traits<string>::convert (move (n), nullptr); } catch (const invalid_argument&) { diag_record dr (fail (l)); dr << "invalid string value "; to_stream (dr.os, n, true /* quote */); } // If it is a quoted chunk, then we add the word as is. // Otherwise we re-lex it. But if the word doesn't contain any // interesting characters (operators plus quotes/escapes), // then no need to re-lex. // // NOTE: update quoting (script.cxx:to_stream_q()) if adding // any new characters. // if (q || s.find_first_of ("|&<>\'\"\\") == string::npos) add_word (move (s), l); else { // If the chunk re-parsing results in error, our diagnostics // will look like this: // // <string>:1:4: error: stdout merge redirect file descriptor must be 2 // script:2:5: info: while parsing string '1>&a' // auto df = make_diag_frame ( [this, s, &l](const diag_record& dr) { dr << info (l) << "while parsing string '" << s << "'"; }); // When re-lexing we do "effective escaping" and only for // ['"\] (quotes plus the backslash itself). In particular, // there is no way to escape redirects, operators, etc. The // idea is to prefer quoting except for passing literal // quotes, for example: // // args = \"&foo\" // cmd $args # cmd &foo // // args = 'x=\"foo bar\"' // cmd $args # cmd x="foo bar" // istringstream is (s); path_name in ("<string>"); lexer lex (is, in, lexer_mode::command_expansion, ra, "\'\"\\"); // Treat the first "sub-token" as always separated from what // we saw earlier. // // Note that this is not "our" token so we cannot do // fail(t). Rather we should do fail(l). // token t (lex.next ()); location l (build2::get_location (t, in)); t.separated = true; string w; bool f (t.type == type::eos); // If the whole thing is empty. for (; t.type != type::eos; t = lex.next ()) { type tt (ra.resolve (t.type)); l = build2::get_location (t, in); // Re-lexing double-quotes will recognize $, ( inside as // tokens so we have to reverse them back. Since we don't // treat spaces as separators we can be sure we will get // it right. // switch (tt) { case type::dollar: w += '$'; continue; case type::lparen: w += '('; continue; } // Retire the current word. We need to distinguish between // empty and non-existent (e.g., > vs >""). // if (!w.empty () || f) { add_word (move (w), l); f = false; } if (tt == type::word) { w = move (t.value); f = true; continue; } // If this is one of the operators/separators, check that // we don't have any pending locations to be filled. // check_pending (l); // Note: there is another one in the outer loop above. // switch (tt) { case type::pipe: case type::log_or: case type::log_and: { // Check that the previous command makes sense. // check_command (l, tt != type::pipe); expr.back ().pipe.push_back (move (c)); c = command (); p = pending::program_next; if (tt != type::pipe) { expr_operator o (tt == type::log_or ? expr_operator::log_or : expr_operator::log_and); expr.push_back ({o, command_pipe ()}); } break; } case type::in_pass: case type::out_pass: case type::in_null: case type::out_null: case type::out_trace: case type::out_merge: case type::in_str: case type::out_str: case type::in_file: case type::out_file_cmp: case type::out_file_ovr: case type::out_file_app: { parse_redirect (move (t), tt, l); break; } case type::clean: { parse_clean (t); break; } case type::in_doc: case type::out_doc: { fail (l) << "here-document redirect in expansion"; break; } } } // Don't forget the last word. // if (!w.empty () || f) add_word (move (w), l); } } ns.clear (); break; } } } if (!pre_parse_) { // Verify we don't have anything pending to be filled and the // command makes sense. // check_pending (l); check_command (l, true); expr.back ().pipe.push_back (move (c)); } return make_pair (move (expr), move (hd)); } parser::parsed_env parser:: parse_env_builtin (token& t, token_type& tt) { // enter: 'env' word token // leave: first token of the program name next (t, tt); // Skip 'env'. // Note that an option name and value can belong to different name // chunks. That's why we parse the env builtin arguments in the chunking // mode into the argument/location pair list up to the '--' separator // and parse this list into the variable sets/unsets afterwords. // // Align the size with environment_vars (double because of -u <var> // which is two arguments). // using args = small_vector<pair<string, location>, 4>; args as; names ns; // Reuse to reduce allocations. while (tt != type::word || t.value != "--") { location l (get_location (t)); if (!start_names (tt)) fail (l) << "env: expected option, variable, or '--' separator " << "instead of " << t; parse_names (t, tt, ns, pattern_mode::ignore, true /* chunk */, "env builtin argument", nullptr); if (pre_parse_) continue; for (name& n: ns) { try { as.emplace_back ( value_traits<string>::convert (move (n), nullptr), l); } catch (const invalid_argument&) { diag_record dr (fail (l)); dr << "invalid string value "; to_stream (dr.os, n, true /* quote */); } } ns.clear (); } location l (get_location (t)); // '--' location. next (t, tt); // Skip '--'. if (tt == type::newline || tt == type::eos) fail (t) << "env: expected program name instead of " << t; // Parse the env builtin options and arguments. // parsed_env r; // Note: args is empty in the pre-parse mode. // auto i (as.begin ()), e (as.end ()); // Parse options (the timeout and variable unsets). // for (; i != e; ++i) { string& o (i->first); // Bail out if the options and arguments separator is encountered. // if (o == "-") { ++i; break; } // We should probably switch to CLI if we need anything more // elaborate. Note however, that we will have no precise error // location then. // // If this is an option represented with its long or short name, then // return its value as string and nullopt otherwise. In the former // case strip the value assignment from the option, if it is in the // <name>=<value> form, and fail if the option value is empty. // auto str = [&i, &e, &o, &l, this] (const char* lo, const char* so) { optional<string> r; if (o == lo || o == so) { if (++i == e) fail (l) << "env: missing value for option '" << o << "'"; r = move (i->first); } else { size_t n (string::traits_type::length (lo)); if (o.compare (0, n, lo) == 0 && o[n] == '=') { r = string (o, n + 1); o.resize (n); } } if (r && r->empty ()) fail (i->second) << "env: empty value for option '" << o << "'"; return r; }; auto bad = [&i, &o, this] (const string& v) { fail (i->second) << "env: invalid value '" << v << "' for option '" << o << "'"; }; // As above but convert the option value to a number and fail on // error. // auto num = [&str, &bad] (const char* ln, const char* sn) { optional<uint64_t> r; if (optional<string> s = str (ln, sn)) { r = parse_number (*s); if (!r) bad (*s); } return r; }; // As above but convert the option value to a directory path and fail // on error. // auto dir = [&str, &bad] (const char* ln, const char* sn) { optional<dir_path> r; if (optional<string> s = str (ln, sn)) try { // Note that we don't need to check that the path is not empty, // since str() fails for empty values. // r = dir_path (move (*s)); } catch (const invalid_path& e) { bad (e.path); } return r; }; // Parse a known option or bail out to parsing the variable sets. // if (optional<uint64_t> v = num ("--timeout", "-t")) { r.timeout = chrono::seconds (*v); } else if (optional<dir_path> v = dir ("--cwd", "-c")) { r.cwd = move (*v); } else if (optional<string> v = str ("--unset", "-u")) { verify_environment_var_name (*v, "env: ", i->second, o.c_str ()); r.variables.add (move (*v)); } else break; } // Parse arguments (variable sets). // for (; i != e; ++i) { string& a (i->first); verify_environment_var_assignment (a, "env: ", i->second); r.variables.add (move (a)); } return r; } command_exit parser:: parse_command_exit (token& t, type& tt) { // enter: equal/not_equal // leave: token after exit status (one parse_names() chunk) exit_comparison comp (tt == type::equal ? exit_comparison::eq : exit_comparison::ne); // The next chunk should be the exit status. // next (t, tt); location l (get_location (t)); names ns (parse_names (t, tt, pattern_mode::ignore, true, "exit status", nullptr)); unsigned long es (256); if (!pre_parse_) { try { if (ns.size () == 1 && ns[0].simple () && !ns[0].empty ()) es = stoul (ns[0].value); } catch (const exception&) {} // Fall through. if (es > 255) { diag_record dr; dr << fail (l) << "expected exit status instead of "; to_stream (dr.os, ns, true /* quote */); dr << info << "exit status is an unsigned integer less than 256"; } } return command_exit {comp, static_cast<uint8_t> (es)}; } void parser:: parse_here_documents (token& t, type& tt, pair<command_expr, here_docs>& p) { // enter: newline // leave: newline // Parse here-document fragments in the order they were mentioned on // the command line. // for (here_doc& h: p.second) { // Switch to the here-line mode which is like single/double-quoted // string but recognized the newline as a separator. // mode (h.literal ? lexer_mode::here_line_single : lexer_mode::here_line_double); next (t, tt); parsed_doc v ( parse_here_document (t, tt, h.end, h.modifiers, h.regex)); // If all the here-document redirects are overridden, then we just // drop the fragment. // if (!pre_parse_ && !h.redirects.empty ()) { auto i (h.redirects.cbegin ()); command& c (p.first[i->expr].pipe[i->pipe]); optional<redirect>& r (i->fd == 0 ? c.in : i->fd == 1 ? c.out : c.err); assert (r); // Must be present since it is referred. if (v.re) { assert (r->type == redirect_type::here_doc_regex); r->regex = move (v.regex); r->regex.flags = move (h.regex_flags); } else { assert (r->type == redirect_type::here_doc_literal); r->str = move (v.str); } r->end = move (h.end); r->end_line = v.end_line; r->end_column = v.end_column; // Note that our references cannot be invalidated because the // command_expr/command-pipe vectors already contain all their // elements. // for (++i; i != h.redirects.cend (); ++i) { command& c (p.first[i->expr].pipe[i->pipe]); optional<redirect>& ir (i->fd == 0 ? c.in : i->fd == 1 ? c.out : c.err); // Must be present since it is referenced by here-doc. // assert (ir); // Note: preserve the original representation. // ir = redirect (redirect_type::here_doc_ref, *r, move (ir->token)); } } expire_mode (); } } parser::parsed_doc parser:: parse_here_document (token& t, type& tt, const string& em, const string& mod, char re) { // enter: first token on first line // leave: newline (after end marker) // String literal. Note that when decide if to terminate the previously // added line with a newline, we need to distinguish a yet empty result // and the one that has a single blank line added. // optional<string> rs; regex_lines rre; // Here-documents can be indented. The leading whitespaces of the end // marker line (called strip prefix) determine the indentation. Every // other line in the here-document should start with this prefix which // is automatically stripped. The only exception is a blank line. // // The fact that the strip prefix is only known at the end, after // seeing all the lines, is rather inconvenient. As a result, the way // we implement this is a bit hackish (though there is also something // elegant about it): at the end of the pre-parse stage we are going // re-examine the sequence of tokens that comprise this here-document // and "fix up" the first token of each line by stripping the prefix. // string sp; // Remember the position of the first token in this here-document. // size_t ri (pre_parse_ ? replay_data_.size () - 1 : 0); // We will use the location of the first token on the line for the // regex diagnostics. At the end of the loop it will point to the // beginning of the end marker. // location l; while (tt != type::eos) { l = get_location (t); // Check if this is the end marker. For starters, it should be a // single, unquoted word followed by a newline. // if (tt == type::word && t.qtype == quote_type::unquoted && peek () == type::newline) { const string& v (t.value); size_t vn (v.size ()); size_t en (em.size ()); // Then check that it ends with the end marker. // if (vn >= en && v.compare (vn - en, en, em) == 0) { // Now check that the prefix only contains whitespaces. // size_t n (vn - en); if (v.find_first_not_of (" \t") >= n) { assert (pre_parse_ || n == 0); // Should have been stripped. if (n != 0) sp.assign (v, 0, n); // Save the strip prefix. next (t, tt); // Get the newline. break; } } } // Expand the line (can be blank). // // @@ PAT: one could argue that if we do it in variables, then we // should do it here as well. Though feels bizarre. // names ns (tt != type::newline ? parse_names (t, tt, pattern_mode::ignore, false, "here-document line", nullptr) : names ()); if (!pre_parse_) { // What shall we do if the expansion results in multiple names? // For, example if the line contains just the variable expansion // and it is of type strings. Adding all the elements space- // separated seems like the natural thing to do. // string s; for (auto b (ns.begin ()), i (b); i != ns.end (); ++i) { string n; try { n = value_traits<string>::convert (move (*i), nullptr); } catch (const invalid_argument&) { fail (l) << "invalid string value '" << *i << "'"; } if (i == b) s = move (n); else { s += ' '; s += n; } } if (!re) { // Add newline after previous line. // if (rs) { *rs += '\n'; *rs += s; } else rs = move (s); } else { // Due to expansion we can end up with multiple lines. If empty // then will add a blank textual literal. // for (size_t p (0); p != string::npos; ) { string ln; size_t np (s.find ('\n', p)); if (np != string::npos) { ln = string (s, p, np - p); p = np + 1; } else { ln = string (s, p); p = np; } if (ln[0] != re) // Line doesn't start with regex introducer. { // This is a line-char literal (covers blank lines as well). // // Append textual literal. // rre.lines.emplace_back (l.line, l.column, move (ln), false); } else // Line starts with the regex introducer. { // This is a char-regex, or a sequence of line-regex syntax // characters or both (in this specific order). So we will // add regex (with optional special characters) or special // literal. // size_t p (ln.find (re, 1)); if (p == string::npos) { // No regex, just a sequence of syntax characters. // string spec (ln, 1); if (spec.empty ()) fail (l) << "no syntax line characters"; // Append special literal. // rre.lines.emplace_back ( l.line, l.column, move (spec), true); } else { // Regex (probably with syntax characters). // regex_parts re; // Empty regex is a special case repesenting a blank line. // if (p == 1) // Position to optional specal characters of an empty // regex. // ++p; else // Can't fail as all the pre-conditions verified // (non-empty with both introducers in place), so no // description required. // re = parse_regex (ln, l, "", &p); // Append regex with optional special characters. // rre.lines.emplace_back (l.line, l.column, move (re.value), move (re.flags), string (ln, p)); } } } } } // We should expand the whole line at once so this would normally be // a newline but can also be an end-of-stream. // if (tt == type::newline) next (t, tt); else assert (tt == type::eos); } if (tt == type::eos) fail (t) << "missing here-document end marker '" << em << "'"; if (pre_parse_) { // Strip the indentation prefix if there is one. // assert (replay_ == replay::save); if (!sp.empty ()) { size_t sn (sp.size ()); for (; ri != replay_data_.size (); ++ri) { token& rt (replay_data_[ri].token); if (rt.type == type::newline) // Blank continue; if (rt.type != type::word || rt.value.compare (0, sn, sp) != 0) fail (rt) << "unindented here-document line"; // If the word is equal to the strip prefix then we have to drop // the token. Note that simply making it an empty word won't // have the same semantics. For instance, it would trigger // concatenated expansion. // if (rt.value.size () == sn) replay_data_.erase (replay_data_.begin () + ri); else { rt.value.erase (0, sn); rt.column += sn; ++ri; } // Skip until next newline. // for (; replay_data_[ri].token.type != type::newline; ++ri) ; } } } else { // Add final newline unless suppressed. // if (mod.find (':') == string::npos) { if (re) // Note that the position is synthetic, but that's ok as we don't // expect any diagnostics to refer this line. // rre.lines.emplace_back (l.line, l.column, string (), false); else if (rs) *rs += '\n'; else rs = "\n"; } // Finalize regex lines. // if (re) { // Empty regex matches nothing, so not of much use. // if (rre.lines.empty ()) fail (l) << "empty here-document regex"; rre.intro = re; } } return re ? parsed_doc (move (rre), l.line, l.column) : parsed_doc (rs ? move (*rs) : string (), l.line, l.column); } size_t parser:: quoted () const { size_t r (0); if (replay_ != replay::play) r = lexer_->quoted (); else { // Examine tokens we have replayed since last reset. // size_t ri (!peeked_ ? replay_i_ : replay_i_ - 1); for (size_t i (replay_quoted_); i != ri; ++i) if (replay_data_[i].token.qtype != quote_type::unquoted) ++r; } return r; } void parser:: reset_quoted (token& cur) { if (replay_ != replay::play) lexer_->reset_quoted (cur.qtype != quote_type::unquoted ? 1 : 0); else { replay_quoted_ = replay_i_ - (!peeked_ ? 1 : 2); // Must be the same token. // assert (replay_data_[replay_quoted_].token.qtype == cur.qtype); } } void parser:: set_lexer (lexer* l) { lexer_ = l; build2::parser::lexer_ = l; } static redirect_aliases no_redirect_aliases; void parser:: apply_value_attributes (const variable* var, value& lhs, value&& rhs, const string& attributes, token_type kind, const path_name& name) { path_ = &name; istringstream is (attributes); // Note that the redirect alias information is not used in the // attributes lexer mode. // lexer l (is, name, lexer_mode::attributes, no_redirect_aliases); set_lexer (&l); token t; type tt; next_with_attributes (t, tt); // Enable `[` recognition. if (tt != type::lsbrace && tt != type::eos) fail (t) << "expected '[' instead of " << t; attributes_push (t, tt, true); if (tt != type::eos) fail (t) << "trailing junk after ']'"; build2::parser::apply_value_attributes (var, lhs, move (rhs), kind); } line_type parser:: pre_parse_line_start (token& t, token_type& tt, lexer_mode stm) { replay_save (); // Start saving tokens from the current one. next (t, tt); // Decide whether this is a variable assignment or a command. // // It is an assignment if the first token is an unquoted name and // the next token is an assign/append/prepend operator. Assignment // to a computed variable name must use the set builtin. // // Note also that special commands take precedence over variable // assignments. // line_type r (line_type::cmd); // Default. if (tt == type::word && t.qtype == quote_type::unquoted) { const string& n (t.value); if (n == "if") r = line_type::cmd_if; else if (n == "if!") r = line_type::cmd_ifn; else if (n == "elif") r = line_type::cmd_elif; else if (n == "elif!") r = line_type::cmd_elifn; else if (n == "else") r = line_type::cmd_else; else if (n == "end") r = line_type::cmd_end; else { // Switch the recognition of leading variable assignments for // the next token. This is safe to do because we know we // cannot be in the quoted mode (since the current token is // not quoted). // type p (peek (stm)); if (p == type::assign || p == type::prepend || p == type::append) { r = line_type::var; // Note that the missing command program is detected later, by // parse_command_expr(). // if (n.empty ()) fail (t) << "missing variable name"; } } } return r; } bool parser:: exec_lines (lines::const_iterator i, lines::const_iterator e, const function<exec_set_function>& exec_set, const function<exec_cmd_function>& exec_cmd, const function<exec_if_function>& exec_if, size_t& li, variable_pool* var_pool) { try { token t; type tt; for (; i != e; ++i) { const line& ln (*i); line_type lt (ln.type); assert (path_ == nullptr); // Copy the tokens and start playing. // replay_data (replay_tokens (ln.tokens)); // We don't really need to change the mode since we already know // the line type. // next (t, tt); const location ll (get_location (t)); switch (lt) { case line_type::var: { // Enter the variable into the pool if this is not done during // the script parsing. Note that in this case the pool is // expected to be provided. // const variable* var (ln.var); if (var == nullptr) { assert (var_pool != nullptr); var = &var_pool->insert (t.value); } exec_set (*var, t, tt, ll); replay_stop (); break; } case line_type::cmd: { bool single (false); if (li == 1) { lines::const_iterator j (i); for (++j; j != e && j->type == line_type::var; ++j) ; if (j == e) // We have no another command. single = true; } exec_cmd (t, tt, li++, single, ll); replay_stop (); break; } case line_type::cmd_if: case line_type::cmd_ifn: case line_type::cmd_elif: case line_type::cmd_elifn: case line_type::cmd_else: { next (t, tt); // Skip to start of command. bool take; if (lt != line_type::cmd_else) { take = exec_if (t, tt, li++, ll); if (lt == line_type::cmd_ifn || lt == line_type::cmd_elifn) take = !take; } else { assert (tt == type::newline); take = true; } replay_stop (); // If end is true, then find the 'end' line. Otherwise, find // the next if-else line. If skip is true then increment the // command line index. // auto next = [e, &li] (lines::const_iterator j, bool end, bool skip) -> lines::const_iterator { // We need to be aware of nested if-else chains. // size_t n (0); for (++j; j != e; ++j) { line_type lt (j->type); if (lt == line_type::cmd_if || lt == line_type::cmd_ifn) ++n; // If we are nested then we just wait until we get back // to the surface. // if (n == 0) { switch (lt) { case line_type::cmd_elif: case line_type::cmd_elifn: case line_type::cmd_else: if (end) break; // Fall through. case line_type::cmd_end: return j; default: break; } } if (lt == line_type::cmd_end) --n; if (skip) { // Note that we don't count else and end as commands. // switch (lt) { case line_type::cmd: case line_type::cmd_if: case line_type::cmd_ifn: case line_type::cmd_elif: case line_type::cmd_elifn: ++li; break; default: break; } } } assert (false); // Missing end. return e; }; // If we are taking this branch then we need to parse all the // lines until the next if-else line and then skip all the // lines until the end (unless next is already end). // // Otherwise, we need to skip all the lines until the next // if-else line and then continue parsing. // if (take) { // Next if-else. // lines::const_iterator j (next (i, false, false)); if (!exec_lines (i + 1, j, exec_set, exec_cmd, exec_if, li, var_pool)) return false; i = j->type == line_type::cmd_end ? j : next (j, true, true); } else { i = next (i, false, true); if (i->type != line_type::cmd_end) --i; // Continue with this line (e.g., elif or else). } break; } case line_type::cmd_end: { assert (false); } } } return true; } catch (const exit& e) { // Bail out if the script is exited with the failure status. Otherwise // exit the lines execution normally. // if (!e.status) throw failed (); replay_stop (); return false; } } // parser::parsed_doc // parser::parsed_doc:: parsed_doc (string s, uint64_t l, uint64_t c) : str (move (s)), re (false), end_line (l), end_column (c) { } parser::parsed_doc:: parsed_doc (regex_lines&& r, uint64_t l, uint64_t c) : regex (move (r)), re (true), end_line (l), end_column (c) { } parser::parsed_doc:: parsed_doc (parsed_doc&& d) : re (d.re), end_line (d.end_line), end_column (d.end_column) { if (re) new (&regex) regex_lines (move (d.regex)); else new (&str) string (move (d.str)); } parser::parsed_doc:: ~parsed_doc () { if (re) regex.~regex_lines (); else str.~string (); } } }
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "v8.h" #include "accessors.h" #include "api.h" #include "bootstrapper.h" #include "codegen.h" #include "compilation-cache.h" #include "conversions.h" #include "cpu-profiler.h" #include "debug.h" #include "deoptimizer.h" #include "global-handles.h" #include "heap-profiler.h" #include "incremental-marking.h" #include "isolate-inl.h" #include "mark-compact.h" #include "natives.h" #include "objects-visiting.h" #include "objects-visiting-inl.h" #include "once.h" #include "runtime-profiler.h" #include "scopeinfo.h" #include "snapshot.h" #include "store-buffer.h" #include "utils/random-number-generator.h" #include "utils.h" #include "v8threads.h" #include "vm-state-inl.h" #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP #include "regexp-macro-assembler.h" #include "arm/regexp-macro-assembler-arm.h" #endif #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP #include "regexp-macro-assembler.h" #include "mips/regexp-macro-assembler-mips.h" #endif namespace v8 { namespace internal { Heap::Heap() : isolate_(NULL), code_range_size_(0), // semispace_size_ should be a power of 2 and old_generation_size_ should be // a multiple of Page::kPageSize. reserved_semispace_size_(8 * (kPointerSize / 4) * MB), max_semispace_size_(8 * (kPointerSize / 4) * MB), initial_semispace_size_(Page::kPageSize), max_old_generation_size_(700ul * (kPointerSize / 4) * MB), max_executable_size_(256ul * (kPointerSize / 4) * MB), // Variables set based on semispace_size_ and old_generation_size_ in // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_) // Will be 4 * reserved_semispace_size_ to ensure that young // generation can be aligned to its size. maximum_committed_(0), survived_since_last_expansion_(0), sweep_generation_(0), always_allocate_scope_depth_(0), linear_allocation_scope_depth_(0), contexts_disposed_(0), global_ic_age_(0), flush_monomorphic_ics_(false), scan_on_scavenge_pages_(0), new_space_(this), old_pointer_space_(NULL), old_data_space_(NULL), code_space_(NULL), map_space_(NULL), cell_space_(NULL), property_cell_space_(NULL), lo_space_(NULL), gc_state_(NOT_IN_GC), gc_post_processing_depth_(0), ms_count_(0), gc_count_(0), remembered_unmapped_pages_index_(0), unflattened_strings_length_(0), #ifdef DEBUG allocation_timeout_(0), #endif // DEBUG new_space_high_promotion_mode_active_(false), old_generation_allocation_limit_(kMinimumOldGenerationAllocationLimit), external_allocation_limit_(0), amount_of_external_allocated_memory_(0), amount_of_external_allocated_memory_at_last_global_gc_(0), old_gen_exhausted_(false), inline_allocation_disabled_(false), store_buffer_rebuilder_(store_buffer()), hidden_string_(NULL), gc_safe_size_of_old_object_(NULL), total_regexp_code_generated_(0), tracer_(NULL), young_survivors_after_last_gc_(0), high_survival_rate_period_length_(0), low_survival_rate_period_length_(0), survival_rate_(0), previous_survival_rate_trend_(Heap::STABLE), survival_rate_trend_(Heap::STABLE), max_gc_pause_(0.0), total_gc_time_ms_(0.0), max_alive_after_gc_(0), min_in_mutator_(kMaxInt), alive_after_last_gc_(0), last_gc_end_timestamp_(0.0), marking_time_(0.0), sweeping_time_(0.0), mark_compact_collector_(this), store_buffer_(this), marking_(this), incremental_marking_(this), number_idle_notifications_(0), last_idle_notification_gc_count_(0), last_idle_notification_gc_count_init_(false), mark_sweeps_since_idle_round_started_(0), gc_count_at_last_idle_gc_(0), scavenges_since_last_idle_round_(kIdleScavengeThreshold), full_codegen_bytes_generated_(0), crankshaft_codegen_bytes_generated_(0), gcs_since_last_deopt_(0), #ifdef VERIFY_HEAP no_weak_object_verification_scope_depth_(0), #endif allocation_sites_scratchpad_length_(0), promotion_queue_(this), configured_(false), external_string_table_(this), chunks_queued_for_free_(NULL), gc_callbacks_depth_(0) { // Allow build-time customization of the max semispace size. Building // V8 with snapshots and a non-default max semispace size is much // easier if you can define it as part of the build environment. #if defined(V8_MAX_SEMISPACE_SIZE) max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE; #endif // Ensure old_generation_size_ is a multiple of kPageSize. ASSERT(MB >= Page::kPageSize); memset(roots_, 0, sizeof(roots_[0]) * kRootListLength); native_contexts_list_ = NULL; array_buffers_list_ = Smi::FromInt(0); allocation_sites_list_ = Smi::FromInt(0); // Put a dummy entry in the remembered pages so we can find the list the // minidump even if there are no real unmapped pages. RememberUnmappedPage(NULL, false); ClearObjectStats(true); } intptr_t Heap::Capacity() { if (!HasBeenSetUp()) return 0; return new_space_.Capacity() + old_pointer_space_->Capacity() + old_data_space_->Capacity() + code_space_->Capacity() + map_space_->Capacity() + cell_space_->Capacity() + property_cell_space_->Capacity(); } intptr_t Heap::CommittedMemory() { if (!HasBeenSetUp()) return 0; return new_space_.CommittedMemory() + old_pointer_space_->CommittedMemory() + old_data_space_->CommittedMemory() + code_space_->CommittedMemory() + map_space_->CommittedMemory() + cell_space_->CommittedMemory() + property_cell_space_->CommittedMemory() + lo_space_->Size(); } size_t Heap::CommittedPhysicalMemory() { if (!HasBeenSetUp()) return 0; return new_space_.CommittedPhysicalMemory() + old_pointer_space_->CommittedPhysicalMemory() + old_data_space_->CommittedPhysicalMemory() + code_space_->CommittedPhysicalMemory() + map_space_->CommittedPhysicalMemory() + cell_space_->CommittedPhysicalMemory() + property_cell_space_->CommittedPhysicalMemory() + lo_space_->CommittedPhysicalMemory(); } intptr_t Heap::CommittedMemoryExecutable() { if (!HasBeenSetUp()) return 0; return isolate()->memory_allocator()->SizeExecutable(); } void Heap::UpdateMaximumCommitted() { if (!HasBeenSetUp()) return; intptr_t current_committed_memory = CommittedMemory(); if (current_committed_memory > maximum_committed_) { maximum_committed_ = current_committed_memory; } } intptr_t Heap::Available() { if (!HasBeenSetUp()) return 0; return new_space_.Available() + old_pointer_space_->Available() + old_data_space_->Available() + code_space_->Available() + map_space_->Available() + cell_space_->Available() + property_cell_space_->Available(); } bool Heap::HasBeenSetUp() { return old_pointer_space_ != NULL && old_data_space_ != NULL && code_space_ != NULL && map_space_ != NULL && cell_space_ != NULL && property_cell_space_ != NULL && lo_space_ != NULL; } int Heap::GcSafeSizeOfOldObject(HeapObject* object) { if (IntrusiveMarking::IsMarked(object)) { return IntrusiveMarking::SizeOfMarkedObject(object); } return object->SizeFromMap(object->map()); } GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space, const char** reason) { // Is global GC requested? if (space != NEW_SPACE) { isolate_->counters()->gc_compactor_caused_by_request()->Increment(); *reason = "GC in old space requested"; return MARK_COMPACTOR; } if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) { *reason = "GC in old space forced by flags"; return MARK_COMPACTOR; } // Is enough data promoted to justify a global GC? if (OldGenerationAllocationLimitReached()) { isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment(); *reason = "promotion limit reached"; return MARK_COMPACTOR; } // Have allocation in OLD and LO failed? if (old_gen_exhausted_) { isolate_->counters()-> gc_compactor_caused_by_oldspace_exhaustion()->Increment(); *reason = "old generations exhausted"; return MARK_COMPACTOR; } // Is there enough space left in OLD to guarantee that a scavenge can // succeed? // // Note that MemoryAllocator->MaxAvailable() undercounts the memory available // for object promotion. It counts only the bytes that the memory // allocator has not yet allocated from the OS and assigned to any space, // and does not count available bytes already in the old space or code // space. Undercounting is safe---we may get an unrequested full GC when // a scavenge would have succeeded. if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) { isolate_->counters()-> gc_compactor_caused_by_oldspace_exhaustion()->Increment(); *reason = "scavenge might not succeed"; return MARK_COMPACTOR; } // Default *reason = NULL; return SCAVENGER; } // TODO(1238405): Combine the infrastructure for --heap-stats and // --log-gc to avoid the complicated preprocessor and flag testing. void Heap::ReportStatisticsBeforeGC() { // Heap::ReportHeapStatistics will also log NewSpace statistics when // compiled --log-gc is set. The following logic is used to avoid // double logging. #ifdef DEBUG if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics(); if (FLAG_heap_stats) { ReportHeapStatistics("Before GC"); } else if (FLAG_log_gc) { new_space_.ReportStatistics(); } if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms(); #else if (FLAG_log_gc) { new_space_.CollectStatistics(); new_space_.ReportStatistics(); new_space_.ClearHistograms(); } #endif // DEBUG } void Heap::PrintShortHeapStatistics() { if (!FLAG_trace_gc_verbose) return; PrintPID("Memory allocator, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB\n", isolate_->memory_allocator()->Size() / KB, isolate_->memory_allocator()->Available() / KB); PrintPID("New space, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", new_space_.Size() / KB, new_space_.Available() / KB, new_space_.CommittedMemory() / KB); PrintPID("Old pointers, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", old_pointer_space_->SizeOfObjects() / KB, old_pointer_space_->Available() / KB, old_pointer_space_->CommittedMemory() / KB); PrintPID("Old data space, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", old_data_space_->SizeOfObjects() / KB, old_data_space_->Available() / KB, old_data_space_->CommittedMemory() / KB); PrintPID("Code space, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", code_space_->SizeOfObjects() / KB, code_space_->Available() / KB, code_space_->CommittedMemory() / KB); PrintPID("Map space, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", map_space_->SizeOfObjects() / KB, map_space_->Available() / KB, map_space_->CommittedMemory() / KB); PrintPID("Cell space, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", cell_space_->SizeOfObjects() / KB, cell_space_->Available() / KB, cell_space_->CommittedMemory() / KB); PrintPID("PropertyCell space, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", property_cell_space_->SizeOfObjects() / KB, property_cell_space_->Available() / KB, property_cell_space_->CommittedMemory() / KB); PrintPID("Large object space, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", lo_space_->SizeOfObjects() / KB, lo_space_->Available() / KB, lo_space_->CommittedMemory() / KB); PrintPID("All spaces, used: %6" V8_PTR_PREFIX "d KB" ", available: %6" V8_PTR_PREFIX "d KB" ", committed: %6" V8_PTR_PREFIX "d KB\n", this->SizeOfObjects() / KB, this->Available() / KB, this->CommittedMemory() / KB); PrintPID("External memory reported: %6" V8_PTR_PREFIX "d KB\n", static_cast<intptr_t>(amount_of_external_allocated_memory_ / KB)); PrintPID("Total time spent in GC : %.1f ms\n", total_gc_time_ms_); } // TODO(1238405): Combine the infrastructure for --heap-stats and // --log-gc to avoid the complicated preprocessor and flag testing. void Heap::ReportStatisticsAfterGC() { // Similar to the before GC, we use some complicated logic to ensure that // NewSpace statistics are logged exactly once when --log-gc is turned on. #if defined(DEBUG) if (FLAG_heap_stats) { new_space_.CollectStatistics(); ReportHeapStatistics("After GC"); } else if (FLAG_log_gc) { new_space_.ReportStatistics(); } #else if (FLAG_log_gc) new_space_.ReportStatistics(); #endif // DEBUG } void Heap::GarbageCollectionPrologue() { { AllowHeapAllocation for_the_first_part_of_prologue; ClearJSFunctionResultCaches(); gc_count_++; unflattened_strings_length_ = 0; if (FLAG_flush_code && FLAG_flush_code_incrementally) { mark_compact_collector()->EnableCodeFlushing(true); } #ifdef VERIFY_HEAP if (FLAG_verify_heap) { Verify(); } #endif } UpdateMaximumCommitted(); #ifdef DEBUG ASSERT(!AllowHeapAllocation::IsAllowed() && gc_state_ == NOT_IN_GC); if (FLAG_gc_verbose) Print(); ReportStatisticsBeforeGC(); #endif // DEBUG store_buffer()->GCPrologue(); if (isolate()->concurrent_osr_enabled()) { isolate()->optimizing_compiler_thread()->AgeBufferedOsrJobs(); } } intptr_t Heap::SizeOfObjects() { intptr_t total = 0; AllSpaces spaces(this); for (Space* space = spaces.next(); space != NULL; space = spaces.next()) { total += space->SizeOfObjects(); } return total; } void Heap::ClearAllICsByKind(Code::Kind kind) { HeapObjectIterator it(code_space()); for (Object* object = it.Next(); object != NULL; object = it.Next()) { Code* code = Code::cast(object); Code::Kind current_kind = code->kind(); if (current_kind == Code::FUNCTION || current_kind == Code::OPTIMIZED_FUNCTION) { code->ClearInlineCaches(kind); } } } void Heap::RepairFreeListsAfterBoot() { PagedSpaces spaces(this); for (PagedSpace* space = spaces.next(); space != NULL; space = spaces.next()) { space->RepairFreeListsAfterBoot(); } } void Heap::ProcessPretenuringFeedback() { if (FLAG_allocation_site_pretenuring) { int tenure_decisions = 0; int dont_tenure_decisions = 0; int allocation_mementos_found = 0; int allocation_sites = 0; int active_allocation_sites = 0; // If the scratchpad overflowed, we have to iterate over the allocation // sites list. bool use_scratchpad = allocation_sites_scratchpad_length_ < kAllocationSiteScratchpadSize; int i = 0; Object* list_element = allocation_sites_list(); bool trigger_deoptimization = false; while (use_scratchpad ? i < allocation_sites_scratchpad_length_ : list_element->IsAllocationSite()) { AllocationSite* site = use_scratchpad ? AllocationSite::cast(allocation_sites_scratchpad()->get(i)) : AllocationSite::cast(list_element); allocation_mementos_found += site->memento_found_count(); if (site->memento_found_count() > 0) { active_allocation_sites++; } if (site->DigestPretenuringFeedback()) trigger_deoptimization = true; if (site->GetPretenureMode() == TENURED) { tenure_decisions++; } else { dont_tenure_decisions++; } allocation_sites++; if (use_scratchpad) { i++; } else { list_element = site->weak_next(); } } if (trigger_deoptimization) { isolate_->stack_guard()->DeoptMarkedAllocationSites(); } FlushAllocationSitesScratchpad(); if (FLAG_trace_pretenuring_statistics && (allocation_mementos_found > 0 || tenure_decisions > 0 || dont_tenure_decisions > 0)) { PrintF("GC: (mode, #visited allocation sites, #active allocation sites, " "#mementos, #tenure decisions, #donttenure decisions) " "(%s, %d, %d, %d, %d, %d)\n", use_scratchpad ? "use scratchpad" : "use list", allocation_sites, active_allocation_sites, allocation_mementos_found, tenure_decisions, dont_tenure_decisions); } } } void Heap::DeoptMarkedAllocationSites() { // TODO(hpayer): If iterating over the allocation sites list becomes a // performance issue, use a cache heap data structure instead (similar to the // allocation sites scratchpad). Object* list_element = allocation_sites_list(); while (list_element->IsAllocationSite()) { AllocationSite* site = AllocationSite::cast(list_element); if (site->deopt_dependent_code()) { site->dependent_code()->MarkCodeForDeoptimization( isolate_, DependentCode::kAllocationSiteTenuringChangedGroup); site->set_deopt_dependent_code(false); } list_element = site->weak_next(); } Deoptimizer::DeoptimizeMarkedCode(isolate_); } void Heap::GarbageCollectionEpilogue() { store_buffer()->GCEpilogue(); // In release mode, we only zap the from space under heap verification. if (Heap::ShouldZapGarbage()) { ZapFromSpace(); } // Process pretenuring feedback and update allocation sites. ProcessPretenuringFeedback(); #ifdef VERIFY_HEAP if (FLAG_verify_heap) { Verify(); } #endif AllowHeapAllocation for_the_rest_of_the_epilogue; #ifdef DEBUG if (FLAG_print_global_handles) isolate_->global_handles()->Print(); if (FLAG_print_handles) PrintHandles(); if (FLAG_gc_verbose) Print(); if (FLAG_code_stats) ReportCodeStatistics("After GC"); #endif if (FLAG_deopt_every_n_garbage_collections > 0) { // TODO(jkummerow/ulan/jarin): This is not safe! We can't assume that // the topmost optimized frame can be deoptimized safely, because it // might not have a lazy bailout point right after its current PC. if (++gcs_since_last_deopt_ == FLAG_deopt_every_n_garbage_collections) { Deoptimizer::DeoptimizeAll(isolate()); gcs_since_last_deopt_ = 0; } } UpdateMaximumCommitted(); isolate_->counters()->alive_after_last_gc()->Set( static_cast<int>(SizeOfObjects())); isolate_->counters()->string_table_capacity()->Set( string_table()->Capacity()); isolate_->counters()->number_of_symbols()->Set( string_table()->NumberOfElements()); if (full_codegen_bytes_generated_ + crankshaft_codegen_bytes_generated_ > 0) { isolate_->counters()->codegen_fraction_crankshaft()->AddSample( static_cast<int>((crankshaft_codegen_bytes_generated_ * 100.0) / (crankshaft_codegen_bytes_generated_ + full_codegen_bytes_generated_))); } if (CommittedMemory() > 0) { isolate_->counters()->external_fragmentation_total()->AddSample( static_cast<int>(100 - (SizeOfObjects() * 100.0) / CommittedMemory())); isolate_->counters()->heap_fraction_new_space()-> AddSample(static_cast<int>( (new_space()->CommittedMemory() * 100.0) / CommittedMemory())); isolate_->counters()->heap_fraction_old_pointer_space()->AddSample( static_cast<int>( (old_pointer_space()->CommittedMemory() * 100.0) / CommittedMemory())); isolate_->counters()->heap_fraction_old_data_space()->AddSample( static_cast<int>( (old_data_space()->CommittedMemory() * 100.0) / CommittedMemory())); isolate_->counters()->heap_fraction_code_space()-> AddSample(static_cast<int>( (code_space()->CommittedMemory() * 100.0) / CommittedMemory())); isolate_->counters()->heap_fraction_map_space()->AddSample( static_cast<int>( (map_space()->CommittedMemory() * 100.0) / CommittedMemory())); isolate_->counters()->heap_fraction_cell_space()->AddSample( static_cast<int>( (cell_space()->CommittedMemory() * 100.0) / CommittedMemory())); isolate_->counters()->heap_fraction_property_cell_space()-> AddSample(static_cast<int>( (property_cell_space()->CommittedMemory() * 100.0) / CommittedMemory())); isolate_->counters()->heap_fraction_lo_space()-> AddSample(static_cast<int>( (lo_space()->CommittedMemory() * 100.0) / CommittedMemory())); isolate_->counters()->heap_sample_total_committed()->AddSample( static_cast<int>(CommittedMemory() / KB)); isolate_->counters()->heap_sample_total_used()->AddSample( static_cast<int>(SizeOfObjects() / KB)); isolate_->counters()->heap_sample_map_space_committed()->AddSample( static_cast<int>(map_space()->CommittedMemory() / KB)); isolate_->counters()->heap_sample_cell_space_committed()->AddSample( static_cast<int>(cell_space()->CommittedMemory() / KB)); isolate_->counters()-> heap_sample_property_cell_space_committed()-> AddSample(static_cast<int>( property_cell_space()->CommittedMemory() / KB)); isolate_->counters()->heap_sample_code_space_committed()->AddSample( static_cast<int>(code_space()->CommittedMemory() / KB)); isolate_->counters()->heap_sample_maximum_committed()->AddSample( static_cast<int>(MaximumCommittedMemory() / KB)); } #define UPDATE_COUNTERS_FOR_SPACE(space) \ isolate_->counters()->space##_bytes_available()->Set( \ static_cast<int>(space()->Available())); \ isolate_->counters()->space##_bytes_committed()->Set( \ static_cast<int>(space()->CommittedMemory())); \ isolate_->counters()->space##_bytes_used()->Set( \ static_cast<int>(space()->SizeOfObjects())); #define UPDATE_FRAGMENTATION_FOR_SPACE(space) \ if (space()->CommittedMemory() > 0) { \ isolate_->counters()->external_fragmentation_##space()->AddSample( \ static_cast<int>(100 - \ (space()->SizeOfObjects() * 100.0) / space()->CommittedMemory())); \ } #define UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(space) \ UPDATE_COUNTERS_FOR_SPACE(space) \ UPDATE_FRAGMENTATION_FOR_SPACE(space) UPDATE_COUNTERS_FOR_SPACE(new_space) UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_pointer_space) UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_data_space) UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(code_space) UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(map_space) UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(cell_space) UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(property_cell_space) UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(lo_space) #undef UPDATE_COUNTERS_FOR_SPACE #undef UPDATE_FRAGMENTATION_FOR_SPACE #undef UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE #ifdef DEBUG ReportStatisticsAfterGC(); #endif // DEBUG isolate_->debug()->AfterGarbageCollection(); } void Heap::CollectAllGarbage(int flags, const char* gc_reason, const v8::GCCallbackFlags gc_callback_flags) { // Since we are ignoring the return value, the exact choice of space does // not matter, so long as we do not specify NEW_SPACE, which would not // cause a full GC. mark_compact_collector_.SetFlags(flags); CollectGarbage(OLD_POINTER_SPACE, gc_reason, gc_callback_flags); mark_compact_collector_.SetFlags(kNoGCFlags); } void Heap::CollectAllAvailableGarbage(const char* gc_reason) { // Since we are ignoring the return value, the exact choice of space does // not matter, so long as we do not specify NEW_SPACE, which would not // cause a full GC. // Major GC would invoke weak handle callbacks on weakly reachable // handles, but won't collect weakly reachable objects until next // major GC. Therefore if we collect aggressively and weak handle callback // has been invoked, we rerun major GC to release objects which become // garbage. // Note: as weak callbacks can execute arbitrary code, we cannot // hope that eventually there will be no weak callbacks invocations. // Therefore stop recollecting after several attempts. if (isolate()->concurrent_recompilation_enabled()) { // The optimizing compiler may be unnecessarily holding on to memory. DisallowHeapAllocation no_recursive_gc; isolate()->optimizing_compiler_thread()->Flush(); } mark_compact_collector()->SetFlags(kMakeHeapIterableMask | kReduceMemoryFootprintMask); isolate_->compilation_cache()->Clear(); const int kMaxNumberOfAttempts = 7; const int kMinNumberOfAttempts = 2; for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) { if (!CollectGarbage(MARK_COMPACTOR, gc_reason, NULL) && attempt + 1 >= kMinNumberOfAttempts) { break; } } mark_compact_collector()->SetFlags(kNoGCFlags); new_space_.Shrink(); UncommitFromSpace(); incremental_marking()->UncommitMarkingDeque(); } void Heap::EnsureFillerObjectAtTop() { // There may be an allocation memento behind every object in new space. // If we evacuate a not full new space or if we are on the last page of // the new space, then there may be uninitialized memory behind the top // pointer of the new space page. We store a filler object there to // identify the unused space. Address from_top = new_space_.top(); Address from_limit = new_space_.limit(); if (from_top < from_limit) { int remaining_in_page = static_cast<int>(from_limit - from_top); CreateFillerObjectAt(from_top, remaining_in_page); } } bool Heap::CollectGarbage(GarbageCollector collector, const char* gc_reason, const char* collector_reason, const v8::GCCallbackFlags gc_callback_flags) { // The VM is in the GC state until exiting this function. VMState<GC> state(isolate_); #ifdef DEBUG // Reset the allocation timeout to the GC interval, but make sure to // allow at least a few allocations after a collection. The reason // for this is that we have a lot of allocation sequences and we // assume that a garbage collection will allow the subsequent // allocation attempts to go through. allocation_timeout_ = Max(6, FLAG_gc_interval); #endif EnsureFillerObjectAtTop(); if (collector == SCAVENGER && !incremental_marking()->IsStopped()) { if (FLAG_trace_incremental_marking) { PrintF("[IncrementalMarking] Scavenge during marking.\n"); } } if (collector == MARK_COMPACTOR && !mark_compact_collector()->abort_incremental_marking() && !incremental_marking()->IsStopped() && !incremental_marking()->should_hurry() && FLAG_incremental_marking_steps) { // Make progress in incremental marking. const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB; incremental_marking()->Step(kStepSizeWhenDelayedByScavenge, IncrementalMarking::NO_GC_VIA_STACK_GUARD); if (!incremental_marking()->IsComplete()) { if (FLAG_trace_incremental_marking) { PrintF("[IncrementalMarking] Delaying MarkSweep.\n"); } collector = SCAVENGER; collector_reason = "incremental marking delaying mark-sweep"; } } bool next_gc_likely_to_collect_more = false; { GCTracer tracer(this, gc_reason, collector_reason); ASSERT(AllowHeapAllocation::IsAllowed()); DisallowHeapAllocation no_allocation_during_gc; GarbageCollectionPrologue(); // The GC count was incremented in the prologue. Tell the tracer about // it. tracer.set_gc_count(gc_count_); // Tell the tracer which collector we've selected. tracer.set_collector(collector); { HistogramTimerScope histogram_timer_scope( (collector == SCAVENGER) ? isolate_->counters()->gc_scavenger() : isolate_->counters()->gc_compactor()); next_gc_likely_to_collect_more = PerformGarbageCollection(collector, &tracer, gc_callback_flags); } GarbageCollectionEpilogue(); } // Start incremental marking for the next cycle. The heap snapshot // generator needs incremental marking to stay off after it aborted. if (!mark_compact_collector()->abort_incremental_marking() && incremental_marking()->IsStopped() && incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) { incremental_marking()->Start(); } return next_gc_likely_to_collect_more; } int Heap::NotifyContextDisposed() { if (isolate()->concurrent_recompilation_enabled()) { // Flush the queued recompilation tasks. isolate()->optimizing_compiler_thread()->Flush(); } flush_monomorphic_ics_ = true; AgeInlineCaches(); return ++contexts_disposed_; } void Heap::MoveElements(FixedArray* array, int dst_index, int src_index, int len) { if (len == 0) return; ASSERT(array->map() != fixed_cow_array_map()); Object** dst_objects = array->data_start() + dst_index; OS::MemMove(dst_objects, array->data_start() + src_index, len * kPointerSize); if (!InNewSpace(array)) { for (int i = 0; i < len; i++) { // TODO(hpayer): check store buffer for entries if (InNewSpace(dst_objects[i])) { RecordWrite(array->address(), array->OffsetOfElementAt(dst_index + i)); } } } incremental_marking()->RecordWrites(array); } #ifdef VERIFY_HEAP // Helper class for verifying the string table. class StringTableVerifier : public ObjectVisitor { public: void VisitPointers(Object** start, Object** end) { // Visit all HeapObject pointers in [start, end). for (Object** p = start; p < end; p++) { if ((*p)->IsHeapObject()) { // Check that the string is actually internalized. CHECK((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsInternalizedString()); } } } }; static void VerifyStringTable(Heap* heap) { StringTableVerifier verifier; heap->string_table()->IterateElements(&verifier); } #endif // VERIFY_HEAP static bool AbortIncrementalMarkingAndCollectGarbage( Heap* heap, AllocationSpace space, const char* gc_reason = NULL) { heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask); bool result = heap->CollectGarbage(space, gc_reason); heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags); return result; } void Heap::ReserveSpace(int *sizes, Address *locations_out) { bool gc_performed = true; int counter = 0; static const int kThreshold = 20; while (gc_performed && counter++ < kThreshold) { gc_performed = false; ASSERT(NEW_SPACE == FIRST_PAGED_SPACE - 1); for (int space = NEW_SPACE; space <= LAST_PAGED_SPACE; space++) { if (sizes[space] != 0) { AllocationResult allocation; if (space == NEW_SPACE) { allocation = new_space()->AllocateRaw(sizes[space]); } else { allocation = paged_space(space)->AllocateRaw(sizes[space]); } FreeListNode* node; if (!allocation.To(&node)) { if (space == NEW_SPACE) { Heap::CollectGarbage(NEW_SPACE, "failed to reserve space in the new space"); } else { AbortIncrementalMarkingAndCollectGarbage( this, static_cast<AllocationSpace>(space), "failed to reserve space in paged space"); } gc_performed = true; break; } else { // Mark with a free list node, in case we have a GC before // deserializing. node->set_size(this, sizes[space]); locations_out[space] = node->address(); } } } } if (gc_performed) { // Failed to reserve the space after several attempts. V8::FatalProcessOutOfMemory("Heap::ReserveSpace"); } } void Heap::EnsureFromSpaceIsCommitted() { if (new_space_.CommitFromSpaceIfNeeded()) return; // Committing memory to from space failed. // Memory is exhausted and we will die. V8::FatalProcessOutOfMemory("Committing semi space failed."); } void Heap::ClearJSFunctionResultCaches() { if (isolate_->bootstrapper()->IsActive()) return; Object* context = native_contexts_list_; while (!context->IsUndefined()) { // Get the caches for this context. GC can happen when the context // is not fully initialized, so the caches can be undefined. Object* caches_or_undefined = Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX); if (!caches_or_undefined->IsUndefined()) { FixedArray* caches = FixedArray::cast(caches_or_undefined); // Clear the caches: int length = caches->length(); for (int i = 0; i < length; i++) { JSFunctionResultCache::cast(caches->get(i))->Clear(); } } // Get the next context: context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK); } } void Heap::ClearNormalizedMapCaches() { if (isolate_->bootstrapper()->IsActive() && !incremental_marking()->IsMarking()) { return; } Object* context = native_contexts_list_; while (!context->IsUndefined()) { // GC can happen when the context is not fully initialized, // so the cache can be undefined. Object* cache = Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX); if (!cache->IsUndefined()) { NormalizedMapCache::cast(cache)->Clear(); } context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK); } } void Heap::UpdateSurvivalRateTrend(int start_new_space_size) { if (start_new_space_size == 0) return; double survival_rate = (static_cast<double>(young_survivors_after_last_gc_) * 100) / start_new_space_size; if (survival_rate > kYoungSurvivalRateHighThreshold) { high_survival_rate_period_length_++; } else { high_survival_rate_period_length_ = 0; } if (survival_rate < kYoungSurvivalRateLowThreshold) { low_survival_rate_period_length_++; } else { low_survival_rate_period_length_ = 0; } double survival_rate_diff = survival_rate_ - survival_rate; if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) { set_survival_rate_trend(DECREASING); } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) { set_survival_rate_trend(INCREASING); } else { set_survival_rate_trend(STABLE); } survival_rate_ = survival_rate; } bool Heap::PerformGarbageCollection( GarbageCollector collector, GCTracer* tracer, const v8::GCCallbackFlags gc_callback_flags) { int freed_global_handles = 0; if (collector != SCAVENGER) { PROFILE(isolate_, CodeMovingGCEvent()); } #ifdef VERIFY_HEAP if (FLAG_verify_heap) { VerifyStringTable(this); } #endif GCType gc_type = collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge; { GCCallbacksScope scope(this); if (scope.CheckReenter()) { AllowHeapAllocation allow_allocation; GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL); VMState<EXTERNAL> state(isolate_); HandleScope handle_scope(isolate_); CallGCPrologueCallbacks(gc_type, kNoGCCallbackFlags); } } EnsureFromSpaceIsCommitted(); int start_new_space_size = Heap::new_space()->SizeAsInt(); if (IsHighSurvivalRate()) { // We speed up the incremental marker if it is running so that it // does not fall behind the rate of promotion, which would cause a // constantly growing old space. incremental_marking()->NotifyOfHighPromotionRate(); } if (collector == MARK_COMPACTOR) { // Perform mark-sweep with optional compaction. MarkCompact(tracer); sweep_generation_++; UpdateSurvivalRateTrend(start_new_space_size); // Temporarily set the limit for case when PostGarbageCollectionProcessing // allocates and triggers GC. The real limit is set at after // PostGarbageCollectionProcessing. old_generation_allocation_limit_ = OldGenerationAllocationLimit(PromotedSpaceSizeOfObjects(), 0); old_gen_exhausted_ = false; } else { tracer_ = tracer; Scavenge(); tracer_ = NULL; UpdateSurvivalRateTrend(start_new_space_size); } if (!new_space_high_promotion_mode_active_ && new_space_.Capacity() == new_space_.MaximumCapacity() && IsStableOrIncreasingSurvivalTrend() && IsHighSurvivalRate()) { // Stable high survival rates even though young generation is at // maximum capacity indicates that most objects will be promoted. // To decrease scavenger pauses and final mark-sweep pauses, we // have to limit maximal capacity of the young generation. SetNewSpaceHighPromotionModeActive(true); if (FLAG_trace_gc) { PrintPID("Limited new space size due to high promotion rate: %d MB\n", new_space_.InitialCapacity() / MB); } // The high promotion mode is our indicator to turn on pretenuring. We have // to deoptimize all optimized code in global pretenuring mode and all // code which should be tenured in local pretenuring mode. if (FLAG_pretenuring) { if (!FLAG_allocation_site_pretenuring) { isolate_->stack_guard()->FullDeopt(); } } } else if (new_space_high_promotion_mode_active_ && IsStableOrDecreasingSurvivalTrend() && IsLowSurvivalRate()) { // Decreasing low survival rates might indicate that the above high // promotion mode is over and we should allow the young generation // to grow again. SetNewSpaceHighPromotionModeActive(false); if (FLAG_trace_gc) { PrintPID("Unlimited new space size due to low promotion rate: %d MB\n", new_space_.MaximumCapacity() / MB); } // Trigger deoptimization here to turn off global pretenuring as soon as // possible. if (FLAG_pretenuring && !FLAG_allocation_site_pretenuring) { isolate_->stack_guard()->FullDeopt(); } } if (new_space_high_promotion_mode_active_ && new_space_.Capacity() > new_space_.InitialCapacity()) { new_space_.Shrink(); } isolate_->counters()->objs_since_last_young()->Set(0); // Callbacks that fire after this point might trigger nested GCs and // restart incremental marking, the assertion can't be moved down. ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped()); gc_post_processing_depth_++; { AllowHeapAllocation allow_allocation; GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL); freed_global_handles = isolate_->global_handles()->PostGarbageCollectionProcessing( collector, tracer); } gc_post_processing_depth_--; isolate_->eternal_handles()->PostGarbageCollectionProcessing(this); // Update relocatables. Relocatable::PostGarbageCollectionProcessing(isolate_); if (collector == MARK_COMPACTOR) { // Register the amount of external allocated memory. amount_of_external_allocated_memory_at_last_global_gc_ = amount_of_external_allocated_memory_; old_generation_allocation_limit_ = OldGenerationAllocationLimit(PromotedSpaceSizeOfObjects(), freed_global_handles); } { GCCallbacksScope scope(this); if (scope.CheckReenter()) { AllowHeapAllocation allow_allocation; GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL); VMState<EXTERNAL> state(isolate_); HandleScope handle_scope(isolate_); CallGCEpilogueCallbacks(gc_type, gc_callback_flags); } } #ifdef VERIFY_HEAP if (FLAG_verify_heap) { VerifyStringTable(this); } #endif return freed_global_handles > 0; } void Heap::CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags) { for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) { if (gc_type & gc_prologue_callbacks_[i].gc_type) { if (!gc_prologue_callbacks_[i].pass_isolate_) { v8::GCPrologueCallback callback = reinterpret_cast<v8::GCPrologueCallback>( gc_prologue_callbacks_[i].callback); callback(gc_type, flags); } else { v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this->isolate()); gc_prologue_callbacks_[i].callback(isolate, gc_type, flags); } } } } void Heap::CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags gc_callback_flags) { for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) { if (gc_type & gc_epilogue_callbacks_[i].gc_type) { if (!gc_epilogue_callbacks_[i].pass_isolate_) { v8::GCPrologueCallback callback = reinterpret_cast<v8::GCPrologueCallback>( gc_epilogue_callbacks_[i].callback); callback(gc_type, gc_callback_flags); } else { v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this->isolate()); gc_epilogue_callbacks_[i].callback( isolate, gc_type, gc_callback_flags); } } } } void Heap::MarkCompact(GCTracer* tracer) { gc_state_ = MARK_COMPACT; LOG(isolate_, ResourceEvent("markcompact", "begin")); uint64_t size_of_objects_before_gc = SizeOfObjects(); mark_compact_collector_.Prepare(tracer); ms_count_++; tracer->set_full_gc_count(ms_count_); MarkCompactPrologue(); mark_compact_collector_.CollectGarbage(); LOG(isolate_, ResourceEvent("markcompact", "end")); gc_state_ = NOT_IN_GC; isolate_->counters()->objs_since_last_full()->Set(0); flush_monomorphic_ics_ = false; if (FLAG_allocation_site_pretenuring) { EvaluateOldSpaceLocalPretenuring(size_of_objects_before_gc); } } void Heap::MarkCompactPrologue() { // At any old GC clear the keyed lookup cache to enable collection of unused // maps. isolate_->keyed_lookup_cache()->Clear(); isolate_->context_slot_cache()->Clear(); isolate_->descriptor_lookup_cache()->Clear(); RegExpResultsCache::Clear(string_split_cache()); RegExpResultsCache::Clear(regexp_multiple_cache()); isolate_->compilation_cache()->MarkCompactPrologue(); CompletelyClearInstanceofCache(); FlushNumberStringCache(); if (FLAG_cleanup_code_caches_at_gc) { polymorphic_code_cache()->set_cache(undefined_value()); } ClearNormalizedMapCaches(); } // Helper class for copying HeapObjects class ScavengeVisitor: public ObjectVisitor { public: explicit ScavengeVisitor(Heap* heap) : heap_(heap) {} void VisitPointer(Object** p) { ScavengePointer(p); } void VisitPointers(Object** start, Object** end) { // Copy all HeapObject pointers in [start, end) for (Object** p = start; p < end; p++) ScavengePointer(p); } private: void ScavengePointer(Object** p) { Object* object = *p; if (!heap_->InNewSpace(object)) return; Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p), reinterpret_cast<HeapObject*>(object)); } Heap* heap_; }; #ifdef VERIFY_HEAP // Visitor class to verify pointers in code or data space do not point into // new space. class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor { public: explicit VerifyNonPointerSpacePointersVisitor(Heap* heap) : heap_(heap) {} void VisitPointers(Object** start, Object**end) { for (Object** current = start; current < end; current++) { if ((*current)->IsHeapObject()) { CHECK(!heap_->InNewSpace(HeapObject::cast(*current))); } } } private: Heap* heap_; }; static void VerifyNonPointerSpacePointers(Heap* heap) { // Verify that there are no pointers to new space in spaces where we // do not expect them. VerifyNonPointerSpacePointersVisitor v(heap); HeapObjectIterator code_it(heap->code_space()); for (HeapObject* object = code_it.Next(); object != NULL; object = code_it.Next()) object->Iterate(&v); // The old data space was normally swept conservatively so that the iterator // doesn't work, so we normally skip the next bit. if (!heap->old_data_space()->was_swept_conservatively()) { HeapObjectIterator data_it(heap->old_data_space()); for (HeapObject* object = data_it.Next(); object != NULL; object = data_it.Next()) object->Iterate(&v); } } #endif // VERIFY_HEAP void Heap::CheckNewSpaceExpansionCriteria() { if (new_space_.Capacity() < new_space_.MaximumCapacity() && survived_since_last_expansion_ > new_space_.Capacity() && !new_space_high_promotion_mode_active_) { // Grow the size of new space if there is room to grow, enough data // has survived scavenge since the last expansion and we are not in // high promotion mode. new_space_.Grow(); survived_since_last_expansion_ = 0; } } static bool IsUnscavengedHeapObject(Heap* heap, Object** p) { return heap->InNewSpace(*p) && !HeapObject::cast(*p)->map_word().IsForwardingAddress(); } void Heap::ScavengeStoreBufferCallback( Heap* heap, MemoryChunk* page, StoreBufferEvent event) { heap->store_buffer_rebuilder_.Callback(page, event); } void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) { if (event == kStoreBufferStartScanningPagesEvent) { start_of_current_page_ = NULL; current_page_ = NULL; } else if (event == kStoreBufferScanningPageEvent) { if (current_page_ != NULL) { // If this page already overflowed the store buffer during this iteration. if (current_page_->scan_on_scavenge()) { // Then we should wipe out the entries that have been added for it. store_buffer_->SetTop(start_of_current_page_); } else if (store_buffer_->Top() - start_of_current_page_ >= (store_buffer_->Limit() - store_buffer_->Top()) >> 2) { // Did we find too many pointers in the previous page? The heuristic is // that no page can take more then 1/5 the remaining slots in the store // buffer. current_page_->set_scan_on_scavenge(true); store_buffer_->SetTop(start_of_current_page_); } else { // In this case the page we scanned took a reasonable number of slots in // the store buffer. It has now been rehabilitated and is no longer // marked scan_on_scavenge. ASSERT(!current_page_->scan_on_scavenge()); } } start_of_current_page_ = store_buffer_->Top(); current_page_ = page; } else if (event == kStoreBufferFullEvent) { // The current page overflowed the store buffer again. Wipe out its entries // in the store buffer and mark it scan-on-scavenge again. This may happen // several times while scanning. if (current_page_ == NULL) { // Store Buffer overflowed while scanning promoted objects. These are not // in any particular page, though they are likely to be clustered by the // allocation routines. store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize / 2); } else { // Store Buffer overflowed while scanning a particular old space page for // pointers to new space. ASSERT(current_page_ == page); ASSERT(page != NULL); current_page_->set_scan_on_scavenge(true); ASSERT(start_of_current_page_ != store_buffer_->Top()); store_buffer_->SetTop(start_of_current_page_); } } else { UNREACHABLE(); } } void PromotionQueue::Initialize() { // Assumes that a NewSpacePage exactly fits a number of promotion queue // entries (where each is a pair of intptr_t). This allows us to simplify // the test fpr when to switch pages. ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize) == 0); limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart()); front_ = rear_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd()); emergency_stack_ = NULL; guard_ = false; } void PromotionQueue::RelocateQueueHead() { ASSERT(emergency_stack_ == NULL); Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_)); intptr_t* head_start = rear_; intptr_t* head_end = Min(front_, reinterpret_cast<intptr_t*>(p->area_end())); int entries_count = static_cast<int>(head_end - head_start) / kEntrySizeInWords; emergency_stack_ = new List<Entry>(2 * entries_count); while (head_start != head_end) { int size = static_cast<int>(*(head_start++)); HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++)); emergency_stack_->Add(Entry(obj, size)); } rear_ = head_end; } class ScavengeWeakObjectRetainer : public WeakObjectRetainer { public: explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) { } virtual Object* RetainAs(Object* object) { if (!heap_->InFromSpace(object)) { return object; } MapWord map_word = HeapObject::cast(object)->map_word(); if (map_word.IsForwardingAddress()) { return map_word.ToForwardingAddress(); } return NULL; } private: Heap* heap_; }; void Heap::Scavenge() { RelocationLock relocation_lock(this); #ifdef VERIFY_HEAP if (FLAG_verify_heap) VerifyNonPointerSpacePointers(this); #endif gc_state_ = SCAVENGE; // Implements Cheney's copying algorithm LOG(isolate_, ResourceEvent("scavenge", "begin")); // Clear descriptor cache. isolate_->descriptor_lookup_cache()->Clear(); // Used for updating survived_since_last_expansion_ at function end. intptr_t survived_watermark = PromotedSpaceSizeOfObjects(); CheckNewSpaceExpansionCriteria(); SelectScavengingVisitorsTable(); incremental_marking()->PrepareForScavenge(); // Flip the semispaces. After flipping, to space is empty, from space has // live objects. new_space_.Flip(); new_space_.ResetAllocationInfo(); // We need to sweep newly copied objects which can be either in the // to space or promoted to the old generation. For to-space // objects, we treat the bottom of the to space as a queue. Newly // copied and unswept objects lie between a 'front' mark and the // allocation pointer. // // Promoted objects can go into various old-generation spaces, and // can be allocated internally in the spaces (from the free list). // We treat the top of the to space as a queue of addresses of // promoted objects. The addresses of newly promoted and unswept // objects lie between a 'front' mark and a 'rear' mark that is // updated as a side effect of promoting an object. // // There is guaranteed to be enough room at the top of the to space // for the addresses of promoted objects: every object promoted // frees up its size in bytes from the top of the new space, and // objects are at least one pointer in size. Address new_space_front = new_space_.ToSpaceStart(); promotion_queue_.Initialize(); #ifdef DEBUG store_buffer()->Clean(); #endif ScavengeVisitor scavenge_visitor(this); // Copy roots. IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE); // Copy objects reachable from the old generation. { StoreBufferRebuildScope scope(this, store_buffer(), &ScavengeStoreBufferCallback); store_buffer()->IteratePointersToNewSpace(&ScavengeObject); } // Copy objects reachable from simple cells by scavenging cell values // directly. HeapObjectIterator cell_iterator(cell_space_); for (HeapObject* heap_object = cell_iterator.Next(); heap_object != NULL; heap_object = cell_iterator.Next()) { if (heap_object->IsCell()) { Cell* cell = Cell::cast(heap_object); Address value_address = cell->ValueAddress(); scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address)); } } // Copy objects reachable from global property cells by scavenging global // property cell values directly. HeapObjectIterator js_global_property_cell_iterator(property_cell_space_); for (HeapObject* heap_object = js_global_property_cell_iterator.Next(); heap_object != NULL; heap_object = js_global_property_cell_iterator.Next()) { if (heap_object->IsPropertyCell()) { PropertyCell* cell = PropertyCell::cast(heap_object); Address value_address = cell->ValueAddress(); scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address)); Address type_address = cell->TypeAddress(); scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(type_address)); } } // Copy objects reachable from the code flushing candidates list. MarkCompactCollector* collector = mark_compact_collector(); if (collector->is_code_flushing_enabled()) { collector->code_flusher()->IteratePointersToFromSpace(&scavenge_visitor); } // Scavenge object reachable from the native contexts list directly. scavenge_visitor.VisitPointer(BitCast<Object**>(&native_contexts_list_)); new_space_front = DoScavenge(&scavenge_visitor, new_space_front); while (isolate()->global_handles()->IterateObjectGroups( &scavenge_visitor, &IsUnscavengedHeapObject)) { new_space_front = DoScavenge(&scavenge_visitor, new_space_front); } isolate()->global_handles()->RemoveObjectGroups(); isolate()->global_handles()->RemoveImplicitRefGroups(); isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles( &IsUnscavengedHeapObject); isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots( &scavenge_visitor); new_space_front = DoScavenge(&scavenge_visitor, new_space_front); UpdateNewSpaceReferencesInExternalStringTable( &UpdateNewSpaceReferenceInExternalStringTableEntry); promotion_queue_.Destroy(); incremental_marking()->UpdateMarkingDequeAfterScavenge(); ScavengeWeakObjectRetainer weak_object_retainer(this); ProcessWeakReferences(&weak_object_retainer); ASSERT(new_space_front == new_space_.top()); // Set age mark. new_space_.set_age_mark(new_space_.top()); new_space_.LowerInlineAllocationLimit( new_space_.inline_allocation_limit_step()); // Update how much has survived scavenge. IncrementYoungSurvivorsCounter(static_cast<int>( (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size())); LOG(isolate_, ResourceEvent("scavenge", "end")); gc_state_ = NOT_IN_GC; scavenges_since_last_idle_round_++; } String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap, Object** p) { MapWord first_word = HeapObject::cast(*p)->map_word(); if (!first_word.IsForwardingAddress()) { // Unreachable external string can be finalized. heap->FinalizeExternalString(String::cast(*p)); return NULL; } // String is still reachable. return String::cast(first_word.ToForwardingAddress()); } void Heap::UpdateNewSpaceReferencesInExternalStringTable( ExternalStringTableUpdaterCallback updater_func) { #ifdef VERIFY_HEAP if (FLAG_verify_heap) { external_string_table_.Verify(); } #endif if (external_string_table_.new_space_strings_.is_empty()) return; Object** start = &external_string_table_.new_space_strings_[0]; Object** end = start + external_string_table_.new_space_strings_.length(); Object** last = start; for (Object** p = start; p < end; ++p) { ASSERT(InFromSpace(*p)); String* target = updater_func(this, p); if (target == NULL) continue; ASSERT(target->IsExternalString()); if (InNewSpace(target)) { // String is still in new space. Update the table entry. *last = target; ++last; } else { // String got promoted. Move it to the old string list. external_string_table_.AddOldString(target); } } ASSERT(last <= end); external_string_table_.ShrinkNewStrings(static_cast<int>(last - start)); } void Heap::UpdateReferencesInExternalStringTable( ExternalStringTableUpdaterCallback updater_func) { // Update old space string references. if (external_string_table_.old_space_strings_.length() > 0) { Object** start = &external_string_table_.old_space_strings_[0]; Object** end = start + external_string_table_.old_space_strings_.length(); for (Object** p = start; p < end; ++p) *p = updater_func(this, p); } UpdateNewSpaceReferencesInExternalStringTable(updater_func); } void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) { // We don't record weak slots during marking or scavenges. // Instead we do it once when we complete mark-compact cycle. // Note that write barrier has no effect if we are already in the middle of // compacting mark-sweep cycle and we have to record slots manually. bool record_slots = gc_state() == MARK_COMPACT && mark_compact_collector()->is_compacting(); ProcessArrayBuffers(retainer, record_slots); ProcessNativeContexts(retainer, record_slots); // TODO(mvstanton): AllocationSites only need to be processed during // MARK_COMPACT, as they live in old space. Verify and address. ProcessAllocationSites(retainer, record_slots); } void Heap::ProcessNativeContexts(WeakObjectRetainer* retainer, bool record_slots) { Object* head = VisitWeakList<Context>( this, native_contexts_list(), retainer, record_slots); // Update the head of the list of contexts. native_contexts_list_ = head; } void Heap::ProcessArrayBuffers(WeakObjectRetainer* retainer, bool record_slots) { Object* array_buffer_obj = VisitWeakList<JSArrayBuffer>(this, array_buffers_list(), retainer, record_slots); set_array_buffers_list(array_buffer_obj); } void Heap::TearDownArrayBuffers() { Object* undefined = undefined_value(); for (Object* o = array_buffers_list(); o != undefined;) { JSArrayBuffer* buffer = JSArrayBuffer::cast(o); Runtime::FreeArrayBuffer(isolate(), buffer); o = buffer->weak_next(); } array_buffers_list_ = undefined; } void Heap::ProcessAllocationSites(WeakObjectRetainer* retainer, bool record_slots) { Object* allocation_site_obj = VisitWeakList<AllocationSite>(this, allocation_sites_list(), retainer, record_slots); set_allocation_sites_list(allocation_site_obj); } void Heap::ResetAllAllocationSitesDependentCode(PretenureFlag flag) { DisallowHeapAllocation no_allocation_scope; Object* cur = allocation_sites_list(); bool marked = false; while (cur->IsAllocationSite()) { AllocationSite* casted = AllocationSite::cast(cur); if (casted->GetPretenureMode() == flag) { casted->ResetPretenureDecision(); casted->set_deopt_dependent_code(true); marked = true; } cur = casted->weak_next(); } if (marked) isolate_->stack_guard()->DeoptMarkedAllocationSites(); } void Heap::EvaluateOldSpaceLocalPretenuring( uint64_t size_of_objects_before_gc) { uint64_t size_of_objects_after_gc = SizeOfObjects(); double old_generation_survival_rate = (static_cast<double>(size_of_objects_after_gc) * 100) / static_cast<double>(size_of_objects_before_gc); if (old_generation_survival_rate < kOldSurvivalRateLowThreshold) { // Too many objects died in the old generation, pretenuring of wrong // allocation sites may be the cause for that. We have to deopt all // dependent code registered in the allocation sites to re-evaluate // our pretenuring decisions. ResetAllAllocationSitesDependentCode(TENURED); if (FLAG_trace_pretenuring) { PrintF("Deopt all allocation sites dependent code due to low survival " "rate in the old generation %f\n", old_generation_survival_rate); } } } void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) { DisallowHeapAllocation no_allocation; // All external strings are listed in the external string table. class ExternalStringTableVisitorAdapter : public ObjectVisitor { public: explicit ExternalStringTableVisitorAdapter( v8::ExternalResourceVisitor* visitor) : visitor_(visitor) {} virtual void VisitPointers(Object** start, Object** end) { for (Object** p = start; p < end; p++) { ASSERT((*p)->IsExternalString()); visitor_->VisitExternalString(Utils::ToLocal( Handle<String>(String::cast(*p)))); } } private: v8::ExternalResourceVisitor* visitor_; } external_string_table_visitor(visitor); external_string_table_.Iterate(&external_string_table_visitor); } class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> { public: static inline void VisitPointer(Heap* heap, Object** p) { Object* object = *p; if (!heap->InNewSpace(object)) return; Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p), reinterpret_cast<HeapObject*>(object)); } }; Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front) { do { SemiSpace::AssertValidRange(new_space_front, new_space_.top()); // The addresses new_space_front and new_space_.top() define a // queue of unprocessed copied objects. Process them until the // queue is empty. while (new_space_front != new_space_.top()) { if (!NewSpacePage::IsAtEnd(new_space_front)) { HeapObject* object = HeapObject::FromAddress(new_space_front); new_space_front += NewSpaceScavenger::IterateBody(object->map(), object); } else { new_space_front = NewSpacePage::FromLimit(new_space_front)->next_page()->area_start(); } } // Promote and process all the to-be-promoted objects. { StoreBufferRebuildScope scope(this, store_buffer(), &ScavengeStoreBufferCallback); while (!promotion_queue()->is_empty()) { HeapObject* target; int size; promotion_queue()->remove(&target, &size); // Promoted object might be already partially visited // during old space pointer iteration. Thus we search specificly // for pointers to from semispace instead of looking for pointers // to new space. ASSERT(!target->IsMap()); IterateAndMarkPointersToFromSpace(target->address(), target->address() + size, &ScavengeObject); } } // Take another spin if there are now unswept objects in new space // (there are currently no more unswept promoted objects). } while (new_space_front != new_space_.top()); return new_space_front; } STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) == 0); STATIC_ASSERT((ConstantPoolArray::kHeaderSize & kDoubleAlignmentMask) == 0); INLINE(static HeapObject* EnsureDoubleAligned(Heap* heap, HeapObject* object, int size)); static HeapObject* EnsureDoubleAligned(Heap* heap, HeapObject* object, int size) { if ((OffsetFrom(object->address()) & kDoubleAlignmentMask) != 0) { heap->CreateFillerObjectAt(object->address(), kPointerSize); return HeapObject::FromAddress(object->address() + kPointerSize); } else { heap->CreateFillerObjectAt(object->address() + size - kPointerSize, kPointerSize); return object; } } enum LoggingAndProfiling { LOGGING_AND_PROFILING_ENABLED, LOGGING_AND_PROFILING_DISABLED }; enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS }; template<MarksHandling marks_handling, LoggingAndProfiling logging_and_profiling_mode> class ScavengingVisitor : public StaticVisitorBase { public: static void Initialize() { table_.Register(kVisitSeqOneByteString, &EvacuateSeqOneByteString); table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString); table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate); table_.Register(kVisitByteArray, &EvacuateByteArray); table_.Register(kVisitFixedArray, &EvacuateFixedArray); table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray); table_.Register(kVisitFixedTypedArray, &EvacuateFixedTypedArray); table_.Register(kVisitFixedFloat64Array, &EvacuateFixedFloat64Array); table_.Register(kVisitNativeContext, &ObjectEvacuationStrategy<POINTER_OBJECT>:: template VisitSpecialized<Context::kSize>); table_.Register(kVisitConsString, &ObjectEvacuationStrategy<POINTER_OBJECT>:: template VisitSpecialized<ConsString::kSize>); table_.Register(kVisitSlicedString, &ObjectEvacuationStrategy<POINTER_OBJECT>:: template VisitSpecialized<SlicedString::kSize>); table_.Register(kVisitSymbol, &ObjectEvacuationStrategy<POINTER_OBJECT>:: template VisitSpecialized<Symbol::kSize>); table_.Register(kVisitSharedFunctionInfo, &ObjectEvacuationStrategy<POINTER_OBJECT>:: template VisitSpecialized<SharedFunctionInfo::kSize>); table_.Register(kVisitJSWeakMap, &ObjectEvacuationStrategy<POINTER_OBJECT>:: Visit); table_.Register(kVisitJSWeakSet, &ObjectEvacuationStrategy<POINTER_OBJECT>:: Visit); table_.Register(kVisitJSArrayBuffer, &ObjectEvacuationStrategy<POINTER_OBJECT>:: Visit); table_.Register(kVisitJSTypedArray, &ObjectEvacuationStrategy<POINTER_OBJECT>:: Visit); table_.Register(kVisitJSDataView, &ObjectEvacuationStrategy<POINTER_OBJECT>:: Visit); table_.Register(kVisitJSRegExp, &ObjectEvacuationStrategy<POINTER_OBJECT>:: Visit); if (marks_handling == IGNORE_MARKS) { table_.Register(kVisitJSFunction, &ObjectEvacuationStrategy<POINTER_OBJECT>:: template VisitSpecialized<JSFunction::kSize>); } else { table_.Register(kVisitJSFunction, &EvacuateJSFunction); } table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>, kVisitDataObject, kVisitDataObjectGeneric>(); table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>, kVisitJSObject, kVisitJSObjectGeneric>(); table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>, kVisitStruct, kVisitStructGeneric>(); } static VisitorDispatchTable<ScavengingCallback>* GetTable() { return &table_; } private: enum ObjectContents { DATA_OBJECT, POINTER_OBJECT }; static void RecordCopiedObject(Heap* heap, HeapObject* obj) { bool should_record = false; #ifdef DEBUG should_record = FLAG_heap_stats; #endif should_record = should_record || FLAG_log_gc; if (should_record) { if (heap->new_space()->Contains(obj)) { heap->new_space()->RecordAllocation(obj); } else { heap->new_space()->RecordPromotion(obj); } } } // Helper function used by CopyObject to copy a source object to an // allocated target object and update the forwarding pointer in the source // object. Returns the target object. INLINE(static void MigrateObject(Heap* heap, HeapObject* source, HeapObject* target, int size)) { // Copy the content of source to target. heap->CopyBlock(target->address(), source->address(), size); // Set the forwarding address. source->set_map_word(MapWord::FromForwardingAddress(target)); if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) { // Update NewSpace stats if necessary. RecordCopiedObject(heap, target); Isolate* isolate = heap->isolate(); HeapProfiler* heap_profiler = isolate->heap_profiler(); if (heap_profiler->is_tracking_object_moves()) { heap_profiler->ObjectMoveEvent(source->address(), target->address(), size); } if (isolate->logger()->is_logging_code_events() || isolate->cpu_profiler()->is_profiling()) { if (target->IsSharedFunctionInfo()) { PROFILE(isolate, SharedFunctionInfoMoveEvent( source->address(), target->address())); } } } if (marks_handling == TRANSFER_MARKS) { if (Marking::TransferColor(source, target)) { MemoryChunk::IncrementLiveBytesFromGC(target->address(), size); } } } template<ObjectContents object_contents, int alignment> static inline void EvacuateObject(Map* map, HeapObject** slot, HeapObject* object, int object_size) { SLOW_ASSERT(object_size <= Page::kMaxRegularHeapObjectSize); SLOW_ASSERT(object->Size() == object_size); int allocation_size = object_size; if (alignment != kObjectAlignment) { ASSERT(alignment == kDoubleAlignment); allocation_size += kPointerSize; } Heap* heap = map->GetHeap(); if (heap->ShouldBePromoted(object->address(), object_size)) { AllocationResult allocation; if (object_contents == DATA_OBJECT) { ASSERT(heap->AllowedToBeMigrated(object, OLD_DATA_SPACE)); allocation = heap->old_data_space()->AllocateRaw(allocation_size); } else { ASSERT(heap->AllowedToBeMigrated(object, OLD_POINTER_SPACE)); allocation = heap->old_pointer_space()->AllocateRaw(allocation_size); } HeapObject* target = NULL; // Initialization to please compiler. if (allocation.To(&target)) { if (alignment != kObjectAlignment) { target = EnsureDoubleAligned(heap, target, allocation_size); } // Order is important: slot might be inside of the target if target // was allocated over a dead object and slot comes from the store // buffer. *slot = target; MigrateObject(heap, object, target, object_size); if (object_contents == POINTER_OBJECT) { if (map->instance_type() == JS_FUNCTION_TYPE) { heap->promotion_queue()->insert( target, JSFunction::kNonWeakFieldsEndOffset); } else { heap->promotion_queue()->insert(target, object_size); } } heap->tracer()->increment_promoted_objects_size(object_size); return; } } ASSERT(heap->AllowedToBeMigrated(object, NEW_SPACE)); AllocationResult allocation = heap->new_space()->AllocateRaw(allocation_size); heap->promotion_queue()->SetNewLimit(heap->new_space()->top()); HeapObject* target = HeapObject::cast(allocation.ToObjectChecked()); if (alignment != kObjectAlignment) { target = EnsureDoubleAligned(heap, target, allocation_size); } // Order is important: slot might be inside of the target if target // was allocated over a dead object and slot comes from the store // buffer. *slot = target; MigrateObject(heap, object, target, object_size); return; } static inline void EvacuateJSFunction(Map* map, HeapObject** slot, HeapObject* object) { ObjectEvacuationStrategy<POINTER_OBJECT>:: template VisitSpecialized<JSFunction::kSize>(map, slot, object); HeapObject* target = *slot; MarkBit mark_bit = Marking::MarkBitFrom(target); if (Marking::IsBlack(mark_bit)) { // This object is black and it might not be rescanned by marker. // We should explicitly record code entry slot for compaction because // promotion queue processing (IterateAndMarkPointersToFromSpace) will // miss it as it is not HeapObject-tagged. Address code_entry_slot = target->address() + JSFunction::kCodeEntryOffset; Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot)); map->GetHeap()->mark_compact_collector()-> RecordCodeEntrySlot(code_entry_slot, code); } } static inline void EvacuateFixedArray(Map* map, HeapObject** slot, HeapObject* object) { int object_size = FixedArray::BodyDescriptor::SizeOf(map, object); EvacuateObject<POINTER_OBJECT, kObjectAlignment>( map, slot, object, object_size); } static inline void EvacuateFixedDoubleArray(Map* map, HeapObject** slot, HeapObject* object) { int length = reinterpret_cast<FixedDoubleArray*>(object)->length(); int object_size = FixedDoubleArray::SizeFor(length); EvacuateObject<DATA_OBJECT, kDoubleAlignment>( map, slot, object, object_size); } static inline void EvacuateFixedTypedArray(Map* map, HeapObject** slot, HeapObject* object) { int object_size = reinterpret_cast<FixedTypedArrayBase*>(object)->size(); EvacuateObject<DATA_OBJECT, kObjectAlignment>( map, slot, object, object_size); } static inline void EvacuateFixedFloat64Array(Map* map, HeapObject** slot, HeapObject* object) { int object_size = reinterpret_cast<FixedFloat64Array*>(object)->size(); EvacuateObject<DATA_OBJECT, kDoubleAlignment>( map, slot, object, object_size); } static inline void EvacuateByteArray(Map* map, HeapObject** slot, HeapObject* object) { int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize(); EvacuateObject<DATA_OBJECT, kObjectAlignment>( map, slot, object, object_size); } static inline void EvacuateSeqOneByteString(Map* map, HeapObject** slot, HeapObject* object) { int object_size = SeqOneByteString::cast(object)-> SeqOneByteStringSize(map->instance_type()); EvacuateObject<DATA_OBJECT, kObjectAlignment>( map, slot, object, object_size); } static inline void EvacuateSeqTwoByteString(Map* map, HeapObject** slot, HeapObject* object) { int object_size = SeqTwoByteString::cast(object)-> SeqTwoByteStringSize(map->instance_type()); EvacuateObject<DATA_OBJECT, kObjectAlignment>( map, slot, object, object_size); } static inline bool IsShortcutCandidate(int type) { return ((type & kShortcutTypeMask) == kShortcutTypeTag); } static inline void EvacuateShortcutCandidate(Map* map, HeapObject** slot, HeapObject* object) { ASSERT(IsShortcutCandidate(map->instance_type())); Heap* heap = map->GetHeap(); if (marks_handling == IGNORE_MARKS && ConsString::cast(object)->unchecked_second() == heap->empty_string()) { HeapObject* first = HeapObject::cast(ConsString::cast(object)->unchecked_first()); *slot = first; if (!heap->InNewSpace(first)) { object->set_map_word(MapWord::FromForwardingAddress(first)); return; } MapWord first_word = first->map_word(); if (first_word.IsForwardingAddress()) { HeapObject* target = first_word.ToForwardingAddress(); *slot = target; object->set_map_word(MapWord::FromForwardingAddress(target)); return; } heap->DoScavengeObject(first->map(), slot, first); object->set_map_word(MapWord::FromForwardingAddress(*slot)); return; } int object_size = ConsString::kSize; EvacuateObject<POINTER_OBJECT, kObjectAlignment>( map, slot, object, object_size); } template<ObjectContents object_contents> class ObjectEvacuationStrategy { public: template<int object_size> static inline void VisitSpecialized(Map* map, HeapObject** slot, HeapObject* object) { EvacuateObject<object_contents, kObjectAlignment>( map, slot, object, object_size); } static inline void Visit(Map* map, HeapObject** slot, HeapObject* object) { int object_size = map->instance_size(); EvacuateObject<object_contents, kObjectAlignment>( map, slot, object, object_size); } }; static VisitorDispatchTable<ScavengingCallback> table_; }; template<MarksHandling marks_handling, LoggingAndProfiling logging_and_profiling_mode> VisitorDispatchTable<ScavengingCallback> ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_; static void InitializeScavengingVisitorsTables() { ScavengingVisitor<TRANSFER_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize(); ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize(); ScavengingVisitor<TRANSFER_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize(); ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize(); } void Heap::SelectScavengingVisitorsTable() { bool logging_and_profiling = isolate()->logger()->is_logging() || isolate()->cpu_profiler()->is_profiling() || (isolate()->heap_profiler() != NULL && isolate()->heap_profiler()->is_tracking_object_moves()); if (!incremental_marking()->IsMarking()) { if (!logging_and_profiling) { scavenging_visitors_table_.CopyFrom( ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::GetTable()); } else { scavenging_visitors_table_.CopyFrom( ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::GetTable()); } } else { if (!logging_and_profiling) { scavenging_visitors_table_.CopyFrom( ScavengingVisitor<TRANSFER_MARKS, LOGGING_AND_PROFILING_DISABLED>::GetTable()); } else { scavenging_visitors_table_.CopyFrom( ScavengingVisitor<TRANSFER_MARKS, LOGGING_AND_PROFILING_ENABLED>::GetTable()); } if (incremental_marking()->IsCompacting()) { // When compacting forbid short-circuiting of cons-strings. // Scavenging code relies on the fact that new space object // can't be evacuated into evacuation candidate but // short-circuiting violates this assumption. scavenging_visitors_table_.Register( StaticVisitorBase::kVisitShortcutCandidate, scavenging_visitors_table_.GetVisitorById( StaticVisitorBase::kVisitConsString)); } } } void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) { SLOW_ASSERT(object->GetIsolate()->heap()->InFromSpace(object)); MapWord first_word = object->map_word(); SLOW_ASSERT(!first_word.IsForwardingAddress()); Map* map = first_word.ToMap(); map->GetHeap()->DoScavengeObject(map, p, object); } AllocationResult Heap::AllocatePartialMap(InstanceType instance_type, int instance_size) { Object* result; AllocationResult allocation = AllocateRaw(Map::kSize, MAP_SPACE, MAP_SPACE); if (!allocation.To(&result)) return allocation; // Map::cast cannot be used due to uninitialized map field. reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map()); reinterpret_cast<Map*>(result)->set_instance_type(instance_type); reinterpret_cast<Map*>(result)->set_instance_size(instance_size); reinterpret_cast<Map*>(result)->set_visitor_id( StaticVisitorBase::GetVisitorId(instance_type, instance_size)); reinterpret_cast<Map*>(result)->set_inobject_properties(0); reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0); reinterpret_cast<Map*>(result)->set_unused_property_fields(0); reinterpret_cast<Map*>(result)->set_bit_field(0); reinterpret_cast<Map*>(result)->set_bit_field2(0); int bit_field3 = Map::EnumLengthBits::encode(kInvalidEnumCacheSentinel) | Map::OwnsDescriptors::encode(true); reinterpret_cast<Map*>(result)->set_bit_field3(bit_field3); return result; } AllocationResult Heap::AllocateMap(InstanceType instance_type, int instance_size, ElementsKind elements_kind) { HeapObject* result; AllocationResult allocation = AllocateRaw(Map::kSize, MAP_SPACE, MAP_SPACE); if (!allocation.To(&result)) return allocation; result->set_map_no_write_barrier(meta_map()); Map* map = Map::cast(result); map->set_instance_type(instance_type); map->set_visitor_id( StaticVisitorBase::GetVisitorId(instance_type, instance_size)); map->set_prototype(null_value(), SKIP_WRITE_BARRIER); map->set_constructor(null_value(), SKIP_WRITE_BARRIER); map->set_instance_size(instance_size); map->set_inobject_properties(0); map->set_pre_allocated_property_fields(0); map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER); map->set_dependent_code(DependentCode::cast(empty_fixed_array()), SKIP_WRITE_BARRIER); map->init_back_pointer(undefined_value()); map->set_unused_property_fields(0); map->set_instance_descriptors(empty_descriptor_array()); map->set_bit_field(0); map->set_bit_field2(1 << Map::kIsExtensible); int bit_field3 = Map::EnumLengthBits::encode(kInvalidEnumCacheSentinel) | Map::OwnsDescriptors::encode(true); map->set_bit_field3(bit_field3); map->set_elements_kind(elements_kind); return map; } AllocationResult Heap::AllocateFillerObject(int size, bool double_align, AllocationSpace space) { HeapObject* obj; { AllocationResult allocation = AllocateRaw(size, space, space); if (!allocation.To(&obj)) return allocation; } #ifdef DEBUG MemoryChunk* chunk = MemoryChunk::FromAddress(obj->address()); ASSERT(chunk->owner()->identity() == space); #endif CreateFillerObjectAt(obj->address(), size); return obj; } const Heap::StringTypeTable Heap::string_type_table[] = { #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \ {type, size, k##camel_name##MapRootIndex}, STRING_TYPE_LIST(STRING_TYPE_ELEMENT) #undef STRING_TYPE_ELEMENT }; const Heap::ConstantStringTable Heap::constant_string_table[] = { #define CONSTANT_STRING_ELEMENT(name, contents) \ {contents, k##name##RootIndex}, INTERNALIZED_STRING_LIST(CONSTANT_STRING_ELEMENT) #undef CONSTANT_STRING_ELEMENT }; const Heap::StructTable Heap::struct_table[] = { #define STRUCT_TABLE_ELEMENT(NAME, Name, name) \ { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex }, STRUCT_LIST(STRUCT_TABLE_ELEMENT) #undef STRUCT_TABLE_ELEMENT }; bool Heap::CreateInitialMaps() { HeapObject* obj; { AllocationResult allocation = AllocatePartialMap(MAP_TYPE, Map::kSize); if (!allocation.To(&obj)) return false; } // Map::cast cannot be used due to uninitialized map field. Map* new_meta_map = reinterpret_cast<Map*>(obj); set_meta_map(new_meta_map); new_meta_map->set_map(new_meta_map); { // Partial map allocation #define ALLOCATE_PARTIAL_MAP(instance_type, size, field_name) \ { Map* map; \ if (!AllocatePartialMap((instance_type), (size)).To(&map)) return false; \ set_##field_name##_map(map); \ } ALLOCATE_PARTIAL_MAP(FIXED_ARRAY_TYPE, kVariableSizeSentinel, fixed_array); ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, undefined); ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, null); ALLOCATE_PARTIAL_MAP(CONSTANT_POOL_ARRAY_TYPE, kVariableSizeSentinel, constant_pool_array); #undef ALLOCATE_PARTIAL_MAP } // Allocate the empty array. { AllocationResult allocation = AllocateEmptyFixedArray(); if (!allocation.To(&obj)) return false; } set_empty_fixed_array(FixedArray::cast(obj)); { AllocationResult allocation = Allocate(null_map(), OLD_POINTER_SPACE); if (!allocation.To(&obj)) return false; } set_null_value(Oddball::cast(obj)); Oddball::cast(obj)->set_kind(Oddball::kNull); { AllocationResult allocation = Allocate(undefined_map(), OLD_POINTER_SPACE); if (!allocation.To(&obj)) return false; } set_undefined_value(Oddball::cast(obj)); Oddball::cast(obj)->set_kind(Oddball::kUndefined); ASSERT(!InNewSpace(undefined_value())); // Set preliminary exception sentinel value before actually initializing it. set_exception(null_value()); // Allocate the empty descriptor array. { AllocationResult allocation = AllocateEmptyFixedArray(); if (!allocation.To(&obj)) return false; } set_empty_descriptor_array(DescriptorArray::cast(obj)); // Allocate the constant pool array. { AllocationResult allocation = AllocateEmptyConstantPoolArray(); if (!allocation.To(&obj)) return false; } set_empty_constant_pool_array(ConstantPoolArray::cast(obj)); // Fix the instance_descriptors for the existing maps. meta_map()->set_code_cache(empty_fixed_array()); meta_map()->set_dependent_code(DependentCode::cast(empty_fixed_array())); meta_map()->init_back_pointer(undefined_value()); meta_map()->set_instance_descriptors(empty_descriptor_array()); fixed_array_map()->set_code_cache(empty_fixed_array()); fixed_array_map()->set_dependent_code( DependentCode::cast(empty_fixed_array())); fixed_array_map()->init_back_pointer(undefined_value()); fixed_array_map()->set_instance_descriptors(empty_descriptor_array()); undefined_map()->set_code_cache(empty_fixed_array()); undefined_map()->set_dependent_code(DependentCode::cast(empty_fixed_array())); undefined_map()->init_back_pointer(undefined_value()); undefined_map()->set_instance_descriptors(empty_descriptor_array()); null_map()->set_code_cache(empty_fixed_array()); null_map()->set_dependent_code(DependentCode::cast(empty_fixed_array())); null_map()->init_back_pointer(undefined_value()); null_map()->set_instance_descriptors(empty_descriptor_array()); constant_pool_array_map()->set_code_cache(empty_fixed_array()); constant_pool_array_map()->set_dependent_code( DependentCode::cast(empty_fixed_array())); constant_pool_array_map()->init_back_pointer(undefined_value()); constant_pool_array_map()->set_instance_descriptors(empty_descriptor_array()); // Fix prototype object for existing maps. meta_map()->set_prototype(null_value()); meta_map()->set_constructor(null_value()); fixed_array_map()->set_prototype(null_value()); fixed_array_map()->set_constructor(null_value()); undefined_map()->set_prototype(null_value()); undefined_map()->set_constructor(null_value()); null_map()->set_prototype(null_value()); null_map()->set_constructor(null_value()); constant_pool_array_map()->set_prototype(null_value()); constant_pool_array_map()->set_constructor(null_value()); { // Map allocation #define ALLOCATE_MAP(instance_type, size, field_name) \ { Map* map; \ if (!AllocateMap((instance_type), size).To(&map)) return false; \ set_##field_name##_map(map); \ } #define ALLOCATE_VARSIZE_MAP(instance_type, field_name) \ ALLOCATE_MAP(instance_type, kVariableSizeSentinel, field_name) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, fixed_cow_array) ASSERT(fixed_array_map() != fixed_cow_array_map()); ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, scope_info) ALLOCATE_MAP(HEAP_NUMBER_TYPE, HeapNumber::kSize, heap_number) ALLOCATE_MAP(SYMBOL_TYPE, Symbol::kSize, symbol) ALLOCATE_MAP(FOREIGN_TYPE, Foreign::kSize, foreign) ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, the_hole); ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, boolean); ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, uninitialized); ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, arguments_marker); ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, no_interceptor_result_sentinel); ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, exception); ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, termination_exception); for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) { const StringTypeTable& entry = string_type_table[i]; { AllocationResult allocation = AllocateMap(entry.type, entry.size); if (!allocation.To(&obj)) return false; } // Mark cons string maps as unstable, because their objects can change // maps during GC. Map* map = Map::cast(obj); if (StringShape(entry.type).IsCons()) map->mark_unstable(); roots_[entry.index] = map; } ALLOCATE_VARSIZE_MAP(STRING_TYPE, undetectable_string) undetectable_string_map()->set_is_undetectable(); ALLOCATE_VARSIZE_MAP(ASCII_STRING_TYPE, undetectable_ascii_string); undetectable_ascii_string_map()->set_is_undetectable(); ALLOCATE_VARSIZE_MAP(FIXED_DOUBLE_ARRAY_TYPE, fixed_double_array) ALLOCATE_VARSIZE_MAP(BYTE_ARRAY_TYPE, byte_array) ALLOCATE_VARSIZE_MAP(FREE_SPACE_TYPE, free_space) #define ALLOCATE_EXTERNAL_ARRAY_MAP(Type, type, TYPE, ctype, size) \ ALLOCATE_MAP(EXTERNAL_##TYPE##_ARRAY_TYPE, ExternalArray::kAlignedSize, \ external_##type##_array) TYPED_ARRAYS(ALLOCATE_EXTERNAL_ARRAY_MAP) #undef ALLOCATE_EXTERNAL_ARRAY_MAP #define ALLOCATE_FIXED_TYPED_ARRAY_MAP(Type, type, TYPE, ctype, size) \ ALLOCATE_VARSIZE_MAP(FIXED_##TYPE##_ARRAY_TYPE, \ fixed_##type##_array) TYPED_ARRAYS(ALLOCATE_FIXED_TYPED_ARRAY_MAP) #undef ALLOCATE_FIXED_TYPED_ARRAY_MAP ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, sloppy_arguments_elements) ALLOCATE_VARSIZE_MAP(CODE_TYPE, code) ALLOCATE_MAP(CELL_TYPE, Cell::kSize, cell) ALLOCATE_MAP(PROPERTY_CELL_TYPE, PropertyCell::kSize, global_property_cell) ALLOCATE_MAP(FILLER_TYPE, kPointerSize, one_pointer_filler) ALLOCATE_MAP(FILLER_TYPE, 2 * kPointerSize, two_pointer_filler) for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) { const StructTable& entry = struct_table[i]; Map* map; if (!AllocateMap(entry.type, entry.size).To(&map)) return false; roots_[entry.index] = map; } ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, hash_table) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, ordered_hash_table) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, function_context) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, catch_context) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, with_context) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, block_context) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, module_context) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, global_context) ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, native_context) native_context_map()->set_dictionary_map(true); native_context_map()->set_visitor_id( StaticVisitorBase::kVisitNativeContext); ALLOCATE_MAP(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kAlignedSize, shared_function_info) ALLOCATE_MAP(JS_MESSAGE_OBJECT_TYPE, JSMessageObject::kSize, message_object) ALLOCATE_MAP(JS_OBJECT_TYPE, JSObject::kHeaderSize + kPointerSize, external) external_map()->set_is_extensible(false); #undef ALLOCATE_VARSIZE_MAP #undef ALLOCATE_MAP } { // Empty arrays { ByteArray* byte_array; if (!AllocateByteArray(0, TENURED).To(&byte_array)) return false; set_empty_byte_array(byte_array); } #define ALLOCATE_EMPTY_EXTERNAL_ARRAY(Type, type, TYPE, ctype, size) \ { ExternalArray* obj; \ if (!AllocateEmptyExternalArray(kExternal##Type##Array).To(&obj)) \ return false; \ set_empty_external_##type##_array(obj); \ } TYPED_ARRAYS(ALLOCATE_EMPTY_EXTERNAL_ARRAY) #undef ALLOCATE_EMPTY_EXTERNAL_ARRAY #define ALLOCATE_EMPTY_FIXED_TYPED_ARRAY(Type, type, TYPE, ctype, size) \ { FixedTypedArrayBase* obj; \ if (!AllocateEmptyFixedTypedArray(kExternal##Type##Array).To(&obj)) \ return false; \ set_empty_fixed_##type##_array(obj); \ } TYPED_ARRAYS(ALLOCATE_EMPTY_FIXED_TYPED_ARRAY) #undef ALLOCATE_EMPTY_FIXED_TYPED_ARRAY } ASSERT(!InNewSpace(empty_fixed_array())); return true; } AllocationResult Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) { // Statically ensure that it is safe to allocate heap numbers in paged // spaces. int size = HeapNumber::kSize; STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxRegularHeapObjectSize); AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, pretenure); HeapObject* result; { AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE); if (!allocation.To(&result)) return allocation; } result->set_map_no_write_barrier(heap_number_map()); HeapNumber::cast(result)->set_value(value); return result; } AllocationResult Heap::AllocateCell(Object* value) { int size = Cell::kSize; STATIC_ASSERT(Cell::kSize <= Page::kMaxRegularHeapObjectSize); HeapObject* result; { AllocationResult allocation = AllocateRaw(size, CELL_SPACE, CELL_SPACE); if (!allocation.To(&result)) return allocation; } result->set_map_no_write_barrier(cell_map()); Cell::cast(result)->set_value(value); return result; } AllocationResult Heap::AllocatePropertyCell() { int size = PropertyCell::kSize; STATIC_ASSERT(PropertyCell::kSize <= Page::kMaxRegularHeapObjectSize); HeapObject* result; AllocationResult allocation = AllocateRaw(size, PROPERTY_CELL_SPACE, PROPERTY_CELL_SPACE); if (!allocation.To(&result)) return allocation; result->set_map_no_write_barrier(global_property_cell_map()); PropertyCell* cell = PropertyCell::cast(result); cell->set_dependent_code(DependentCode::cast(empty_fixed_array()), SKIP_WRITE_BARRIER); cell->set_value(the_hole_value()); cell->set_type(HeapType::None()); return result; } void Heap::CreateApiObjects() { HandleScope scope(isolate()); Factory* factory = isolate()->factory(); Handle<Map> new_neander_map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize); // Don't use Smi-only elements optimizations for objects with the neander // map. There are too many cases where element values are set directly with a // bottleneck to trap the Smi-only -> fast elements transition, and there // appears to be no benefit for optimize this case. new_neander_map->set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND); set_neander_map(*new_neander_map); Handle<JSObject> listeners = factory->NewNeanderObject(); Handle<FixedArray> elements = factory->NewFixedArray(2); elements->set(0, Smi::FromInt(0)); listeners->set_elements(*elements); set_message_listeners(*listeners); } void Heap::CreateJSEntryStub() { JSEntryStub stub(isolate()); set_js_entry_code(*stub.GetCode()); } void Heap::CreateJSConstructEntryStub() { JSConstructEntryStub stub(isolate()); set_js_construct_entry_code(*stub.GetCode()); } void Heap::CreateFixedStubs() { // Here we create roots for fixed stubs. They are needed at GC // for cooking and uncooking (check out frames.cc). // The eliminates the need for doing dictionary lookup in the // stub cache for these stubs. HandleScope scope(isolate()); // Create stubs that should be there, so we don't unexpectedly have to // create them if we need them during the creation of another stub. // Stub creation mixes raw pointers and handles in an unsafe manner so // we cannot create stubs while we are creating stubs. CodeStub::GenerateStubsAheadOfTime(isolate()); // MacroAssembler::Abort calls (usually enabled with --debug-code) depend on // CEntryStub, so we need to call GenerateStubsAheadOfTime before JSEntryStub // is created. // gcc-4.4 has problem generating correct code of following snippet: // { JSEntryStub stub; // js_entry_code_ = *stub.GetCode(); // } // { JSConstructEntryStub stub; // js_construct_entry_code_ = *stub.GetCode(); // } // To workaround the problem, make separate functions without inlining. Heap::CreateJSEntryStub(); Heap::CreateJSConstructEntryStub(); } void Heap::CreateInitialObjects() { HandleScope scope(isolate()); Factory* factory = isolate()->factory(); // The -0 value must be set before NumberFromDouble works. set_minus_zero_value(*factory->NewHeapNumber(-0.0, TENURED)); ASSERT(std::signbit(minus_zero_value()->Number()) != 0); set_nan_value(*factory->NewHeapNumber(OS::nan_value(), TENURED)); set_infinity_value(*factory->NewHeapNumber(V8_INFINITY, TENURED)); // The hole has not been created yet, but we want to put something // predictable in the gaps in the string table, so lets make that Smi zero. set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0))); // Allocate initial string table. set_string_table(*StringTable::New(isolate(), kInitialStringTableSize)); // Finish initializing oddballs after creating the string table. Oddball::Initialize(isolate(), factory->undefined_value(), "undefined", factory->nan_value(), Oddball::kUndefined); // Initialize the null_value. Oddball::Initialize(isolate(), factory->null_value(), "null", handle(Smi::FromInt(0), isolate()), Oddball::kNull); set_true_value(*factory->NewOddball(factory->boolean_map(), "true", handle(Smi::FromInt(1), isolate()), Oddball::kTrue)); set_false_value(*factory->NewOddball(factory->boolean_map(), "false", handle(Smi::FromInt(0), isolate()), Oddball::kFalse)); set_the_hole_value(*factory->NewOddball(factory->the_hole_map(), "hole", handle(Smi::FromInt(-1), isolate()), Oddball::kTheHole)); set_uninitialized_value( *factory->NewOddball(factory->uninitialized_map(), "uninitialized", handle(Smi::FromInt(-1), isolate()), Oddball::kUninitialized)); set_arguments_marker(*factory->NewOddball(factory->arguments_marker_map(), "arguments_marker", handle(Smi::FromInt(-4), isolate()), Oddball::kArgumentMarker)); set_no_interceptor_result_sentinel( *factory->NewOddball(factory->no_interceptor_result_sentinel_map(), "no_interceptor_result_sentinel", handle(Smi::FromInt(-2), isolate()), Oddball::kOther)); set_termination_exception( *factory->NewOddball(factory->termination_exception_map(), "termination_exception", handle(Smi::FromInt(-3), isolate()), Oddball::kOther)); set_exception( *factory->NewOddball(factory->exception_map(), "exception", handle(Smi::FromInt(-5), isolate()), Oddball::kException)); for (unsigned i = 0; i < ARRAY_SIZE(constant_string_table); i++) { Handle<String> str = factory->InternalizeUtf8String(constant_string_table[i].contents); roots_[constant_string_table[i].index] = *str; } // Allocate the hidden string which is used to identify the hidden properties // in JSObjects. The hash code has a special value so that it will not match // the empty string when searching for the property. It cannot be part of the // loop above because it needs to be allocated manually with the special // hash code in place. The hash code for the hidden_string is zero to ensure // that it will always be at the first entry in property descriptors. hidden_string_ = *factory->NewOneByteInternalizedString( OneByteVector("", 0), String::kEmptyStringHash); // Create the code_stubs dictionary. The initial size is set to avoid // expanding the dictionary during bootstrapping. set_code_stubs(*UnseededNumberDictionary::New(isolate(), 128)); // Create the non_monomorphic_cache used in stub-cache.cc. The initial size // is set to avoid expanding the dictionary during bootstrapping. set_non_monomorphic_cache(*UnseededNumberDictionary::New(isolate(), 64)); set_polymorphic_code_cache(PolymorphicCodeCache::cast( *factory->NewStruct(POLYMORPHIC_CODE_CACHE_TYPE))); set_instanceof_cache_function(Smi::FromInt(0)); set_instanceof_cache_map(Smi::FromInt(0)); set_instanceof_cache_answer(Smi::FromInt(0)); CreateFixedStubs(); // Allocate the dictionary of intrinsic function names. Handle<NameDictionary> intrinsic_names = NameDictionary::New(isolate(), Runtime::kNumFunctions); Runtime::InitializeIntrinsicFunctionNames(isolate(), intrinsic_names); set_intrinsic_function_names(*intrinsic_names); set_number_string_cache(*factory->NewFixedArray( kInitialNumberStringCacheSize * 2, TENURED)); // Allocate cache for single character one byte strings. set_single_character_string_cache(*factory->NewFixedArray( String::kMaxOneByteCharCode + 1, TENURED)); // Allocate cache for string split and regexp-multiple. set_string_split_cache(*factory->NewFixedArray( RegExpResultsCache::kRegExpResultsCacheSize, TENURED)); set_regexp_multiple_cache(*factory->NewFixedArray( RegExpResultsCache::kRegExpResultsCacheSize, TENURED)); // Allocate cache for external strings pointing to native source code. set_natives_source_cache(*factory->NewFixedArray( Natives::GetBuiltinsCount())); set_undefined_cell(*factory->NewCell(factory->undefined_value())); // The symbol registry is initialized lazily. set_symbol_registry(undefined_value()); // Allocate object to hold object observation state. set_observation_state(*factory->NewJSObjectFromMap( factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize))); // Allocate object to hold object microtask state. set_microtask_state(*factory->NewJSObjectFromMap( factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize))); set_frozen_symbol(*factory->NewPrivateSymbol()); set_nonexistent_symbol(*factory->NewPrivateSymbol()); set_elements_transition_symbol(*factory->NewPrivateSymbol()); set_uninitialized_symbol(*factory->NewPrivateSymbol()); set_megamorphic_symbol(*factory->NewPrivateSymbol()); set_observed_symbol(*factory->NewPrivateSymbol()); Handle<SeededNumberDictionary> slow_element_dictionary = SeededNumberDictionary::New(isolate(), 0, TENURED); slow_element_dictionary->set_requires_slow_elements(); set_empty_slow_element_dictionary(*slow_element_dictionary); set_materialized_objects(*factory->NewFixedArray(0, TENURED)); // Handling of script id generation is in Factory::NewScript. set_last_script_id(Smi::FromInt(v8::UnboundScript::kNoScriptId)); set_allocation_sites_scratchpad(*factory->NewFixedArray( kAllocationSiteScratchpadSize, TENURED)); InitializeAllocationSitesScratchpad(); // Initialize keyed lookup cache. isolate_->keyed_lookup_cache()->Clear(); // Initialize context slot cache. isolate_->context_slot_cache()->Clear(); // Initialize descriptor cache. isolate_->descriptor_lookup_cache()->Clear(); // Initialize compilation cache. isolate_->compilation_cache()->Clear(); } bool Heap::RootCanBeWrittenAfterInitialization(Heap::RootListIndex root_index) { RootListIndex writable_roots[] = { kStoreBufferTopRootIndex, kStackLimitRootIndex, kNumberStringCacheRootIndex, kInstanceofCacheFunctionRootIndex, kInstanceofCacheMapRootIndex, kInstanceofCacheAnswerRootIndex, kCodeStubsRootIndex, kNonMonomorphicCacheRootIndex, kPolymorphicCodeCacheRootIndex, kLastScriptIdRootIndex, kEmptyScriptRootIndex, kRealStackLimitRootIndex, kArgumentsAdaptorDeoptPCOffsetRootIndex, kConstructStubDeoptPCOffsetRootIndex, kGetterStubDeoptPCOffsetRootIndex, kSetterStubDeoptPCOffsetRootIndex, kStringTableRootIndex, }; for (unsigned int i = 0; i < ARRAY_SIZE(writable_roots); i++) { if (root_index == writable_roots[i]) return true; } return false; } bool Heap::RootCanBeTreatedAsConstant(RootListIndex root_index) { return !RootCanBeWrittenAfterInitialization(root_index) && !InNewSpace(roots_array_start()[root_index]); } Object* RegExpResultsCache::Lookup(Heap* heap, String* key_string, Object* key_pattern, ResultsCacheType type) { FixedArray* cache; if (!key_string->IsInternalizedString()) return Smi::FromInt(0); if (type == STRING_SPLIT_SUBSTRINGS) { ASSERT(key_pattern->IsString()); if (!key_pattern->IsInternalizedString()) return Smi::FromInt(0); cache = heap->string_split_cache(); } else { ASSERT(type == REGEXP_MULTIPLE_INDICES); ASSERT(key_pattern->IsFixedArray()); cache = heap->regexp_multiple_cache(); } uint32_t hash = key_string->Hash(); uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) & ~(kArrayEntriesPerCacheEntry - 1)); if (cache->get(index + kStringOffset) == key_string && cache->get(index + kPatternOffset) == key_pattern) { return cache->get(index + kArrayOffset); } index = ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1)); if (cache->get(index + kStringOffset) == key_string && cache->get(index + kPatternOffset) == key_pattern) { return cache->get(index + kArrayOffset); } return Smi::FromInt(0); } void RegExpResultsCache::Enter(Isolate* isolate, Handle<String> key_string, Handle<Object> key_pattern, Handle<FixedArray> value_array, ResultsCacheType type) { Factory* factory = isolate->factory(); Handle<FixedArray> cache; if (!key_string->IsInternalizedString()) return; if (type == STRING_SPLIT_SUBSTRINGS) { ASSERT(key_pattern->IsString()); if (!key_pattern->IsInternalizedString()) return; cache = factory->string_split_cache(); } else { ASSERT(type == REGEXP_MULTIPLE_INDICES); ASSERT(key_pattern->IsFixedArray()); cache = factory->regexp_multiple_cache(); } uint32_t hash = key_string->Hash(); uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) & ~(kArrayEntriesPerCacheEntry - 1)); if (cache->get(index + kStringOffset) == Smi::FromInt(0)) { cache->set(index + kStringOffset, *key_string); cache->set(index + kPatternOffset, *key_pattern); cache->set(index + kArrayOffset, *value_array); } else { uint32_t index2 = ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1)); if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) { cache->set(index2 + kStringOffset, *key_string); cache->set(index2 + kPatternOffset, *key_pattern); cache->set(index2 + kArrayOffset, *value_array); } else { cache->set(index2 + kStringOffset, Smi::FromInt(0)); cache->set(index2 + kPatternOffset, Smi::FromInt(0)); cache->set(index2 + kArrayOffset, Smi::FromInt(0)); cache->set(index + kStringOffset, *key_string); cache->set(index + kPatternOffset, *key_pattern); cache->set(index + kArrayOffset, *value_array); } } // If the array is a reasonably short list of substrings, convert it into a // list of internalized strings. if (type == STRING_SPLIT_SUBSTRINGS && value_array->length() < 100) { for (int i = 0; i < value_array->length(); i++) { Handle<String> str(String::cast(value_array->get(i)), isolate); Handle<String> internalized_str = factory->InternalizeString(str); value_array->set(i, *internalized_str); } } // Convert backing store to a copy-on-write array. value_array->set_map_no_write_barrier(*factory->fixed_cow_array_map()); } void RegExpResultsCache::Clear(FixedArray* cache) { for (int i = 0; i < kRegExpResultsCacheSize; i++) { cache->set(i, Smi::FromInt(0)); } } int Heap::FullSizeNumberStringCacheLength() { // Compute the size of the number string cache based on the max newspace size. // The number string cache has a minimum size based on twice the initial cache // size to ensure that it is bigger after being made 'full size'. int number_string_cache_size = max_semispace_size_ / 512; number_string_cache_size = Max(kInitialNumberStringCacheSize * 2, Min(0x4000, number_string_cache_size)); // There is a string and a number per entry so the length is twice the number // of entries. return number_string_cache_size * 2; } void Heap::FlushNumberStringCache() { // Flush the number to string cache. int len = number_string_cache()->length(); for (int i = 0; i < len; i++) { number_string_cache()->set_undefined(i); } } void Heap::FlushAllocationSitesScratchpad() { for (int i = 0; i < allocation_sites_scratchpad_length_; i++) { allocation_sites_scratchpad()->set_undefined(i); } allocation_sites_scratchpad_length_ = 0; } void Heap::InitializeAllocationSitesScratchpad() { ASSERT(allocation_sites_scratchpad()->length() == kAllocationSiteScratchpadSize); for (int i = 0; i < kAllocationSiteScratchpadSize; i++) { allocation_sites_scratchpad()->set_undefined(i); } } void Heap::AddAllocationSiteToScratchpad(AllocationSite* site, ScratchpadSlotMode mode) { if (allocation_sites_scratchpad_length_ < kAllocationSiteScratchpadSize) { // We cannot use the normal write-barrier because slots need to be // recorded with non-incremental marking as well. We have to explicitly // record the slot to take evacuation candidates into account. allocation_sites_scratchpad()->set( allocation_sites_scratchpad_length_, site, SKIP_WRITE_BARRIER); Object** slot = allocation_sites_scratchpad()->RawFieldOfElementAt( allocation_sites_scratchpad_length_); if (mode == RECORD_SCRATCHPAD_SLOT) { // We need to allow slots buffer overflow here since the evacuation // candidates are not part of the global list of old space pages and // releasing an evacuation candidate due to a slots buffer overflow // results in lost pages. mark_compact_collector()->RecordSlot( slot, slot, *slot, SlotsBuffer::IGNORE_OVERFLOW); } allocation_sites_scratchpad_length_++; } } Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) { return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]); } Heap::RootListIndex Heap::RootIndexForExternalArrayType( ExternalArrayType array_type) { switch (array_type) { #define ARRAY_TYPE_TO_ROOT_INDEX(Type, type, TYPE, ctype, size) \ case kExternal##Type##Array: \ return kExternal##Type##ArrayMapRootIndex; TYPED_ARRAYS(ARRAY_TYPE_TO_ROOT_INDEX) #undef ARRAY_TYPE_TO_ROOT_INDEX default: UNREACHABLE(); return kUndefinedValueRootIndex; } } Map* Heap::MapForFixedTypedArray(ExternalArrayType array_type) { return Map::cast(roots_[RootIndexForFixedTypedArray(array_type)]); } Heap::RootListIndex Heap::RootIndexForFixedTypedArray( ExternalArrayType array_type) { switch (array_type) { #define ARRAY_TYPE_TO_ROOT_INDEX(Type, type, TYPE, ctype, size) \ case kExternal##Type##Array: \ return kFixed##Type##ArrayMapRootIndex; TYPED_ARRAYS(ARRAY_TYPE_TO_ROOT_INDEX) #undef ARRAY_TYPE_TO_ROOT_INDEX default: UNREACHABLE(); return kUndefinedValueRootIndex; } } Heap::RootListIndex Heap::RootIndexForEmptyExternalArray( ElementsKind elementsKind) { switch (elementsKind) { #define ELEMENT_KIND_TO_ROOT_INDEX(Type, type, TYPE, ctype, size) \ case EXTERNAL_##TYPE##_ELEMENTS: \ return kEmptyExternal##Type##ArrayRootIndex; TYPED_ARRAYS(ELEMENT_KIND_TO_ROOT_INDEX) #undef ELEMENT_KIND_TO_ROOT_INDEX default: UNREACHABLE(); return kUndefinedValueRootIndex; } } Heap::RootListIndex Heap::RootIndexForEmptyFixedTypedArray( ElementsKind elementsKind) { switch (elementsKind) { #define ELEMENT_KIND_TO_ROOT_INDEX(Type, type, TYPE, ctype, size) \ case TYPE##_ELEMENTS: \ return kEmptyFixed##Type##ArrayRootIndex; TYPED_ARRAYS(ELEMENT_KIND_TO_ROOT_INDEX) #undef ELEMENT_KIND_TO_ROOT_INDEX default: UNREACHABLE(); return kUndefinedValueRootIndex; } } ExternalArray* Heap::EmptyExternalArrayForMap(Map* map) { return ExternalArray::cast( roots_[RootIndexForEmptyExternalArray(map->elements_kind())]); } FixedTypedArrayBase* Heap::EmptyFixedTypedArrayForMap(Map* map) { return FixedTypedArrayBase::cast( roots_[RootIndexForEmptyFixedTypedArray(map->elements_kind())]); } AllocationResult Heap::AllocateForeign(Address address, PretenureFlag pretenure) { // Statically ensure that it is safe to allocate foreigns in paged spaces. STATIC_ASSERT(Foreign::kSize <= Page::kMaxRegularHeapObjectSize); AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE; Foreign* result; AllocationResult allocation = Allocate(foreign_map(), space); if (!allocation.To(&result)) return allocation; result->set_foreign_address(address); return result; } AllocationResult Heap::AllocateByteArray(int length, PretenureFlag pretenure) { if (length < 0 || length > ByteArray::kMaxLength) { v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true); } int size = ByteArray::SizeFor(length); AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, pretenure); HeapObject* result; { AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE); if (!allocation.To(&result)) return allocation; } result->set_map_no_write_barrier(byte_array_map()); ByteArray::cast(result)->set_length(length); return result; } void Heap::CreateFillerObjectAt(Address addr, int size) { if (size == 0) return; HeapObject* filler = HeapObject::FromAddress(addr); if (size == kPointerSize) { filler->set_map_no_write_barrier(one_pointer_filler_map()); } else if (size == 2 * kPointerSize) { filler->set_map_no_write_barrier(two_pointer_filler_map()); } else { filler->set_map_no_write_barrier(free_space_map()); FreeSpace::cast(filler)->set_size(size); } } bool Heap::CanMoveObjectStart(HeapObject* object) { Address address = object->address(); bool is_in_old_pointer_space = InOldPointerSpace(address); bool is_in_old_data_space = InOldDataSpace(address); if (lo_space()->Contains(object)) return false; Page* page = Page::FromAddress(address); // We can move the object start if: // (1) the object is not in old pointer or old data space, // (2) the page of the object was already swept, // (3) the page was already concurrently swept. This case is an optimization // for concurrent sweeping. The WasSwept predicate for concurrently swept // pages is set after sweeping all pages. return (!is_in_old_pointer_space && !is_in_old_data_space) || page->WasSwept() || (mark_compact_collector()->AreSweeperThreadsActivated() && page->parallel_sweeping() <= MemoryChunk::PARALLEL_SWEEPING_FINALIZE); } void Heap::AdjustLiveBytes(Address address, int by, InvocationMode mode) { if (incremental_marking()->IsMarking() && Marking::IsBlack(Marking::MarkBitFrom(address))) { if (mode == FROM_GC) { MemoryChunk::IncrementLiveBytesFromGC(address, by); } else { MemoryChunk::IncrementLiveBytesFromMutator(address, by); } } } AllocationResult Heap::AllocateExternalArray(int length, ExternalArrayType array_type, void* external_pointer, PretenureFlag pretenure) { int size = ExternalArray::kAlignedSize; AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, pretenure); HeapObject* result; { AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE); if (!allocation.To(&result)) return allocation; } result->set_map_no_write_barrier( MapForExternalArrayType(array_type)); ExternalArray::cast(result)->set_length(length); ExternalArray::cast(result)->set_external_pointer(external_pointer); return result; } static void ForFixedTypedArray(ExternalArrayType array_type, int* element_size, ElementsKind* element_kind) { switch (array_type) { #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case kExternal##Type##Array: \ *element_size = size; \ *element_kind = TYPE##_ELEMENTS; \ return; TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE default: *element_size = 0; // Bogus *element_kind = UINT8_ELEMENTS; // Bogus UNREACHABLE(); } } AllocationResult Heap::AllocateFixedTypedArray(int length, ExternalArrayType array_type, PretenureFlag pretenure) { int element_size; ElementsKind elements_kind; ForFixedTypedArray(array_type, &element_size, &elements_kind); int size = OBJECT_POINTER_ALIGN( length * element_size + FixedTypedArrayBase::kDataOffset); #ifndef V8_HOST_ARCH_64_BIT if (array_type == kExternalFloat64Array) { size += kPointerSize; } #endif AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, pretenure); HeapObject* object; AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE); if (!allocation.To(&object)) return allocation; if (array_type == kExternalFloat64Array) { object = EnsureDoubleAligned(this, object, size); } object->set_map(MapForFixedTypedArray(array_type)); FixedTypedArrayBase* elements = FixedTypedArrayBase::cast(object); elements->set_length(length); memset(elements->DataPtr(), 0, elements->DataSize()); return elements; } AllocationResult Heap::AllocateCode(int object_size, bool immovable) { ASSERT(IsAligned(static_cast<intptr_t>(object_size), kCodeAlignment)); AllocationResult allocation; // Large code objects and code objects which should stay at a fixed address // are allocated in large object space. HeapObject* result; bool force_lo_space = object_size > code_space()->AreaSize(); if (force_lo_space) { allocation = lo_space_->AllocateRaw(object_size, EXECUTABLE); } else { allocation = AllocateRaw(object_size, CODE_SPACE, CODE_SPACE); } if (!allocation.To(&result)) return allocation; if (immovable && !force_lo_space && // Objects on the first page of each space are never moved. !code_space_->FirstPage()->Contains(result->address())) { // Discard the first code allocation, which was on a page where it could be // moved. CreateFillerObjectAt(result->address(), object_size); allocation = lo_space_->AllocateRaw(object_size, EXECUTABLE); if (!allocation.To(&result)) return allocation; } result->set_map_no_write_barrier(code_map()); Code* code = Code::cast(result); ASSERT(!isolate_->code_range()->exists() || isolate_->code_range()->contains(code->address())); code->set_gc_metadata(Smi::FromInt(0)); code->set_ic_age(global_ic_age_); return code; } AllocationResult Heap::CopyCode(Code* code) { AllocationResult allocation; HeapObject* new_constant_pool; if (FLAG_enable_ool_constant_pool && code->constant_pool() != empty_constant_pool_array()) { // Copy the constant pool, since edits to the copied code may modify // the constant pool. allocation = CopyConstantPoolArray(code->constant_pool()); if (!allocation.To(&new_constant_pool)) return allocation; } else { new_constant_pool = empty_constant_pool_array(); } // Allocate an object the same size as the code object. int obj_size = code->Size(); if (obj_size > code_space()->AreaSize()) { allocation = lo_space_->AllocateRaw(obj_size, EXECUTABLE); } else { allocation = AllocateRaw(obj_size, CODE_SPACE, CODE_SPACE); } HeapObject* result; if (!allocation.To(&result)) return allocation; // Copy code object. Address old_addr = code->address(); Address new_addr = result->address(); CopyBlock(new_addr, old_addr, obj_size); Code* new_code = Code::cast(result); // Update the constant pool. new_code->set_constant_pool(new_constant_pool); // Relocate the copy. ASSERT(!isolate_->code_range()->exists() || isolate_->code_range()->contains(code->address())); new_code->Relocate(new_addr - old_addr); return new_code; } AllocationResult Heap::CopyCode(Code* code, Vector<byte> reloc_info) { // Allocate ByteArray and ConstantPoolArray before the Code object, so that we // do not risk leaving uninitialized Code object (and breaking the heap). ByteArray* reloc_info_array; { AllocationResult allocation = AllocateByteArray(reloc_info.length(), TENURED); if (!allocation.To(&reloc_info_array)) return allocation; } HeapObject* new_constant_pool; if (FLAG_enable_ool_constant_pool && code->constant_pool() != empty_constant_pool_array()) { // Copy the constant pool, since edits to the copied code may modify // the constant pool. AllocationResult allocation = CopyConstantPoolArray(code->constant_pool()); if (!allocation.To(&new_constant_pool)) return allocation; } else { new_constant_pool = empty_constant_pool_array(); } int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment); int new_obj_size = Code::SizeFor(new_body_size); Address old_addr = code->address(); size_t relocation_offset = static_cast<size_t>(code->instruction_end() - old_addr); AllocationResult allocation; if (new_obj_size > code_space()->AreaSize()) { allocation = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE); } else { allocation = AllocateRaw(new_obj_size, CODE_SPACE, CODE_SPACE); } HeapObject* result; if (!allocation.To(&result)) return allocation; // Copy code object. Address new_addr = result->address(); // Copy header and instructions. CopyBytes(new_addr, old_addr, relocation_offset); Code* new_code = Code::cast(result); new_code->set_relocation_info(reloc_info_array); // Update constant pool. new_code->set_constant_pool(new_constant_pool); // Copy patched rinfo. CopyBytes(new_code->relocation_start(), reloc_info.start(), static_cast<size_t>(reloc_info.length())); // Relocate the copy. ASSERT(!isolate_->code_range()->exists() || isolate_->code_range()->contains(code->address())); new_code->Relocate(new_addr - old_addr); #ifdef VERIFY_HEAP if (FLAG_verify_heap) code->ObjectVerify(); #endif return new_code; } void Heap::InitializeAllocationMemento(AllocationMemento* memento, AllocationSite* allocation_site) { memento->set_map_no_write_barrier(allocation_memento_map()); ASSERT(allocation_site->map() == allocation_site_map()); memento->set_allocation_site(allocation_site, SKIP_WRITE_BARRIER); if (FLAG_allocation_site_pretenuring) { allocation_site->IncrementMementoCreateCount(); } } AllocationResult Heap::Allocate(Map* map, AllocationSpace space, AllocationSite* allocation_site) { ASSERT(gc_state_ == NOT_IN_GC); ASSERT(map->instance_type() != MAP_TYPE); // If allocation failures are disallowed, we may allocate in a different // space when new space is full and the object is not a large object. AllocationSpace retry_space = (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type()); int size = map->instance_size(); if (allocation_site != NULL) { size += AllocationMemento::kSize; } HeapObject* result; AllocationResult allocation = AllocateRaw(size, space, retry_space); if (!allocation.To(&result)) return allocation; // No need for write barrier since object is white and map is in old space. result->set_map_no_write_barrier(map); if (allocation_site != NULL) { AllocationMemento* alloc_memento = reinterpret_cast<AllocationMemento*>( reinterpret_cast<Address>(result) + map->instance_size()); InitializeAllocationMemento(alloc_memento, allocation_site); } return result; } AllocationResult Heap::AllocateArgumentsObject(Object* callee, int length) { // To get fast allocation and map sharing for arguments objects we // allocate them based on an arguments boilerplate. JSObject* boilerplate; int arguments_object_size; bool strict_mode_callee = callee->IsJSFunction() && JSFunction::cast(callee)->shared()->strict_mode() == STRICT; if (strict_mode_callee) { boilerplate = isolate()->context()->native_context()->strict_arguments_boilerplate(); arguments_object_size = kStrictArgumentsObjectSize; } else { boilerplate = isolate()->context()->native_context()->sloppy_arguments_boilerplate(); arguments_object_size = kSloppyArgumentsObjectSize; } // Check that the size of the boilerplate matches our // expectations. The ArgumentsAccessStub::GenerateNewObject relies // on the size being a known constant. ASSERT(arguments_object_size == boilerplate->map()->instance_size()); // Do the allocation. HeapObject* result; { AllocationResult allocation = AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE); if (!allocation.To(&result)) return allocation; } // Copy the content. The arguments boilerplate doesn't have any // fields that point to new space so it's safe to skip the write // barrier here. CopyBlock(result->address(), boilerplate->address(), JSObject::kHeaderSize); // Set the length property. JSObject* js_obj = JSObject::cast(result); js_obj->InObjectPropertyAtPut( kArgumentsLengthIndex, Smi::FromInt(length), SKIP_WRITE_BARRIER); // Set the callee property for sloppy mode arguments object only. if (!strict_mode_callee) { js_obj->InObjectPropertyAtPut(kArgumentsCalleeIndex, callee); } // Check the state of the object ASSERT(js_obj->HasFastProperties()); ASSERT(js_obj->HasFastObjectElements()); return js_obj; } void Heap::InitializeJSObjectFromMap(JSObject* obj, FixedArray* properties, Map* map) { obj->set_properties(properties); obj->initialize_elements(); // TODO(1240798): Initialize the object's body using valid initial values // according to the object's initial map. For example, if the map's // instance type is JS_ARRAY_TYPE, the length field should be initialized // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object // verification code has to cope with (temporarily) invalid objects. See // for example, JSArray::JSArrayVerify). Object* filler; // We cannot always fill with one_pointer_filler_map because objects // created from API functions expect their internal fields to be initialized // with undefined_value. // Pre-allocated fields need to be initialized with undefined_value as well // so that object accesses before the constructor completes (e.g. in the // debugger) will not cause a crash. if (map->constructor()->IsJSFunction() && JSFunction::cast(map->constructor())->shared()-> IsInobjectSlackTrackingInProgress()) { // We might want to shrink the object later. ASSERT(obj->GetInternalFieldCount() == 0); filler = Heap::one_pointer_filler_map(); } else { filler = Heap::undefined_value(); } obj->InitializeBody(map, Heap::undefined_value(), filler); } AllocationResult Heap::AllocateJSObjectFromMap( Map* map, PretenureFlag pretenure, bool allocate_properties, AllocationSite* allocation_site) { // JSFunctions should be allocated using AllocateFunction to be // properly initialized. ASSERT(map->instance_type() != JS_FUNCTION_TYPE); // Both types of global objects should be allocated using // AllocateGlobalObject to be properly initialized. ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE); ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE); // Allocate the backing storage for the properties. FixedArray* properties; if (allocate_properties) { int prop_size = map->InitialPropertiesLength(); ASSERT(prop_size >= 0); { AllocationResult allocation = AllocateFixedArray(prop_size, pretenure); if (!allocation.To(&properties)) return allocation; } } else { properties = empty_fixed_array(); } // Allocate the JSObject. int size = map->instance_size(); AllocationSpace space = SelectSpace(size, OLD_POINTER_SPACE, pretenure); JSObject* js_obj; AllocationResult allocation = Allocate(map, space, allocation_site); if (!allocation.To(&js_obj)) return allocation; // Initialize the JSObject. InitializeJSObjectFromMap(js_obj, properties, map); ASSERT(js_obj->HasFastElements() || js_obj->HasExternalArrayElements() || js_obj->HasFixedTypedArrayElements()); return js_obj; } AllocationResult Heap::AllocateJSObject(JSFunction* constructor, PretenureFlag pretenure, AllocationSite* allocation_site) { ASSERT(constructor->has_initial_map()); // Allocate the object based on the constructors initial map. AllocationResult allocation = AllocateJSObjectFromMap( constructor->initial_map(), pretenure, true, allocation_site); #ifdef DEBUG // Make sure result is NOT a global object if valid. HeapObject* obj; ASSERT(!allocation.To(&obj) || !obj->IsGlobalObject()); #endif return allocation; } AllocationResult Heap::CopyJSObject(JSObject* source, AllocationSite* site) { // Never used to copy functions. If functions need to be copied we // have to be careful to clear the literals array. SLOW_ASSERT(!source->IsJSFunction()); // Make the clone. Map* map = source->map(); int object_size = map->instance_size(); HeapObject* clone; ASSERT(site == NULL || AllocationSite::CanTrack(map->instance_type())); WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER; // If we're forced to always allocate, we use the general allocation // functions which may leave us with an object in old space. if (always_allocate()) { { AllocationResult allocation = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE); if (!allocation.To(&clone)) return allocation; } Address clone_address = clone->address(); CopyBlock(clone_address, source->address(), object_size); // Update write barrier for all fields that lie beyond the header. RecordWrites(clone_address, JSObject::kHeaderSize, (object_size - JSObject::kHeaderSize) / kPointerSize); } else { wb_mode = SKIP_WRITE_BARRIER; { int adjusted_object_size = site != NULL ? object_size + AllocationMemento::kSize : object_size; AllocationResult allocation = AllocateRaw(adjusted_object_size, NEW_SPACE, NEW_SPACE); if (!allocation.To(&clone)) return allocation; } SLOW_ASSERT(InNewSpace(clone)); // Since we know the clone is allocated in new space, we can copy // the contents without worrying about updating the write barrier. CopyBlock(clone->address(), source->address(), object_size); if (site != NULL) { AllocationMemento* alloc_memento = reinterpret_cast<AllocationMemento*>( reinterpret_cast<Address>(clone) + object_size); InitializeAllocationMemento(alloc_memento, site); } } SLOW_ASSERT( JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind()); FixedArrayBase* elements = FixedArrayBase::cast(source->elements()); FixedArray* properties = FixedArray::cast(source->properties()); // Update elements if necessary. if (elements->length() > 0) { FixedArrayBase* elem; { AllocationResult allocation; if (elements->map() == fixed_cow_array_map()) { allocation = FixedArray::cast(elements); } else if (source->HasFastDoubleElements()) { allocation = CopyFixedDoubleArray(FixedDoubleArray::cast(elements)); } else { allocation = CopyFixedArray(FixedArray::cast(elements)); } if (!allocation.To(&elem)) return allocation; } JSObject::cast(clone)->set_elements(elem, wb_mode); } // Update properties if necessary. if (properties->length() > 0) { FixedArray* prop; { AllocationResult allocation = CopyFixedArray(properties); if (!allocation.To(&prop)) return allocation; } JSObject::cast(clone)->set_properties(prop, wb_mode); } // Return the new clone. return clone; } AllocationResult Heap::AllocateStringFromUtf8Slow(Vector<const char> string, int non_ascii_start, PretenureFlag pretenure) { // Continue counting the number of characters in the UTF-8 string, starting // from the first non-ascii character or word. Access<UnicodeCache::Utf8Decoder> decoder(isolate_->unicode_cache()->utf8_decoder()); decoder->Reset(string.start() + non_ascii_start, string.length() - non_ascii_start); int utf16_length = decoder->Utf16Length(); ASSERT(utf16_length > 0); // Allocate string. HeapObject* result; { int chars = non_ascii_start + utf16_length; AllocationResult allocation = AllocateRawTwoByteString(chars, pretenure); if (!allocation.To(&result) || result->IsException()) { return allocation; } } // Copy ascii portion. uint16_t* data = SeqTwoByteString::cast(result)->GetChars(); if (non_ascii_start != 0) { const char* ascii_data = string.start(); for (int i = 0; i < non_ascii_start; i++) { *data++ = *ascii_data++; } } // Now write the remainder. decoder->WriteUtf16(data, utf16_length); return result; } AllocationResult Heap::AllocateStringFromTwoByte(Vector<const uc16> string, PretenureFlag pretenure) { // Check if the string is an ASCII string. HeapObject* result; int length = string.length(); const uc16* start = string.start(); if (String::IsOneByte(start, length)) { AllocationResult allocation = AllocateRawOneByteString(length, pretenure); if (!allocation.To(&result) || result->IsException()) { return allocation; } CopyChars(SeqOneByteString::cast(result)->GetChars(), start, length); } else { // It's not a one byte string. AllocationResult allocation = AllocateRawTwoByteString(length, pretenure); if (!allocation.To(&result) || result->IsException()) { return allocation; } CopyChars(SeqTwoByteString::cast(result)->GetChars(), start, length); } return result; } static inline void WriteOneByteData(Vector<const char> vector, uint8_t* chars, int len) { // Only works for ascii. ASSERT(vector.length() == len); OS::MemCopy(chars, vector.start(), len); } static inline void WriteTwoByteData(Vector<const char> vector, uint16_t* chars, int len) { const uint8_t* stream = reinterpret_cast<const uint8_t*>(vector.start()); unsigned stream_length = vector.length(); while (stream_length != 0) { unsigned consumed = 0; uint32_t c = unibrow::Utf8::ValueOf(stream, stream_length, &consumed); ASSERT(c != unibrow::Utf8::kBadChar); ASSERT(consumed <= stream_length); stream_length -= consumed; stream += consumed; if (c > unibrow::Utf16::kMaxNonSurrogateCharCode) { len -= 2; if (len < 0) break; *chars++ = unibrow::Utf16::LeadSurrogate(c); *chars++ = unibrow::Utf16::TrailSurrogate(c); } else { len -= 1; if (len < 0) break; *chars++ = c; } } ASSERT(stream_length == 0); ASSERT(len == 0); } static inline void WriteOneByteData(String* s, uint8_t* chars, int len) { ASSERT(s->length() == len); String::WriteToFlat(s, chars, 0, len); } static inline void WriteTwoByteData(String* s, uint16_t* chars, int len) { ASSERT(s->length() == len); String::WriteToFlat(s, chars, 0, len); } template<bool is_one_byte, typename T> AllocationResult Heap::AllocateInternalizedStringImpl( T t, int chars, uint32_t hash_field) { ASSERT(chars >= 0); // Compute map and object size. int size; Map* map; if (chars < 0 || chars > String::kMaxLength) { return isolate()->ThrowInvalidStringLength(); } if (is_one_byte) { map = ascii_internalized_string_map(); size = SeqOneByteString::SizeFor(chars); } else { map = internalized_string_map(); size = SeqTwoByteString::SizeFor(chars); } AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, TENURED); // Allocate string. HeapObject* result; { AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE); if (!allocation.To(&result)) return allocation; } result->set_map_no_write_barrier(map); // Set length and hash fields of the allocated string. String* answer = String::cast(result); answer->set_length(chars); answer->set_hash_field(hash_field); ASSERT_EQ(size, answer->Size()); if (is_one_byte) { WriteOneByteData(t, SeqOneByteString::cast(answer)->GetChars(), chars); } else { WriteTwoByteData(t, SeqTwoByteString::cast(answer)->GetChars(), chars); } return answer; } // Need explicit instantiations. template AllocationResult Heap::AllocateInternalizedStringImpl<true>( String*, int, uint32_t); template AllocationResult Heap::AllocateInternalizedStringImpl<false>( String*, int, uint32_t); template AllocationResult Heap::AllocateInternalizedStringImpl<false>( Vector<const char>, int, uint32_t); AllocationResult Heap::AllocateRawOneByteString(int length, PretenureFlag pretenure) { if (length < 0 || length > String::kMaxLength) { return isolate()->ThrowInvalidStringLength(); } int size = SeqOneByteString::SizeFor(length); ASSERT(size <= SeqOneByteString::kMaxSize); AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, pretenure); HeapObject* result; { AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE); if (!allocation.To(&result)) return allocation; } // Partially initialize the object. result->set_map_no_write_barrier(ascii_string_map()); String::cast(result)->set_length(length); String::cast(result)->set_hash_field(String::kEmptyHashField); ASSERT_EQ(size, HeapObject::cast(result)->Size()); return result; } AllocationResult Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) { if (length < 0 || length > String::kMaxLength) { return isolate()->ThrowInvalidStringLength(); } int size = SeqTwoByteString::SizeFor(length); ASSERT(size <= SeqTwoByteString::kMaxSize); AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, pretenure); HeapObject* result; { AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE); if (!allocation.To(&result)) return allocation; } // Partially initialize the object. result->set_map_no_write_barrier(string_map()); String::cast(result)->set_length(length); String::cast(result)->set_hash_field(String::kEmptyHashField); ASSERT_EQ(size, HeapObject::cast(result)->Size()); return result; } AllocationResult Heap::AllocateEmptyFixedArray() { int size = FixedArray::SizeFor(0); HeapObject* result; { AllocationResult allocation = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE); if (!allocation.To(&result)) return allocation; } // Initialize the object. result->set_map_no_write_barrier(fixed_array_map()); FixedArray::cast(result)->set_length(0); return result; } AllocationResult Heap::AllocateEmptyExternalArray( ExternalArrayType array_type) { return AllocateExternalArray(0, array_type, NULL, TENURED); } AllocationResult Heap::CopyAndTenureFixedCOWArray(FixedArray* src) { if (!InNewSpace(src)) { return src; } int len = src->length(); HeapObject* obj; { AllocationResult allocation = AllocateRawFixedArray(len, TENURED); if (!allocation.To(&obj)) return allocation; } obj->set_map_no_write_barrier(fixed_array_map()); FixedArray* result = FixedArray::cast(obj); result->set_length(len); // Copy the content DisallowHeapAllocation no_gc; WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc); for (int i = 0; i < len; i++) result->set(i, src->get(i), mode); // TODO(mvstanton): The map is set twice because of protection against calling // set() on a COW FixedArray. Issue v8:3221 created to track this, and // we might then be able to remove this whole method. HeapObject::cast(obj)->set_map_no_write_barrier(fixed_cow_array_map()); return result; } AllocationResult Heap::AllocateEmptyFixedTypedArray( ExternalArrayType array_type) { return AllocateFixedTypedArray(0, array_type, TENURED); } AllocationResult Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) { int len = src->length(); HeapObject* obj; { AllocationResult allocation = AllocateRawFixedArray(len, NOT_TENURED); if (!allocation.To(&obj)) return allocation; } if (InNewSpace(obj)) { obj->set_map_no_write_barrier(map); CopyBlock(obj->address() + kPointerSize, src->address() + kPointerSize, FixedArray::SizeFor(len) - kPointerSize); return obj; } obj->set_map_no_write_barrier(map); FixedArray* result = FixedArray::cast(obj); result->set_length(len); // Copy the content DisallowHeapAllocation no_gc; WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc); for (int i = 0; i < len; i++) result->set(i, src->get(i), mode); return result; } AllocationResult Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src, Map* map) { int len = src->length(); HeapObject* obj; { AllocationResult allocation = AllocateRawFixedDoubleArray(len, NOT_TENURED); if (!allocation.To(&obj)) return allocation; } obj->set_map_no_write_barrier(map); CopyBlock( obj->address() + FixedDoubleArray::kLengthOffset, src->address() + FixedDoubleArray::kLengthOffset, FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset); return obj; } AllocationResult Heap::CopyConstantPoolArrayWithMap(ConstantPoolArray* src, Map* map) { int int64_entries = src->count_of_int64_entries(); int code_ptr_entries = src->count_of_code_ptr_entries(); int heap_ptr_entries = src->count_of_heap_ptr_entries(); int int32_entries = src->count_of_int32_entries(); HeapObject* obj; { AllocationResult allocation = AllocateConstantPoolArray(int64_entries, code_ptr_entries, heap_ptr_entries, int32_entries); if (!allocation.To(&obj)) return allocation; } obj->set_map_no_write_barrier(map); int size = ConstantPoolArray::SizeFor( int64_entries, code_ptr_entries, heap_ptr_entries, int32_entries); CopyBlock( obj->address() + ConstantPoolArray::kLengthOffset, src->address() + ConstantPoolArray::kLengthOffset, size - ConstantPoolArray::kLengthOffset); return obj; } AllocationResult Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) { if (length < 0 || length > FixedArray::kMaxLength) { v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true); } int size = FixedArray::SizeFor(length); AllocationSpace space = SelectSpace(size, OLD_POINTER_SPACE, pretenure); return AllocateRaw(size, space, OLD_POINTER_SPACE); } AllocationResult Heap::AllocateFixedArrayWithFiller(int length, PretenureFlag pretenure, Object* filler) { ASSERT(length >= 0); ASSERT(empty_fixed_array()->IsFixedArray()); if (length == 0) return empty_fixed_array(); ASSERT(!InNewSpace(filler)); HeapObject* result; { AllocationResult allocation = AllocateRawFixedArray(length, pretenure); if (!allocation.To(&result)) return allocation; } result->set_map_no_write_barrier(fixed_array_map()); FixedArray* array = FixedArray::cast(result); array->set_length(length); MemsetPointer(array->data_start(), filler, length); return array; } AllocationResult Heap::AllocateFixedArray(int length, PretenureFlag pretenure) { return AllocateFixedArrayWithFiller(length, pretenure, undefined_value()); } AllocationResult Heap::AllocateUninitializedFixedArray(int length) { if (length == 0) return empty_fixed_array(); HeapObject* obj; { AllocationResult allocation = AllocateRawFixedArray(length, NOT_TENURED); if (!allocation.To(&obj)) return allocation; } obj->set_map_no_write_barrier(fixed_array_map()); FixedArray::cast(obj)->set_length(length); return obj; } AllocationResult Heap::AllocateUninitializedFixedDoubleArray( int length, PretenureFlag pretenure) { if (length == 0) return empty_fixed_array(); HeapObject* elements; AllocationResult allocation = AllocateRawFixedDoubleArray(length, pretenure); if (!allocation.To(&elements)) return allocation; elements->set_map_no_write_barrier(fixed_double_array_map()); FixedDoubleArray::cast(elements)->set_length(length); return elements; } AllocationResult Heap::AllocateRawFixedDoubleArray(int length, PretenureFlag pretenure) { if (length < 0 || length > FixedDoubleArray::kMaxLength) { v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true); } int size = FixedDoubleArray::SizeFor(length); #ifndef V8_HOST_ARCH_64_BIT size += kPointerSize; #endif AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, pretenure); HeapObject* object; { AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE); if (!allocation.To(&object)) return allocation; } return EnsureDoubleAligned(this, object, size); } AllocationResult Heap::AllocateConstantPoolArray(int number_of_int64_entries, int number_of_code_ptr_entries, int number_of_heap_ptr_entries, int number_of_int32_entries) { CHECK(number_of_int64_entries >= 0 && number_of_int64_entries <= ConstantPoolArray::kMaxEntriesPerType && number_of_code_ptr_entries >= 0 && number_of_code_ptr_entries <= ConstantPoolArray::kMaxEntriesPerType && number_of_heap_ptr_entries >= 0 && number_of_heap_ptr_entries <= ConstantPoolArray::kMaxEntriesPerType && number_of_int32_entries >= 0 && number_of_int32_entries <= ConstantPoolArray::kMaxEntriesPerType); int size = ConstantPoolArray::SizeFor(number_of_int64_entries, number_of_code_ptr_entries, number_of_heap_ptr_entries, number_of_int32_entries); #ifndef V8_HOST_ARCH_64_BIT size += kPointerSize; #endif AllocationSpace space = SelectSpace(size, OLD_POINTER_SPACE, TENURED); HeapObject* object; { AllocationResult allocation = AllocateRaw(size, space, OLD_POINTER_SPACE); if (!allocation.To(&object)) return allocation; } object = EnsureDoubleAligned(this, object, size); object->set_map_no_write_barrier(constant_pool_array_map()); ConstantPoolArray* constant_pool = ConstantPoolArray::cast(object); constant_pool->Init(number_of_int64_entries, number_of_code_ptr_entries, number_of_heap_ptr_entries, number_of_int32_entries); if (number_of_code_ptr_entries > 0) { int offset = constant_pool->OffsetOfElementAt(constant_pool->first_code_ptr_index()); MemsetPointer( reinterpret_cast<Address*>(HeapObject::RawField(constant_pool, offset)), isolate()->builtins()->builtin(Builtins::kIllegal)->entry(), number_of_code_ptr_entries); } if (number_of_heap_ptr_entries > 0) { int offset = constant_pool->OffsetOfElementAt(constant_pool->first_heap_ptr_index()); MemsetPointer( HeapObject::RawField(constant_pool, offset), undefined_value(), number_of_heap_ptr_entries); } return constant_pool; } AllocationResult Heap::AllocateEmptyConstantPoolArray() { int size = ConstantPoolArray::SizeFor(0, 0, 0, 0); HeapObject* result; { AllocationResult allocation = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE); if (!allocation.To(&result)) return allocation; } result->set_map_no_write_barrier(constant_pool_array_map()); ConstantPoolArray::cast(result)->Init(0, 0, 0, 0); return result; } AllocationResult Heap::AllocateSymbol() { // Statically ensure that it is safe to allocate symbols in paged spaces. STATIC_ASSERT(Symbol::kSize <= Page::kMaxRegularHeapObjectSize); HeapObject* result; AllocationResult allocation = AllocateRaw(Symbol::kSize, OLD_POINTER_SPACE, OLD_POINTER_SPACE); if (!allocation.To(&result)) return allocation; result->set_map_no_write_barrier(symbol_map()); // Generate a random hash value. int hash; int attempts = 0; do { hash = isolate()->random_number_generator()->NextInt() & Name::kHashBitMask; attempts++; } while (hash == 0 && attempts < 30); if (hash == 0) hash = 1; // never return 0 Symbol::cast(result)->set_hash_field( Name::kIsNotArrayIndexMask | (hash << Name::kHashShift)); Symbol::cast(result)->set_name(undefined_value()); Symbol::cast(result)->set_flags(Smi::FromInt(0)); ASSERT(!Symbol::cast(result)->is_private()); return result; } AllocationResult Heap::AllocateStruct(InstanceType type) { Map* map; switch (type) { #define MAKE_CASE(NAME, Name, name) \ case NAME##_TYPE: map = name##_map(); break; STRUCT_LIST(MAKE_CASE) #undef MAKE_CASE default: UNREACHABLE(); return exception(); } int size = map->instance_size(); AllocationSpace space = SelectSpace(size, OLD_POINTER_SPACE, TENURED); Struct* result; { AllocationResult allocation = Allocate(map, space); if (!allocation.To(&result)) return allocation; } result->InitializeBody(size); return result; } bool Heap::IsHeapIterable() { return (!old_pointer_space()->was_swept_conservatively() && !old_data_space()->was_swept_conservatively()); } void Heap::EnsureHeapIsIterable() { ASSERT(AllowHeapAllocation::IsAllowed()); if (!IsHeapIterable()) { CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable"); } ASSERT(IsHeapIterable()); } void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) { incremental_marking()->Step(step_size, IncrementalMarking::NO_GC_VIA_STACK_GUARD); if (incremental_marking()->IsComplete()) { bool uncommit = false; if (gc_count_at_last_idle_gc_ == gc_count_) { // No GC since the last full GC, the mutator is probably not active. isolate_->compilation_cache()->Clear(); uncommit = true; } CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental"); mark_sweeps_since_idle_round_started_++; gc_count_at_last_idle_gc_ = gc_count_; if (uncommit) { new_space_.Shrink(); UncommitFromSpace(); } } } bool Heap::IdleNotification(int hint) { // Hints greater than this value indicate that // the embedder is requesting a lot of GC work. const int kMaxHint = 1000; const int kMinHintForIncrementalMarking = 10; // Minimal hint that allows to do full GC. const int kMinHintForFullGC = 100; intptr_t size_factor = Min(Max(hint, 20), kMaxHint) / 4; // The size factor is in range [5..250]. The numbers here are chosen from // experiments. If you changes them, make sure to test with // chrome/performance_ui_tests --gtest_filter="GeneralMixMemoryTest.* intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold; if (contexts_disposed_ > 0) { contexts_disposed_ = 0; int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000); if (hint >= mark_sweep_time && !FLAG_expose_gc && incremental_marking()->IsStopped()) { HistogramTimerScope scope(isolate_->counters()->gc_context()); CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification: contexts disposed"); } else { AdvanceIdleIncrementalMarking(step_size); } // After context disposal there is likely a lot of garbage remaining, reset // the idle notification counters in order to trigger more incremental GCs // on subsequent idle notifications. StartIdleRound(); return false; } if (!FLAG_incremental_marking || Serializer::enabled(isolate_)) { return IdleGlobalGC(); } // By doing small chunks of GC work in each IdleNotification, // perform a round of incremental GCs and after that wait until // the mutator creates enough garbage to justify a new round. // An incremental GC progresses as follows: // 1. many incremental marking steps, // 2. one old space mark-sweep-compact, // Use mark-sweep-compact events to count incremental GCs in a round. if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) { if (EnoughGarbageSinceLastIdleRound()) { StartIdleRound(); } else { return true; } } int remaining_mark_sweeps = kMaxMarkSweepsInIdleRound - mark_sweeps_since_idle_round_started_; if (incremental_marking()->IsStopped()) { // If there are no more than two GCs left in this idle round and we are // allowed to do a full GC, then make those GCs full in order to compact // the code space. // TODO(ulan): Once we enable code compaction for incremental marking, // we can get rid of this special case and always start incremental marking. if (remaining_mark_sweeps <= 2 && hint >= kMinHintForFullGC) { CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification: finalize idle round"); mark_sweeps_since_idle_round_started_++; } else if (hint > kMinHintForIncrementalMarking) { incremental_marking()->Start(); } } if (!incremental_marking()->IsStopped() && hint > kMinHintForIncrementalMarking) { AdvanceIdleIncrementalMarking(step_size); } if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) { FinishIdleRound(); return true; } // If the IdleNotifcation is called with a large hint we will wait for // the sweepter threads here. if (hint >= kMinHintForFullGC && mark_compact_collector()->IsConcurrentSweepingInProgress()) { mark_compact_collector()->WaitUntilSweepingCompleted(); } return false; } bool Heap::IdleGlobalGC() { static const int kIdlesBeforeScavenge = 4; static const int kIdlesBeforeMarkSweep = 7; static const int kIdlesBeforeMarkCompact = 8; static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1; static const unsigned int kGCsBetweenCleanup = 4; if (!last_idle_notification_gc_count_init_) { last_idle_notification_gc_count_ = gc_count_; last_idle_notification_gc_count_init_ = true; } bool uncommit = true; bool finished = false; // Reset the number of idle notifications received when a number of // GCs have taken place. This allows another round of cleanup based // on idle notifications if enough work has been carried out to // provoke a number of garbage collections. if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) { number_idle_notifications_ = Min(number_idle_notifications_ + 1, kMaxIdleCount); } else { number_idle_notifications_ = 0; last_idle_notification_gc_count_ = gc_count_; } if (number_idle_notifications_ == kIdlesBeforeScavenge) { CollectGarbage(NEW_SPACE, "idle notification"); new_space_.Shrink(); last_idle_notification_gc_count_ = gc_count_; } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) { // Before doing the mark-sweep collections we clear the // compilation cache to avoid hanging on to source code and // generated code for cached functions. isolate_->compilation_cache()->Clear(); CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification"); new_space_.Shrink(); last_idle_notification_gc_count_ = gc_count_; } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) { CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification"); new_space_.Shrink(); last_idle_notification_gc_count_ = gc_count_; number_idle_notifications_ = 0; finished = true; } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) { // If we have received more than kIdlesBeforeMarkCompact idle // notifications we do not perform any cleanup because we don't // expect to gain much by doing so. finished = true; } if (uncommit) UncommitFromSpace(); return finished; } #ifdef DEBUG void Heap::Print() { if (!HasBeenSetUp()) return; isolate()->PrintStack(stdout); AllSpaces spaces(this); for (Space* space = spaces.next(); space != NULL; space = spaces.next()) { space->Print(); } } void Heap::ReportCodeStatistics(const char* title) { PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title); PagedSpace::ResetCodeStatistics(isolate()); // We do not look for code in new space, map space, or old space. If code // somehow ends up in those spaces, we would miss it here. code_space_->CollectCodeStatistics(); lo_space_->CollectCodeStatistics(); PagedSpace::ReportCodeStatistics(isolate()); } // This function expects that NewSpace's allocated objects histogram is // populated (via a call to CollectStatistics or else as a side effect of a // just-completed scavenge collection). void Heap::ReportHeapStatistics(const char* title) { USE(title); PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n", title, gc_count_); PrintF("old_generation_allocation_limit_ %" V8_PTR_PREFIX "d\n", old_generation_allocation_limit_); PrintF("\n"); PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles(isolate_)); isolate_->global_handles()->PrintStats(); PrintF("\n"); PrintF("Heap statistics : "); isolate_->memory_allocator()->ReportStatistics(); PrintF("To space : "); new_space_.ReportStatistics(); PrintF("Old pointer space : "); old_pointer_space_->ReportStatistics(); PrintF("Old data space : "); old_data_space_->ReportStatistics(); PrintF("Code space : "); code_space_->ReportStatistics(); PrintF("Map space : "); map_space_->ReportStatistics(); PrintF("Cell space : "); cell_space_->ReportStatistics(); PrintF("PropertyCell space : "); property_cell_space_->ReportStatistics(); PrintF("Large object space : "); lo_space_->ReportStatistics(); PrintF(">>>>>> ========================================= >>>>>>\n"); } #endif // DEBUG bool Heap::Contains(HeapObject* value) { return Contains(value->address()); } bool Heap::Contains(Address addr) { if (isolate_->memory_allocator()->IsOutsideAllocatedSpace(addr)) return false; return HasBeenSetUp() && (new_space_.ToSpaceContains(addr) || old_pointer_space_->Contains(addr) || old_data_space_->Contains(addr) || code_space_->Contains(addr) || map_space_->Contains(addr) || cell_space_->Contains(addr) || property_cell_space_->Contains(addr) || lo_space_->SlowContains(addr)); } bool Heap::InSpace(HeapObject* value, AllocationSpace space) { return InSpace(value->address(), space); } bool Heap::InSpace(Address addr, AllocationSpace space) { if (isolate_->memory_allocator()->IsOutsideAllocatedSpace(addr)) return false; if (!HasBeenSetUp()) return false; switch (space) { case NEW_SPACE: return new_space_.ToSpaceContains(addr); case OLD_POINTER_SPACE: return old_pointer_space_->Contains(addr); case OLD_DATA_SPACE: return old_data_space_->Contains(addr); case CODE_SPACE: return code_space_->Contains(addr); case MAP_SPACE: return map_space_->Contains(addr); case CELL_SPACE: return cell_space_->Contains(addr); case PROPERTY_CELL_SPACE: return property_cell_space_->Contains(addr); case LO_SPACE: return lo_space_->SlowContains(addr); case INVALID_SPACE: break; } UNREACHABLE(); return false; } #ifdef VERIFY_HEAP void Heap::Verify() { CHECK(HasBeenSetUp()); HandleScope scope(isolate()); store_buffer()->Verify(); VerifyPointersVisitor visitor; IterateRoots(&visitor, VISIT_ONLY_STRONG); VerifySmisVisitor smis_visitor; IterateSmiRoots(&smis_visitor); new_space_.Verify(); old_pointer_space_->Verify(&visitor); map_space_->Verify(&visitor); VerifyPointersVisitor no_dirty_regions_visitor; old_data_space_->Verify(&no_dirty_regions_visitor); code_space_->Verify(&no_dirty_regions_visitor); cell_space_->Verify(&no_dirty_regions_visitor); property_cell_space_->Verify(&no_dirty_regions_visitor); lo_space_->Verify(); } #endif void Heap::ZapFromSpace() { NewSpacePageIterator it(new_space_.FromSpaceStart(), new_space_.FromSpaceEnd()); while (it.has_next()) { NewSpacePage* page = it.next(); for (Address cursor = page->area_start(), limit = page->area_end(); cursor < limit; cursor += kPointerSize) { Memory::Address_at(cursor) = kFromSpaceZapValue; } } } void Heap::IterateAndMarkPointersToFromSpace(Address start, Address end, ObjectSlotCallback callback) { Address slot_address = start; // We are not collecting slots on new space objects during mutation // thus we have to scan for pointers to evacuation candidates when we // promote objects. But we should not record any slots in non-black // objects. Grey object's slots would be rescanned. // White object might not survive until the end of collection // it would be a violation of the invariant to record it's slots. bool record_slots = false; if (incremental_marking()->IsCompacting()) { MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start)); record_slots = Marking::IsBlack(mark_bit); } while (slot_address < end) { Object** slot = reinterpret_cast<Object**>(slot_address); Object* object = *slot; // If the store buffer becomes overfull we mark pages as being exempt from // the store buffer. These pages are scanned to find pointers that point // to the new space. In that case we may hit newly promoted objects and // fix the pointers before the promotion queue gets to them. Thus the 'if'. if (object->IsHeapObject()) { if (Heap::InFromSpace(object)) { callback(reinterpret_cast<HeapObject**>(slot), HeapObject::cast(object)); Object* new_object = *slot; if (InNewSpace(new_object)) { SLOW_ASSERT(Heap::InToSpace(new_object)); SLOW_ASSERT(new_object->IsHeapObject()); store_buffer_.EnterDirectlyIntoStoreBuffer( reinterpret_cast<Address>(slot)); } SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object)); } else if (record_slots && MarkCompactCollector::IsOnEvacuationCandidate(object)) { mark_compact_collector()->RecordSlot(slot, slot, object); } } slot_address += kPointerSize; } } #ifdef DEBUG typedef bool (*CheckStoreBufferFilter)(Object** addr); bool IsAMapPointerAddress(Object** addr) { uintptr_t a = reinterpret_cast<uintptr_t>(addr); int mod = a % Map::kSize; return mod >= Map::kPointerFieldsBeginOffset && mod < Map::kPointerFieldsEndOffset; } bool EverythingsAPointer(Object** addr) { return true; } static void CheckStoreBuffer(Heap* heap, Object** current, Object** limit, Object**** store_buffer_position, Object*** store_buffer_top, CheckStoreBufferFilter filter, Address special_garbage_start, Address special_garbage_end) { Map* free_space_map = heap->free_space_map(); for ( ; current < limit; current++) { Object* o = *current; Address current_address = reinterpret_cast<Address>(current); // Skip free space. if (o == free_space_map) { Address current_address = reinterpret_cast<Address>(current); FreeSpace* free_space = FreeSpace::cast(HeapObject::FromAddress(current_address)); int skip = free_space->Size(); ASSERT(current_address + skip <= reinterpret_cast<Address>(limit)); ASSERT(skip > 0); current_address += skip - kPointerSize; current = reinterpret_cast<Object**>(current_address); continue; } // Skip the current linear allocation space between top and limit which is // unmarked with the free space map, but can contain junk. if (current_address == special_garbage_start && special_garbage_end != special_garbage_start) { current_address = special_garbage_end - kPointerSize; current = reinterpret_cast<Object**>(current_address); continue; } if (!(*filter)(current)) continue; ASSERT(current_address < special_garbage_start || current_address >= special_garbage_end); ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue); // We have to check that the pointer does not point into new space // without trying to cast it to a heap object since the hash field of // a string can contain values like 1 and 3 which are tagged null // pointers. if (!heap->InNewSpace(o)) continue; while (**store_buffer_position < current && *store_buffer_position < store_buffer_top) { (*store_buffer_position)++; } if (**store_buffer_position != current || *store_buffer_position == store_buffer_top) { Object** obj_start = current; while (!(*obj_start)->IsMap()) obj_start--; UNREACHABLE(); } } } // Check that the store buffer contains all intergenerational pointers by // scanning a page and ensuring that all pointers to young space are in the // store buffer. void Heap::OldPointerSpaceCheckStoreBuffer() { OldSpace* space = old_pointer_space(); PageIterator pages(space); store_buffer()->SortUniq(); while (pages.has_next()) { Page* page = pages.next(); Object** current = reinterpret_cast<Object**>(page->area_start()); Address end = page->area_end(); Object*** store_buffer_position = store_buffer()->Start(); Object*** store_buffer_top = store_buffer()->Top(); Object** limit = reinterpret_cast<Object**>(end); CheckStoreBuffer(this, current, limit, &store_buffer_position, store_buffer_top, &EverythingsAPointer, space->top(), space->limit()); } } void Heap::MapSpaceCheckStoreBuffer() { MapSpace* space = map_space(); PageIterator pages(space); store_buffer()->SortUniq(); while (pages.has_next()) { Page* page = pages.next(); Object** current = reinterpret_cast<Object**>(page->area_start()); Address end = page->area_end(); Object*** store_buffer_position = store_buffer()->Start(); Object*** store_buffer_top = store_buffer()->Top(); Object** limit = reinterpret_cast<Object**>(end); CheckStoreBuffer(this, current, limit, &store_buffer_position, store_buffer_top, &IsAMapPointerAddress, space->top(), space->limit()); } } void Heap::LargeObjectSpaceCheckStoreBuffer() { LargeObjectIterator it(lo_space()); for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) { // We only have code, sequential strings, or fixed arrays in large // object space, and only fixed arrays can possibly contain pointers to // the young generation. if (object->IsFixedArray()) { Object*** store_buffer_position = store_buffer()->Start(); Object*** store_buffer_top = store_buffer()->Top(); Object** current = reinterpret_cast<Object**>(object->address()); Object** limit = reinterpret_cast<Object**>(object->address() + object->Size()); CheckStoreBuffer(this, current, limit, &store_buffer_position, store_buffer_top, &EverythingsAPointer, NULL, NULL); } } } #endif void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) { IterateStrongRoots(v, mode); IterateWeakRoots(v, mode); } void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) { v->VisitPointer(reinterpret_cast<Object**>(&roots_[kStringTableRootIndex])); v->Synchronize(VisitorSynchronization::kStringTable); if (mode != VISIT_ALL_IN_SCAVENGE && mode != VISIT_ALL_IN_SWEEP_NEWSPACE) { // Scavenge collections have special processing for this. external_string_table_.Iterate(v); } v->Synchronize(VisitorSynchronization::kExternalStringsTable); } void Heap::IterateSmiRoots(ObjectVisitor* v) { // Acquire execution access since we are going to read stack limit values. ExecutionAccess access(isolate()); v->VisitPointers(&roots_[kSmiRootsStart], &roots_[kRootListLength]); v->Synchronize(VisitorSynchronization::kSmiRootList); } void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) { v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]); v->Synchronize(VisitorSynchronization::kStrongRootList); v->VisitPointer(BitCast<Object**>(&hidden_string_)); v->Synchronize(VisitorSynchronization::kInternalizedString); isolate_->bootstrapper()->Iterate(v); v->Synchronize(VisitorSynchronization::kBootstrapper); isolate_->Iterate(v); v->Synchronize(VisitorSynchronization::kTop); Relocatable::Iterate(isolate_, v); v->Synchronize(VisitorSynchronization::kRelocatable); if (isolate_->deoptimizer_data() != NULL) { isolate_->deoptimizer_data()->Iterate(v); } v->Synchronize(VisitorSynchronization::kDebug); isolate_->compilation_cache()->Iterate(v); v->Synchronize(VisitorSynchronization::kCompilationCache); // Iterate over local handles in handle scopes. isolate_->handle_scope_implementer()->Iterate(v); isolate_->IterateDeferredHandles(v); v->Synchronize(VisitorSynchronization::kHandleScope); // Iterate over the builtin code objects and code stubs in the // heap. Note that it is not necessary to iterate over code objects // on scavenge collections. if (mode != VISIT_ALL_IN_SCAVENGE) { isolate_->builtins()->IterateBuiltins(v); } v->Synchronize(VisitorSynchronization::kBuiltins); // Iterate over global handles. switch (mode) { case VISIT_ONLY_STRONG: isolate_->global_handles()->IterateStrongRoots(v); break; case VISIT_ALL_IN_SCAVENGE: isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v); break; case VISIT_ALL_IN_SWEEP_NEWSPACE: case VISIT_ALL: isolate_->global_handles()->IterateAllRoots(v); break; } v->Synchronize(VisitorSynchronization::kGlobalHandles); // Iterate over eternal handles. if (mode == VISIT_ALL_IN_SCAVENGE) { isolate_->eternal_handles()->IterateNewSpaceRoots(v); } else { isolate_->eternal_handles()->IterateAllRoots(v); } v->Synchronize(VisitorSynchronization::kEternalHandles); // Iterate over pointers being held by inactive threads. isolate_->thread_manager()->Iterate(v); v->Synchronize(VisitorSynchronization::kThreadManager); // Iterate over the pointers the Serialization/Deserialization code is // holding. // During garbage collection this keeps the partial snapshot cache alive. // During deserialization of the startup snapshot this creates the partial // snapshot cache and deserializes the objects it refers to. During // serialization this does nothing, since the partial snapshot cache is // empty. However the next thing we do is create the partial snapshot, // filling up the partial snapshot cache with objects it needs as we go. SerializerDeserializer::Iterate(isolate_, v); // We don't do a v->Synchronize call here, because in debug mode that will // output a flag to the snapshot. However at this point the serializer and // deserializer are deliberately a little unsynchronized (see above) so the // checking of the sync flag in the snapshot would fail. } // TODO(1236194): Since the heap size is configurable on the command line // and through the API, we should gracefully handle the case that the heap // size is not big enough to fit all the initial objects. bool Heap::ConfigureHeap(int max_semispace_size, intptr_t max_old_space_size, intptr_t max_executable_size, intptr_t code_range_size) { if (HasBeenSetUp()) return false; // If max space size flags are specified overwrite the configuration. if (FLAG_max_new_space_size > 0) { max_semispace_size = (FLAG_max_new_space_size / 2) * kLumpOfMemory; } if (FLAG_max_old_space_size > 0) { max_old_space_size = FLAG_max_old_space_size * kLumpOfMemory; } if (FLAG_max_executable_size > 0) { max_executable_size = FLAG_max_executable_size * kLumpOfMemory; } if (FLAG_stress_compaction) { // This will cause more frequent GCs when stressing. max_semispace_size_ = Page::kPageSize; } if (max_semispace_size > 0) { if (max_semispace_size < Page::kPageSize) { max_semispace_size = Page::kPageSize; if (FLAG_trace_gc) { PrintPID("Max semispace size cannot be less than %dkbytes\n", Page::kPageSize >> 10); } } max_semispace_size_ = max_semispace_size; } if (Snapshot::IsEnabled()) { // If we are using a snapshot we always reserve the default amount // of memory for each semispace because code in the snapshot has // write-barrier code that relies on the size and alignment of new // space. We therefore cannot use a larger max semispace size // than the default reserved semispace size. if (max_semispace_size_ > reserved_semispace_size_) { max_semispace_size_ = reserved_semispace_size_; if (FLAG_trace_gc) { PrintPID("Max semispace size cannot be more than %dkbytes\n", reserved_semispace_size_ >> 10); } } } else { // If we are not using snapshots we reserve space for the actual // max semispace size. reserved_semispace_size_ = max_semispace_size_; } if (max_old_space_size > 0) max_old_generation_size_ = max_old_space_size; if (max_executable_size > 0) { max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize); } // The max executable size must be less than or equal to the max old // generation size. if (max_executable_size_ > max_old_generation_size_) { max_executable_size_ = max_old_generation_size_; } // The new space size must be a power of two to support single-bit testing // for containment. max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_); reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_); initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_); // The external allocation limit should be below 256 MB on all architectures // to avoid unnecessary low memory notifications, as that is the threshold // for some embedders. external_allocation_limit_ = 12 * max_semispace_size_; ASSERT(external_allocation_limit_ <= 256 * MB); // The old generation is paged and needs at least one page for each space. int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1; max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count * Page::kPageSize), RoundUp(max_old_generation_size_, Page::kPageSize)); // We rely on being able to allocate new arrays in paged spaces. ASSERT(Page::kMaxRegularHeapObjectSize >= (JSArray::kSize + FixedArray::SizeFor(JSObject::kInitialMaxFastElementArray) + AllocationMemento::kSize)); code_range_size_ = code_range_size; configured_ = true; return true; } bool Heap::ConfigureHeapDefault() { return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB, static_cast<intptr_t>(FLAG_max_old_space_size) * MB, static_cast<intptr_t>(FLAG_max_executable_size) * MB, static_cast<intptr_t>(0)); } void Heap::RecordStats(HeapStats* stats, bool take_snapshot) { *stats->start_marker = HeapStats::kStartMarker; *stats->end_marker = HeapStats::kEndMarker; *stats->new_space_size = new_space_.SizeAsInt(); *stats->new_space_capacity = static_cast<int>(new_space_.Capacity()); *stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects(); *stats->old_pointer_space_capacity = old_pointer_space_->Capacity(); *stats->old_data_space_size = old_data_space_->SizeOfObjects(); *stats->old_data_space_capacity = old_data_space_->Capacity(); *stats->code_space_size = code_space_->SizeOfObjects(); *stats->code_space_capacity = code_space_->Capacity(); *stats->map_space_size = map_space_->SizeOfObjects(); *stats->map_space_capacity = map_space_->Capacity(); *stats->cell_space_size = cell_space_->SizeOfObjects(); *stats->cell_space_capacity = cell_space_->Capacity(); *stats->property_cell_space_size = property_cell_space_->SizeOfObjects(); *stats->property_cell_space_capacity = property_cell_space_->Capacity(); *stats->lo_space_size = lo_space_->Size(); isolate_->global_handles()->RecordStats(stats); *stats->memory_allocator_size = isolate()->memory_allocator()->Size(); *stats->memory_allocator_capacity = isolate()->memory_allocator()->Size() + isolate()->memory_allocator()->Available(); *stats->os_error = OS::GetLastError(); isolate()->memory_allocator()->Available(); if (take_snapshot) { HeapIterator iterator(this); for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) { InstanceType type = obj->map()->instance_type(); ASSERT(0 <= type && type <= LAST_TYPE); stats->objects_per_type[type]++; stats->size_per_type[type] += obj->Size(); } } } intptr_t Heap::PromotedSpaceSizeOfObjects() { return old_pointer_space_->SizeOfObjects() + old_data_space_->SizeOfObjects() + code_space_->SizeOfObjects() + map_space_->SizeOfObjects() + cell_space_->SizeOfObjects() + property_cell_space_->SizeOfObjects() + lo_space_->SizeOfObjects(); } int64_t Heap::PromotedExternalMemorySize() { if (amount_of_external_allocated_memory_ <= amount_of_external_allocated_memory_at_last_global_gc_) return 0; return amount_of_external_allocated_memory_ - amount_of_external_allocated_memory_at_last_global_gc_; } intptr_t Heap::OldGenerationAllocationLimit(intptr_t old_gen_size, int freed_global_handles) { const int kMaxHandles = 1000; const int kMinHandles = 100; double min_factor = 1.1; double max_factor = 4; // We set the old generation growing factor to 2 to grow the heap slower on // memory-constrained devices. if (max_old_generation_size_ <= kMaxOldSpaceSizeMediumMemoryDevice) { max_factor = 2; } // If there are many freed global handles, then the next full GC will // likely collect a lot of garbage. Choose the heap growing factor // depending on freed global handles. // TODO(ulan, hpayer): Take into account mutator utilization. double factor; if (freed_global_handles <= kMinHandles) { factor = max_factor; } else if (freed_global_handles >= kMaxHandles) { factor = min_factor; } else { // Compute factor using linear interpolation between points // (kMinHandles, max_factor) and (kMaxHandles, min_factor). factor = max_factor - (freed_global_handles - kMinHandles) * (max_factor - min_factor) / (kMaxHandles - kMinHandles); } if (FLAG_stress_compaction || mark_compact_collector()->reduce_memory_footprint_) { factor = min_factor; } intptr_t limit = static_cast<intptr_t>(old_gen_size * factor); limit = Max(limit, kMinimumOldGenerationAllocationLimit); limit += new_space_.Capacity(); intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2; return Min(limit, halfway_to_the_max); } void Heap::EnableInlineAllocation() { if (!inline_allocation_disabled_) return; inline_allocation_disabled_ = false; // Update inline allocation limit for new space. new_space()->UpdateInlineAllocationLimit(0); } void Heap::DisableInlineAllocation() { if (inline_allocation_disabled_) return; inline_allocation_disabled_ = true; // Update inline allocation limit for new space. new_space()->UpdateInlineAllocationLimit(0); // Update inline allocation limit for old spaces. PagedSpaces spaces(this); for (PagedSpace* space = spaces.next(); space != NULL; space = spaces.next()) { space->EmptyAllocationInfo(); } } V8_DECLARE_ONCE(initialize_gc_once); static void InitializeGCOnce() { InitializeScavengingVisitorsTables(); NewSpaceScavenger::Initialize(); MarkCompactCollector::Initialize(); } bool Heap::SetUp() { #ifdef DEBUG allocation_timeout_ = FLAG_gc_interval; #endif // Initialize heap spaces and initial maps and objects. Whenever something // goes wrong, just return false. The caller should check the results and // call Heap::TearDown() to release allocated memory. // // If the heap is not yet configured (e.g. through the API), configure it. // Configuration is based on the flags new-space-size (really the semispace // size) and old-space-size if set or the initial values of semispace_size_ // and old_generation_size_ otherwise. if (!configured_) { if (!ConfigureHeapDefault()) return false; } CallOnce(&initialize_gc_once, &InitializeGCOnce); MarkMapPointersAsEncoded(false); // Set up memory allocator. if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize())) return false; // Set up new space. if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) { return false; } // Initialize old pointer space. old_pointer_space_ = new OldSpace(this, max_old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE); if (old_pointer_space_ == NULL) return false; if (!old_pointer_space_->SetUp()) return false; // Initialize old data space. old_data_space_ = new OldSpace(this, max_old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE); if (old_data_space_ == NULL) return false; if (!old_data_space_->SetUp()) return false; if (!isolate_->code_range()->SetUp(code_range_size_)) return false; // Initialize the code space, set its maximum capacity to the old // generation size. It needs executable memory. code_space_ = new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE); if (code_space_ == NULL) return false; if (!code_space_->SetUp()) return false; // Initialize map space. map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE); if (map_space_ == NULL) return false; if (!map_space_->SetUp()) return false; // Initialize simple cell space. cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE); if (cell_space_ == NULL) return false; if (!cell_space_->SetUp()) return false; // Initialize global property cell space. property_cell_space_ = new PropertyCellSpace(this, max_old_generation_size_, PROPERTY_CELL_SPACE); if (property_cell_space_ == NULL) return false; if (!property_cell_space_->SetUp()) return false; // The large object code space may contain code or data. We set the memory // to be non-executable here for safety, but this means we need to enable it // explicitly when allocating large code objects. lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE); if (lo_space_ == NULL) return false; if (!lo_space_->SetUp()) return false; // Set up the seed that is used to randomize the string hash function. ASSERT(hash_seed() == 0); if (FLAG_randomize_hashes) { if (FLAG_hash_seed == 0) { int rnd = isolate()->random_number_generator()->NextInt(); set_hash_seed(Smi::FromInt(rnd & Name::kHashBitMask)); } else { set_hash_seed(Smi::FromInt(FLAG_hash_seed)); } } LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity())); LOG(isolate_, IntPtrTEvent("heap-available", Available())); store_buffer()->SetUp(); mark_compact_collector()->SetUp(); return true; } bool Heap::CreateHeapObjects() { // Create initial maps. if (!CreateInitialMaps()) return false; CreateApiObjects(); // Create initial objects CreateInitialObjects(); CHECK_EQ(0, gc_count_); native_contexts_list_ = undefined_value(); array_buffers_list_ = undefined_value(); allocation_sites_list_ = undefined_value(); weak_object_to_code_table_ = undefined_value(); return true; } void Heap::SetStackLimits() { ASSERT(isolate_ != NULL); ASSERT(isolate_ == isolate()); // On 64 bit machines, pointers are generally out of range of Smis. We write // something that looks like an out of range Smi to the GC. // Set up the special root array entries containing the stack limits. // These are actually addresses, but the tag makes the GC ignore it. roots_[kStackLimitRootIndex] = reinterpret_cast<Object*>( (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag); roots_[kRealStackLimitRootIndex] = reinterpret_cast<Object*>( (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag); } void Heap::TearDown() { #ifdef VERIFY_HEAP if (FLAG_verify_heap) { Verify(); } #endif UpdateMaximumCommitted(); if (FLAG_print_cumulative_gc_stat) { PrintF("\n"); PrintF("gc_count=%d ", gc_count_); PrintF("mark_sweep_count=%d ", ms_count_); PrintF("max_gc_pause=%.1f ", get_max_gc_pause()); PrintF("total_gc_time=%.1f ", total_gc_time_ms_); PrintF("min_in_mutator=%.1f ", get_min_in_mutator()); PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ", get_max_alive_after_gc()); PrintF("total_marking_time=%.1f ", marking_time()); PrintF("total_sweeping_time=%.1f ", sweeping_time()); PrintF("\n\n"); } if (FLAG_print_max_heap_committed) { PrintF("\n"); PrintF("maximum_committed_by_heap=%" V8_PTR_PREFIX "d ", MaximumCommittedMemory()); PrintF("maximum_committed_by_new_space=%" V8_PTR_PREFIX "d ", new_space_.MaximumCommittedMemory()); PrintF("maximum_committed_by_old_pointer_space=%" V8_PTR_PREFIX "d ", old_data_space_->MaximumCommittedMemory()); PrintF("maximum_committed_by_old_data_space=%" V8_PTR_PREFIX "d ", old_pointer_space_->MaximumCommittedMemory()); PrintF("maximum_committed_by_old_data_space=%" V8_PTR_PREFIX "d ", old_pointer_space_->MaximumCommittedMemory()); PrintF("maximum_committed_by_code_space=%" V8_PTR_PREFIX "d ", code_space_->MaximumCommittedMemory()); PrintF("maximum_committed_by_map_space=%" V8_PTR_PREFIX "d ", map_space_->MaximumCommittedMemory()); PrintF("maximum_committed_by_cell_space=%" V8_PTR_PREFIX "d ", cell_space_->MaximumCommittedMemory()); PrintF("maximum_committed_by_property_space=%" V8_PTR_PREFIX "d ", property_cell_space_->MaximumCommittedMemory()); PrintF("maximum_committed_by_lo_space=%" V8_PTR_PREFIX "d ", lo_space_->MaximumCommittedMemory()); PrintF("\n\n"); } TearDownArrayBuffers(); isolate_->global_handles()->TearDown(); external_string_table_.TearDown(); mark_compact_collector()->TearDown(); new_space_.TearDown(); if (old_pointer_space_ != NULL) { old_pointer_space_->TearDown(); delete old_pointer_space_; old_pointer_space_ = NULL; } if (old_data_space_ != NULL) { old_data_space_->TearDown(); delete old_data_space_; old_data_space_ = NULL; } if (code_space_ != NULL) { code_space_->TearDown(); delete code_space_; code_space_ = NULL; } if (map_space_ != NULL) { map_space_->TearDown(); delete map_space_; map_space_ = NULL; } if (cell_space_ != NULL) { cell_space_->TearDown(); delete cell_space_; cell_space_ = NULL; } if (property_cell_space_ != NULL) { property_cell_space_->TearDown(); delete property_cell_space_; property_cell_space_ = NULL; } if (lo_space_ != NULL) { lo_space_->TearDown(); delete lo_space_; lo_space_ = NULL; } store_buffer()->TearDown(); incremental_marking()->TearDown(); isolate_->memory_allocator()->TearDown(); } void Heap::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback callback, GCType gc_type, bool pass_isolate) { ASSERT(callback != NULL); GCPrologueCallbackPair pair(callback, gc_type, pass_isolate); ASSERT(!gc_prologue_callbacks_.Contains(pair)); return gc_prologue_callbacks_.Add(pair); } void Heap::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback) { ASSERT(callback != NULL); for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) { if (gc_prologue_callbacks_[i].callback == callback) { gc_prologue_callbacks_.Remove(i); return; } } UNREACHABLE(); } void Heap::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, GCType gc_type, bool pass_isolate) { ASSERT(callback != NULL); GCEpilogueCallbackPair pair(callback, gc_type, pass_isolate); ASSERT(!gc_epilogue_callbacks_.Contains(pair)); return gc_epilogue_callbacks_.Add(pair); } void Heap::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback) { ASSERT(callback != NULL); for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) { if (gc_epilogue_callbacks_[i].callback == callback) { gc_epilogue_callbacks_.Remove(i); return; } } UNREACHABLE(); } // TODO(ishell): Find a better place for this. void Heap::AddWeakObjectToCodeDependency(Handle<Object> obj, Handle<DependentCode> dep) { ASSERT(!InNewSpace(*obj)); ASSERT(!InNewSpace(*dep)); // This handle scope keeps the table handle local to this function, which // allows us to safely skip write barriers in table update operations. HandleScope scope(isolate()); Handle<WeakHashTable> table(WeakHashTable::cast(weak_object_to_code_table_), isolate()); table = WeakHashTable::Put(table, obj, dep); if (ShouldZapGarbage() && weak_object_to_code_table_ != *table) { WeakHashTable::cast(weak_object_to_code_table_)->Zap(the_hole_value()); } set_weak_object_to_code_table(*table); ASSERT_EQ(*dep, table->Lookup(obj)); } DependentCode* Heap::LookupWeakObjectToCodeDependency(Handle<Object> obj) { Object* dep = WeakHashTable::cast(weak_object_to_code_table_)->Lookup(obj); if (dep->IsDependentCode()) return DependentCode::cast(dep); return DependentCode::cast(empty_fixed_array()); } void Heap::EnsureWeakObjectToCodeTable() { if (!weak_object_to_code_table()->IsHashTable()) { set_weak_object_to_code_table(*WeakHashTable::New( isolate(), 16, USE_DEFAULT_MINIMUM_CAPACITY, TENURED)); } } void Heap::FatalProcessOutOfMemory(const char* location, bool take_snapshot) { v8::internal::V8::FatalProcessOutOfMemory(location, take_snapshot); } #ifdef DEBUG class PrintHandleVisitor: public ObjectVisitor { public: void VisitPointers(Object** start, Object** end) { for (Object** p = start; p < end; p++) PrintF(" handle %p to %p\n", reinterpret_cast<void*>(p), reinterpret_cast<void*>(*p)); } }; void Heap::PrintHandles() { PrintF("Handles:\n"); PrintHandleVisitor v; isolate_->handle_scope_implementer()->Iterate(&v); } #endif Space* AllSpaces::next() { switch (counter_++) { case NEW_SPACE: return heap_->new_space(); case OLD_POINTER_SPACE: return heap_->old_pointer_space(); case OLD_DATA_SPACE: return heap_->old_data_space(); case CODE_SPACE: return heap_->code_space(); case MAP_SPACE: return heap_->map_space(); case CELL_SPACE: return heap_->cell_space(); case PROPERTY_CELL_SPACE: return heap_->property_cell_space(); case LO_SPACE: return heap_->lo_space(); default: return NULL; } } PagedSpace* PagedSpaces::next() { switch (counter_++) { case OLD_POINTER_SPACE: return heap_->old_pointer_space(); case OLD_DATA_SPACE: return heap_->old_data_space(); case CODE_SPACE: return heap_->code_space(); case MAP_SPACE: return heap_->map_space(); case CELL_SPACE: return heap_->cell_space(); case PROPERTY_CELL_SPACE: return heap_->property_cell_space(); default: return NULL; } } OldSpace* OldSpaces::next() { switch (counter_++) { case OLD_POINTER_SPACE: return heap_->old_pointer_space(); case OLD_DATA_SPACE: return heap_->old_data_space(); case CODE_SPACE: return heap_->code_space(); default: return NULL; } } SpaceIterator::SpaceIterator(Heap* heap) : heap_(heap), current_space_(FIRST_SPACE), iterator_(NULL), size_func_(NULL) { } SpaceIterator::SpaceIterator(Heap* heap, HeapObjectCallback size_func) : heap_(heap), current_space_(FIRST_SPACE), iterator_(NULL), size_func_(size_func) { } SpaceIterator::~SpaceIterator() { // Delete active iterator if any. delete iterator_; } bool SpaceIterator::has_next() { // Iterate until no more spaces. return current_space_ != LAST_SPACE; } ObjectIterator* SpaceIterator::next() { if (iterator_ != NULL) { delete iterator_; iterator_ = NULL; // Move to the next space current_space_++; if (current_space_ > LAST_SPACE) { return NULL; } } // Return iterator for the new current space. return CreateIterator(); } // Create an iterator for the space to iterate. ObjectIterator* SpaceIterator::CreateIterator() { ASSERT(iterator_ == NULL); switch (current_space_) { case NEW_SPACE: iterator_ = new SemiSpaceIterator(heap_->new_space(), size_func_); break; case OLD_POINTER_SPACE: iterator_ = new HeapObjectIterator(heap_->old_pointer_space(), size_func_); break; case OLD_DATA_SPACE: iterator_ = new HeapObjectIterator(heap_->old_data_space(), size_func_); break; case CODE_SPACE: iterator_ = new HeapObjectIterator(heap_->code_space(), size_func_); break; case MAP_SPACE: iterator_ = new HeapObjectIterator(heap_->map_space(), size_func_); break; case CELL_SPACE: iterator_ = new HeapObjectIterator(heap_->cell_space(), size_func_); break; case PROPERTY_CELL_SPACE: iterator_ = new HeapObjectIterator(heap_->property_cell_space(), size_func_); break; case LO_SPACE: iterator_ = new LargeObjectIterator(heap_->lo_space(), size_func_); break; } // Return the newly allocated iterator; ASSERT(iterator_ != NULL); return iterator_; } class HeapObjectsFilter { public: virtual ~HeapObjectsFilter() {} virtual bool SkipObject(HeapObject* object) = 0; }; class UnreachableObjectsFilter : public HeapObjectsFilter { public: explicit UnreachableObjectsFilter(Heap* heap) : heap_(heap) { MarkReachableObjects(); } ~UnreachableObjectsFilter() { heap_->mark_compact_collector()->ClearMarkbits(); } bool SkipObject(HeapObject* object) { MarkBit mark_bit = Marking::MarkBitFrom(object); return !mark_bit.Get(); } private: class MarkingVisitor : public ObjectVisitor { public: MarkingVisitor() : marking_stack_(10) {} void VisitPointers(Object** start, Object** end) { for (Object** p = start; p < end; p++) { if (!(*p)->IsHeapObject()) continue; HeapObject* obj = HeapObject::cast(*p); MarkBit mark_bit = Marking::MarkBitFrom(obj); if (!mark_bit.Get()) { mark_bit.Set(); marking_stack_.Add(obj); } } } void TransitiveClosure() { while (!marking_stack_.is_empty()) { HeapObject* obj = marking_stack_.RemoveLast(); obj->Iterate(this); } } private: List<HeapObject*> marking_stack_; }; void MarkReachableObjects() { MarkingVisitor visitor; heap_->IterateRoots(&visitor, VISIT_ALL); visitor.TransitiveClosure(); } Heap* heap_; DisallowHeapAllocation no_allocation_; }; HeapIterator::HeapIterator(Heap* heap) : heap_(heap), filtering_(HeapIterator::kNoFiltering), filter_(NULL) { Init(); } HeapIterator::HeapIterator(Heap* heap, HeapIterator::HeapObjectsFiltering filtering) : heap_(heap), filtering_(filtering), filter_(NULL) { Init(); } HeapIterator::~HeapIterator() { Shutdown(); } void HeapIterator::Init() { // Start the iteration. space_iterator_ = new SpaceIterator(heap_); switch (filtering_) { case kFilterUnreachable: filter_ = new UnreachableObjectsFilter(heap_); break; default: break; } object_iterator_ = space_iterator_->next(); } void HeapIterator::Shutdown() { #ifdef DEBUG // Assert that in filtering mode we have iterated through all // objects. Otherwise, heap will be left in an inconsistent state. if (filtering_ != kNoFiltering) { ASSERT(object_iterator_ == NULL); } #endif // Make sure the last iterator is deallocated. delete space_iterator_; space_iterator_ = NULL; object_iterator_ = NULL; delete filter_; filter_ = NULL; } HeapObject* HeapIterator::next() { if (filter_ == NULL) return NextObject(); HeapObject* obj = NextObject(); while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject(); return obj; } HeapObject* HeapIterator::NextObject() { // No iterator means we are done. if (object_iterator_ == NULL) return NULL; if (HeapObject* obj = object_iterator_->next_object()) { // If the current iterator has more objects we are fine. return obj; } else { // Go though the spaces looking for one that has objects. while (space_iterator_->has_next()) { object_iterator_ = space_iterator_->next(); if (HeapObject* obj = object_iterator_->next_object()) { return obj; } } } // Done with the last space. object_iterator_ = NULL; return NULL; } void HeapIterator::reset() { // Restart the iterator. Shutdown(); Init(); } #ifdef DEBUG Object* const PathTracer::kAnyGlobalObject = NULL; class PathTracer::MarkVisitor: public ObjectVisitor { public: explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {} void VisitPointers(Object** start, Object** end) { // Scan all HeapObject pointers in [start, end) for (Object** p = start; !tracer_->found() && (p < end); p++) { if ((*p)->IsHeapObject()) tracer_->MarkRecursively(p, this); } } private: PathTracer* tracer_; }; class PathTracer::UnmarkVisitor: public ObjectVisitor { public: explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {} void VisitPointers(Object** start, Object** end) { // Scan all HeapObject pointers in [start, end) for (Object** p = start; p < end; p++) { if ((*p)->IsHeapObject()) tracer_->UnmarkRecursively(p, this); } } private: PathTracer* tracer_; }; void PathTracer::VisitPointers(Object** start, Object** end) { bool done = ((what_to_find_ == FIND_FIRST) && found_target_); // Visit all HeapObject pointers in [start, end) for (Object** p = start; !done && (p < end); p++) { if ((*p)->IsHeapObject()) { TracePathFrom(p); done = ((what_to_find_ == FIND_FIRST) && found_target_); } } } void PathTracer::Reset() { found_target_ = false; object_stack_.Clear(); } void PathTracer::TracePathFrom(Object** root) { ASSERT((search_target_ == kAnyGlobalObject) || search_target_->IsHeapObject()); found_target_in_trace_ = false; Reset(); MarkVisitor mark_visitor(this); MarkRecursively(root, &mark_visitor); UnmarkVisitor unmark_visitor(this); UnmarkRecursively(root, &unmark_visitor); ProcessResults(); } static bool SafeIsNativeContext(HeapObject* obj) { return obj->map() == obj->GetHeap()->raw_unchecked_native_context_map(); } void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) { if (!(*p)->IsHeapObject()) return; HeapObject* obj = HeapObject::cast(*p); Object* map = obj->map(); if (!map->IsHeapObject()) return; // visited before if (found_target_in_trace_) return; // stop if target found object_stack_.Add(obj); if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) || (obj == search_target_)) { found_target_in_trace_ = true; found_target_ = true; return; } bool is_native_context = SafeIsNativeContext(obj); // not visited yet Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map)); Address map_addr = map_p->address(); obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag)); // Scan the object body. if (is_native_context && (visit_mode_ == VISIT_ONLY_STRONG)) { // This is specialized to scan Context's properly. Object** start = reinterpret_cast<Object**>(obj->address() + Context::kHeaderSize); Object** end = reinterpret_cast<Object**>(obj->address() + Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize); mark_visitor->VisitPointers(start, end); } else { obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p), mark_visitor); } // Scan the map after the body because the body is a lot more interesting // when doing leak detection. MarkRecursively(&map, mark_visitor); if (!found_target_in_trace_) // don't pop if found the target object_stack_.RemoveLast(); } void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) { if (!(*p)->IsHeapObject()) return; HeapObject* obj = HeapObject::cast(*p); Object* map = obj->map(); if (map->IsHeapObject()) return; // unmarked already Address map_addr = reinterpret_cast<Address>(map); map_addr -= kMarkTag; ASSERT_TAG_ALIGNED(map_addr); HeapObject* map_p = HeapObject::FromAddress(map_addr); obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p)); UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor); obj->IterateBody(Map::cast(map_p)->instance_type(), obj->SizeFromMap(Map::cast(map_p)), unmark_visitor); } void PathTracer::ProcessResults() { if (found_target_) { PrintF("=====================================\n"); PrintF("==== Path to object ====\n"); PrintF("=====================================\n\n"); ASSERT(!object_stack_.is_empty()); for (int i = 0; i < object_stack_.length(); i++) { if (i > 0) PrintF("\n |\n |\n V\n\n"); Object* obj = object_stack_[i]; obj->Print(); } PrintF("=====================================\n"); } } // Triggers a depth-first traversal of reachable objects from one // given root object and finds a path to a specific heap object and // prints it. void Heap::TracePathToObjectFrom(Object* target, Object* root) { PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL); tracer.VisitPointer(&root); } // Triggers a depth-first traversal of reachable objects from roots // and finds a path to a specific heap object and prints it. void Heap::TracePathToObject(Object* target) { PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL); IterateRoots(&tracer, VISIT_ONLY_STRONG); } // Triggers a depth-first traversal of reachable objects from roots // and finds a path to any global object and prints it. Useful for // determining the source for leaks of global objects. void Heap::TracePathToGlobal() { PathTracer tracer(PathTracer::kAnyGlobalObject, PathTracer::FIND_ALL, VISIT_ALL); IterateRoots(&tracer, VISIT_ONLY_STRONG); } #endif static intptr_t CountTotalHolesSize(Heap* heap) { intptr_t holes_size = 0; OldSpaces spaces(heap); for (OldSpace* space = spaces.next(); space != NULL; space = spaces.next()) { holes_size += space->Waste() + space->Available(); } return holes_size; } GCTracer::GCTracer(Heap* heap, const char* gc_reason, const char* collector_reason) : start_time_(0.0), start_object_size_(0), start_memory_size_(0), gc_count_(0), full_gc_count_(0), allocated_since_last_gc_(0), spent_in_mutator_(0), promoted_objects_size_(0), nodes_died_in_new_space_(0), nodes_copied_in_new_space_(0), nodes_promoted_(0), heap_(heap), gc_reason_(gc_reason), collector_reason_(collector_reason) { if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return; start_time_ = OS::TimeCurrentMillis(); start_object_size_ = heap_->SizeOfObjects(); start_memory_size_ = heap_->isolate()->memory_allocator()->Size(); for (int i = 0; i < Scope::kNumberOfScopes; i++) { scopes_[i] = 0; } in_free_list_or_wasted_before_gc_ = CountTotalHolesSize(heap); allocated_since_last_gc_ = heap_->SizeOfObjects() - heap_->alive_after_last_gc_; if (heap_->last_gc_end_timestamp_ > 0) { spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0); } steps_count_ = heap_->incremental_marking()->steps_count(); steps_took_ = heap_->incremental_marking()->steps_took(); longest_step_ = heap_->incremental_marking()->longest_step(); steps_count_since_last_gc_ = heap_->incremental_marking()->steps_count_since_last_gc(); steps_took_since_last_gc_ = heap_->incremental_marking()->steps_took_since_last_gc(); } GCTracer::~GCTracer() { // Printf ONE line iff flag is set. if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return; bool first_gc = (heap_->last_gc_end_timestamp_ == 0); heap_->alive_after_last_gc_ = heap_->SizeOfObjects(); heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis(); double time = heap_->last_gc_end_timestamp_ - start_time_; // Update cumulative GC statistics if required. if (FLAG_print_cumulative_gc_stat) { heap_->total_gc_time_ms_ += time; heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time); heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_, heap_->alive_after_last_gc_); if (!first_gc) { heap_->min_in_mutator_ = Min(heap_->min_in_mutator_, spent_in_mutator_); } } else if (FLAG_trace_gc_verbose) { heap_->total_gc_time_ms_ += time; } if (collector_ == SCAVENGER && FLAG_trace_gc_ignore_scavenger) return; heap_->AddMarkingTime(scopes_[Scope::MC_MARK]); if (FLAG_print_cumulative_gc_stat && !FLAG_trace_gc) return; PrintPID("%8.0f ms: ", heap_->isolate()->time_millis_since_init()); if (!FLAG_trace_gc_nvp) { int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]); double end_memory_size_mb = static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB; PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ", CollectorString(), static_cast<double>(start_object_size_) / MB, static_cast<double>(start_memory_size_) / MB, SizeOfHeapObjects(), end_memory_size_mb); if (external_time > 0) PrintF("%d / ", external_time); PrintF("%.1f ms", time); if (steps_count_ > 0) { if (collector_ == SCAVENGER) { PrintF(" (+ %.1f ms in %d steps since last GC)", steps_took_since_last_gc_, steps_count_since_last_gc_); } else { PrintF(" (+ %.1f ms in %d steps since start of marking, " "biggest step %.1f ms)", steps_took_, steps_count_, longest_step_); } } if (gc_reason_ != NULL) { PrintF(" [%s]", gc_reason_); } if (collector_reason_ != NULL) { PrintF(" [%s]", collector_reason_); } PrintF(".\n"); } else { PrintF("pause=%.1f ", time); PrintF("mutator=%.1f ", spent_in_mutator_); PrintF("gc="); switch (collector_) { case SCAVENGER: PrintF("s"); break; case MARK_COMPACTOR: PrintF("ms"); break; default: UNREACHABLE(); } PrintF(" "); PrintF("external=%.1f ", scopes_[Scope::EXTERNAL]); PrintF("mark=%.1f ", scopes_[Scope::MC_MARK]); PrintF("sweep=%.2f ", scopes_[Scope::MC_SWEEP]); PrintF("sweepns=%.2f ", scopes_[Scope::MC_SWEEP_NEWSPACE]); PrintF("sweepos=%.2f ", scopes_[Scope::MC_SWEEP_OLDSPACE]); PrintF("evacuate=%.1f ", scopes_[Scope::MC_EVACUATE_PAGES]); PrintF("new_new=%.1f ", scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]); PrintF("root_new=%.1f ", scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]); PrintF("old_new=%.1f ", scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]); PrintF("compaction_ptrs=%.1f ", scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]); PrintF("intracompaction_ptrs=%.1f ", scopes_[Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]); PrintF("misc_compaction=%.1f ", scopes_[Scope::MC_UPDATE_MISC_POINTERS]); PrintF("weakcollection_process=%.1f ", scopes_[Scope::MC_WEAKCOLLECTION_PROCESS]); PrintF("weakcollection_clear=%.1f ", scopes_[Scope::MC_WEAKCOLLECTION_CLEAR]); PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_); PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects()); PrintF("holes_size_before=%" V8_PTR_PREFIX "d ", in_free_list_or_wasted_before_gc_); PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize(heap_)); PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_); PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_); PrintF("nodes_died_in_new=%d ", nodes_died_in_new_space_); PrintF("nodes_copied_in_new=%d ", nodes_copied_in_new_space_); PrintF("nodes_promoted=%d ", nodes_promoted_); if (collector_ == SCAVENGER) { PrintF("stepscount=%d ", steps_count_since_last_gc_); PrintF("stepstook=%.1f ", steps_took_since_last_gc_); } else { PrintF("stepscount=%d ", steps_count_); PrintF("stepstook=%.1f ", steps_took_); PrintF("longeststep=%.1f ", longest_step_); } PrintF("\n"); } heap_->PrintShortHeapStatistics(); } const char* GCTracer::CollectorString() { switch (collector_) { case SCAVENGER: return "Scavenge"; case MARK_COMPACTOR: return "Mark-sweep"; } return "Unknown GC"; } int KeyedLookupCache::Hash(Handle<Map> map, Handle<Name> name) { DisallowHeapAllocation no_gc; // Uses only lower 32 bits if pointers are larger. uintptr_t addr_hash = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(*map)) >> kMapHashShift; return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask); } int KeyedLookupCache::Lookup(Handle<Map> map, Handle<Name> name) { DisallowHeapAllocation no_gc; int index = (Hash(map, name) & kHashMask); for (int i = 0; i < kEntriesPerBucket; i++) { Key& key = keys_[index + i]; if ((key.map == *map) && key.name->Equals(*name)) { return field_offsets_[index + i]; } } return kNotFound; } void KeyedLookupCache::Update(Handle<Map> map, Handle<Name> name, int field_offset) { DisallowHeapAllocation no_gc; if (!name->IsUniqueName()) { if (!StringTable::InternalizeStringIfExists(name->GetIsolate(), Handle<String>::cast(name)). ToHandle(&name)) { return; } } // This cache is cleared only between mark compact passes, so we expect the // cache to only contain old space names. ASSERT(!map->GetIsolate()->heap()->InNewSpace(*name)); int index = (Hash(map, name) & kHashMask); // After a GC there will be free slots, so we use them in order (this may // help to get the most frequently used one in position 0). for (int i = 0; i< kEntriesPerBucket; i++) { Key& key = keys_[index]; Object* free_entry_indicator = NULL; if (key.map == free_entry_indicator) { key.map = *map; key.name = *name; field_offsets_[index + i] = field_offset; return; } } // No free entry found in this bucket, so we move them all down one and // put the new entry at position zero. for (int i = kEntriesPerBucket - 1; i > 0; i--) { Key& key = keys_[index + i]; Key& key2 = keys_[index + i - 1]; key = key2; field_offsets_[index + i] = field_offsets_[index + i - 1]; } // Write the new first entry. Key& key = keys_[index]; key.map = *map; key.name = *name; field_offsets_[index] = field_offset; } void KeyedLookupCache::Clear() { for (int index = 0; index < kLength; index++) keys_[index].map = NULL; } void DescriptorLookupCache::Clear() { for (int index = 0; index < kLength; index++) keys_[index].source = NULL; } void ExternalStringTable::CleanUp() { int last = 0; for (int i = 0; i < new_space_strings_.length(); ++i) { if (new_space_strings_[i] == heap_->the_hole_value()) { continue; } ASSERT(new_space_strings_[i]->IsExternalString()); if (heap_->InNewSpace(new_space_strings_[i])) { new_space_strings_[last++] = new_space_strings_[i]; } else { old_space_strings_.Add(new_space_strings_[i]); } } new_space_strings_.Rewind(last); new_space_strings_.Trim(); last = 0; for (int i = 0; i < old_space_strings_.length(); ++i) { if (old_space_strings_[i] == heap_->the_hole_value()) { continue; } ASSERT(old_space_strings_[i]->IsExternalString()); ASSERT(!heap_->InNewSpace(old_space_strings_[i])); old_space_strings_[last++] = old_space_strings_[i]; } old_space_strings_.Rewind(last); old_space_strings_.Trim(); #ifdef VERIFY_HEAP if (FLAG_verify_heap) { Verify(); } #endif } void ExternalStringTable::TearDown() { for (int i = 0; i < new_space_strings_.length(); ++i) { heap_->FinalizeExternalString(ExternalString::cast(new_space_strings_[i])); } new_space_strings_.Free(); for (int i = 0; i < old_space_strings_.length(); ++i) { heap_->FinalizeExternalString(ExternalString::cast(old_space_strings_[i])); } old_space_strings_.Free(); } void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) { chunk->set_next_chunk(chunks_queued_for_free_); chunks_queued_for_free_ = chunk; } void Heap::FreeQueuedChunks() { if (chunks_queued_for_free_ == NULL) return; MemoryChunk* next; MemoryChunk* chunk; for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) { next = chunk->next_chunk(); chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED); if (chunk->owner()->identity() == LO_SPACE) { // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress. // If FromAnyPointerAddress encounters a slot that belongs to a large // chunk queued for deletion it will fail to find the chunk because // it try to perform a search in the list of pages owned by of the large // object space and queued chunks were detached from that list. // To work around this we split large chunk into normal kPageSize aligned // pieces and initialize size, owner and flags field of every piece. // If FromAnyPointerAddress encounters a slot that belongs to one of // these smaller pieces it will treat it as a slot on a normal Page. Address chunk_end = chunk->address() + chunk->size(); MemoryChunk* inner = MemoryChunk::FromAddress( chunk->address() + Page::kPageSize); MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1); while (inner <= inner_last) { // Size of a large chunk is always a multiple of // OS::AllocateAlignment() so there is always // enough space for a fake MemoryChunk header. Address area_end = Min(inner->address() + Page::kPageSize, chunk_end); // Guard against overflow. if (area_end < inner->address()) area_end = chunk_end; inner->SetArea(inner->address(), area_end); inner->set_size(Page::kPageSize); inner->set_owner(lo_space()); inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED); inner = MemoryChunk::FromAddress( inner->address() + Page::kPageSize); } } } isolate_->heap()->store_buffer()->Compact(); isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED); for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) { next = chunk->next_chunk(); isolate_->memory_allocator()->Free(chunk); } chunks_queued_for_free_ = NULL; } void Heap::RememberUnmappedPage(Address page, bool compacted) { uintptr_t p = reinterpret_cast<uintptr_t>(page); // Tag the page pointer to make it findable in the dump file. if (compacted) { p ^= 0xc1ead & (Page::kPageSize - 1); // Cleared. } else { p ^= 0x1d1ed & (Page::kPageSize - 1); // I died. } remembered_unmapped_pages_[remembered_unmapped_pages_index_] = reinterpret_cast<Address>(p); remembered_unmapped_pages_index_++; remembered_unmapped_pages_index_ %= kRememberedUnmappedPages; } void Heap::ClearObjectStats(bool clear_last_time_stats) { memset(object_counts_, 0, sizeof(object_counts_)); memset(object_sizes_, 0, sizeof(object_sizes_)); if (clear_last_time_stats) { memset(object_counts_last_time_, 0, sizeof(object_counts_last_time_)); memset(object_sizes_last_time_, 0, sizeof(object_sizes_last_time_)); } } static LazyMutex checkpoint_object_stats_mutex = LAZY_MUTEX_INITIALIZER; void Heap::CheckpointObjectStats() { LockGuard<Mutex> lock_guard(checkpoint_object_stats_mutex.Pointer()); Counters* counters = isolate()->counters(); #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \ counters->count_of_##name()->Increment( \ static_cast<int>(object_counts_[name])); \ counters->count_of_##name()->Decrement( \ static_cast<int>(object_counts_last_time_[name])); \ counters->size_of_##name()->Increment( \ static_cast<int>(object_sizes_[name])); \ counters->size_of_##name()->Decrement( \ static_cast<int>(object_sizes_last_time_[name])); INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT) #undef ADJUST_LAST_TIME_OBJECT_COUNT int index; #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \ index = FIRST_CODE_KIND_SUB_TYPE + Code::name; \ counters->count_of_CODE_TYPE_##name()->Increment( \ static_cast<int>(object_counts_[index])); \ counters->count_of_CODE_TYPE_##name()->Decrement( \ static_cast<int>(object_counts_last_time_[index])); \ counters->size_of_CODE_TYPE_##name()->Increment( \ static_cast<int>(object_sizes_[index])); \ counters->size_of_CODE_TYPE_##name()->Decrement( \ static_cast<int>(object_sizes_last_time_[index])); CODE_KIND_LIST(ADJUST_LAST_TIME_OBJECT_COUNT) #undef ADJUST_LAST_TIME_OBJECT_COUNT #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \ index = FIRST_FIXED_ARRAY_SUB_TYPE + name; \ counters->count_of_FIXED_ARRAY_##name()->Increment( \ static_cast<int>(object_counts_[index])); \ counters->count_of_FIXED_ARRAY_##name()->Decrement( \ static_cast<int>(object_counts_last_time_[index])); \ counters->size_of_FIXED_ARRAY_##name()->Increment( \ static_cast<int>(object_sizes_[index])); \ counters->size_of_FIXED_ARRAY_##name()->Decrement( \ static_cast<int>(object_sizes_last_time_[index])); FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT) #undef ADJUST_LAST_TIME_OBJECT_COUNT #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \ index = \ FIRST_CODE_AGE_SUB_TYPE + Code::k##name##CodeAge - Code::kFirstCodeAge; \ counters->count_of_CODE_AGE_##name()->Increment( \ static_cast<int>(object_counts_[index])); \ counters->count_of_CODE_AGE_##name()->Decrement( \ static_cast<int>(object_counts_last_time_[index])); \ counters->size_of_CODE_AGE_##name()->Increment( \ static_cast<int>(object_sizes_[index])); \ counters->size_of_CODE_AGE_##name()->Decrement( \ static_cast<int>(object_sizes_last_time_[index])); CODE_AGE_LIST_COMPLETE(ADJUST_LAST_TIME_OBJECT_COUNT) #undef ADJUST_LAST_TIME_OBJECT_COUNT OS::MemCopy(object_counts_last_time_, object_counts_, sizeof(object_counts_)); OS::MemCopy(object_sizes_last_time_, object_sizes_, sizeof(object_sizes_)); ClearObjectStats(); } } } // namespace v8::internal
page ,132 ;/* ; * Microsoft Confidential ; * Copyright (C) Microsoft Corporation 1991 ; * All Rights Reserved. ; */ ; SCCSID = @(#)parse.asm 1.1 85/05/14 ; SCCSID = @(#)parse.asm 1.1 85/05/14 .sall .xlist .xcref INCLUDE DOSSYM.INC INCLUDE DEVSYM.INC include comsw.asm include comseg.asm include comequ.asm .list .cref break <Parse.Asm> ;---------------------------------------------------------------------------- ; PARSE.ASM contains the routines to perform command line parsing. ; Parse and Path share a buffer and argv[] definitions. ; Invoking <Parseline> maps the unparsed command line in COMBUF into an ; array of pointers to the parsed tokens. The resulting array, argv[], ; also contains extra information provided by cparse about each token ; <Parseline> should be executed prior to <Path_Search> ; ; Alan L, OS/MSDOS August 15, 1983 ; ; ; ENTRY: ; <Parseline>: command line in COMTAB. ; EXIT: ; <Parseline>: success flag, argcnt (number of args), argv[]. ; NOTE(S): ; * <Argv_calc> handily turns an array index into an absolute pointer. ; The computation depends on the size of an argv[] element (arg_ele). ; * <Parseline> calls <cparse> for chunks of the command line. <Cparse> ; does not function as specified; see <Parseline> for more details. ; * <Parseline> now knows about the flags the internals of COMMAND.COM ; need to know about. This extra information is stored in a switch_flag ; word with each command-line argument; the switches themselves will not ; appear in the resulting arg structure. ; * With the exception of CARRY, flags are generally preserved across calls. ;--------------- ; CONSTANTS: ;--------------- DEBUGx equ FALSE ; prints out debug info ;--------------- ; DATA: ;--------------- DATARES SEGMENT PUBLIC BYTE EXTRN FORFLAG:BYTE DATARES ENDS TRANSPACE SEGMENT PUBLIC BYTE ;AC000; EXTRN combuf:byte EXTRN cpyflag:byte EXTRN expand_star:byte EXTRN RESSEG:word EXTRN STARTEL:word TRANSPACE ENDS TRANCODE SEGMENT PUBLIC BYTE ;AC000; PUBLIC argv_calc ; convert array index into address PUBLIC parseline assume cs:trangroup, ds:trangroup, es:trangroup, ss:nothing break <Parseline: Munch on the command line> ;---------------------------------------------------------------------------- ; PARSELINE takes an MSDOS command line and maps it into a UNIX-style ; argv[argvcnt] array. The most important difference between this array and ; the tradition UNIX format is the extra cparse information included with ; each argument element. ;--------------- ; ENTRY: ; (BL special delimiter for cparse -- not implemented) ;--------------- ; EXIT: ; CF set if error ; AL error code (carry set). Note AH clobbered in any event. ; argv[] array of cparse flags and pointers to arguments ; argvcnt argument count ;--------------- ; NOTE(S): ; * BL (special delimiter) is ignored, for now (set to space). ; * Parseflags record contains cparse flags, as follows: ; sw_flag -- was this arg a switch? ; wildcard -- whether or not it contained a * or ? ; path_sep -- maybe it was a pathname ; unused -- for future expansion ; special_delim -- was there an initial special delimiter? ; * argv[] and argvcnt are undefined if CF/AL indicates an error. ; * Relationship between input, cparse output, and comtail can be ; found in the following chart. Despite the claim of the cparse ; documentation that, "Token buffer always starts d: for non switch ; tokens", such is not the case (see column two, row two). ; Similarly, [STARTEL] is not null when the command line is one of ; the forms, "d:", "d:\", or "d:/". In fact, *STARTEL (i.e., what ; STARTEL addresses) will be null. This is clearly just a ; documentation error. ; * cparse also returns a switch code in BP for each switch it ; recognizes on the command line. ; * arglen for each token does NOT include the terminating null. ; * Finally, note that interesting constructions like 'foodir/*.exe' ; parse as three separate tokens, and the asterisk is NOT a wildcard. ; For example, 'for %i in (foodir/*.exe) do echo %i' will first ; echo 'foodir', then '*', then '.exe'. Using cparse for command- ; line parsing may result in slightly different behavior than ; previously observed with the old COMMAND.COM command-line parser. ; ; Input Cparse Command Line (80H) ; \alan\foo.bat c:\alan\foo.bat \alan\foo.bat ; alan\foo.bat alan\foo.bat alan\foo.bat ; foo.bat foo.bat foo.bat ; c:\alan\foo.bat c:\alan\foo.bat c:\alan\foo.bat ; c:alan\foo.bat c:alan\foo.bat c:alan\foo.bat ; c:foo.bat c:foo.bat c:foo.bat ;--------------- ; CONSTANTS: ;--------------- ;--------------- ; DATA: ;--------------- TRANSPACE SEGMENT PUBLIC BYTE ;AC000; EXTRN arg:byte EXTRN argbufptr:word EXTRN comptr:word EXTRN last_arg:word EXTRN tpbuf:byte TRANSPACE ENDS ;--------------- parseline: ;--------------- push AX ; most of these are clobbered push BX ; by cparse... push CX push DX push DI push SI pushf mov cpyflag,0 ; Turn "CPARSE called from COPY flag" off mov [LAST_ARG], -1 ; last argument at which to accumulate xor ax,ax mov cx,SIZE arg_unit mov di,offset trangroup:arg rep stosb mov argbufptr,offset trangroup:arg.argbuf mov arg.argswinfo, 0 ; switch information, and info to date mov arg.argvcnt, 0 ; initialize argvcnt/argv[] mov SI, OFFSET TRANGROUP:combuf+2 ; prescan leaves cooked input in combuf ; This next section of code (up to pcont:) makes sure that si is set up for ; parsing. It should point at COMBUF if FORFLAG is set and arg.argforcombuf ; otherwise. This is done so that commands can get arg pointers into their ; original command line (or an exact copy of it) in arg_ocomptr. ; Arg.argforcombuf is used so that the for loop processor will always be able ; to get a hold of its original command line; even after COMBUF is blasted by ; the command to be repeated or the transient part of command has been ; reloaded. push ds mov ds,[RESSEG] assume ds:resgroup cmp FORFLAG,0 pop ds assume ds:trangroup jnz pcont mov di,OFFSET TRANGROUP:arg.argforcombuf xor ch,ch mov cl,[COMBUF+1] inc cl rep movsb mov si,OFFSET TRANGROUP:arg.argforcombuf pcont: mov DI, OFFSET TRANGROUP:tpbuf ; destination is temporary token buffer mov BL, ' ' ; no special delimiter, for now parseloop: mov comptr,si ; save ptr into original command buffer xor BP, BP ; switch information put here by cparse mov byte ptr [expand_star],0 ; don't expand *'s to ?'s invoke scanoff ; skip leading blanks... invoke cparse ; byte off a token (args in SI, DI, BL) jnc More_prse or BP,BP ; Check for trailing switch character jz parsedone call newarg ; We hit CR but BP is non-zero. The ; typical cause of this is that a ; switch char IMMEDIATELY preceeds ; the CR. We have an argument, but it ; is sort of an error. jmp short parsedone ; We're done (found the CR). More_prse: mov cpyflag,2 ; tell CPARSE that 1st token is done call newarg ; add to argv array (CX has char count) jnc parseloop ; was everything OK? jmp short parse_error ; NO, it wasn't -- bug out (CF set) parsedone: ; successful completion of parseline popf clc jmp short parse_exit parse_error: ; error entry (er, exit) point popf stc parse_exit: ; depend on not changing CF pop SI pop DI pop DX pop CX pop BX pop AX ret ;--------------- ; parseline ends ;---------------------------------------------------------------------------- break <NewArg> ;---------------------------------------------------------------------------- ; NEWARG adds the supplied argstring and cparse data to arg.argv[]. ; ENTRY: ; BH argflags ; CX character count in argstring ; DI pointer to argstring ; comptr ptr to starting loc of current token in original command ; [STARTEL] cparse's answer to where the last element starts ; EXIT: ; argbufptr points to next free section of argbuffer ; arg.argbuf contains null-terminated argument strings ; arg.argvcnt argument count ; arg.argv[] array of flags and pointers ; arg.arg_ocomptr ptr to starting loc of current token in original command ; CF set if error ; AL carry set: error code; otherwise, zero ;--------------- newarg: ;--------------- push BX push CX push DX ; one never knows, do one? push DI push SI pushf call arg_switch ; if it's a switch, record switch info ; LEAVE SWITCH ON COMMAND LINE!! ;;; jc newarg_done ; previous arg's switches -- and leave cmp arg.argvcnt, ARGMAX ; check to ensure we've not jge too_many_args ; exceeded array limits mov DH, BH ; save argflags mov BX, arg.argvcnt ; argv[argvcnt++] = arg data inc arg.argvcnt mov AX, OFFSET TRANGROUP:arg.argv call argv_calc ; convert offset to pointer mov [BX].argsw_word, 0 ; no switch information, yet... mov [BX].arglen, CX ; argv[argvcnt].arglen = arg length mov [BX].argflags, DH ; argv[argvcnt].argflags = cparse flags mov SI, argbufptr mov [BX].argpointer, SI ; argv[argvcnt].argpointer = [argbufptr] add SI, [STARTEL] ; save startel from new location sub SI, DI ; form pointer into argbuf mov [BX].argstartel, SI ; argv[argvcnt].argstartel = new [STARTEL] mov si,[comptr] mov [BX].arg_ocomptr,si ; arg_ocomptr=ptr into original com line mov SI, DI ; now save argstring in argbuffer mov DI, argbufptr ; load the argbuf pointer and make add DI, CX ; sure we're not about to run off cmp DI, OFFSET TRANGROUP:arg.argbuf+ARGBLEN-1 jge buf_ovflow ; the end of the buffer (plus null byte) sub DI, CX ; adjust the pointer cld rep movsb ; and save the string in argbuffer mov AL, ANULL ; tack a null byte on the end stosb mov argbufptr, DI ; update argbufptr after copy newarg_done: popf clc jmp short newarg_exit too_many_args: mov AX, arg_cnt_error jmp short newarg_error buf_ovflow: mov AX, arg_buf_ovflow newarg_error: popf stc newarg_exit: pop SI pop DI pop DX pop CX pop BX ret ;--------------- ; NewArg ends ;---------------------------------------------------------------------------- break <Arg_Switch> ;---------------------------------------------------------------------------- ; ARG_SWITCH decides if an argument might really be a switch. In the ; event that it is, and we can recognize ; ENTRY: ; As in <newarg>. ; EXIT: ; CF -- clear (wasn't a switch); set (was a switch) ; NOTE(S): ; * The mechanism mapping a switch into a bit-value depends entirely ; on the order of definition in the <switch_list> variable and the ; values chosen to define the bits in CMDT:COMEQU.ASM. Change either ; <switch_list> or the definitions in CMDT:COMEQU.ASM -- and rewrite ; this mechanism. This code taken from CMDT:TCODE.ASM. ; * The <switch_list> declared below is redundant to one declared in ; TDATA.ASM, and used in TCODE.ASM. ; * An ugly routine. ;--------------- ; CONSTANTS: ;--------------- ; Constants come from the definitions in CMDT:COMEQU.ASM. ;--------------- ; DATA: ;--------------- TRANSPACE SEGMENT PUBLIC BYTE ;AC000; extrn switch_list:byte switch_count EQU $-switch_list transpace ends ;--------------- Arg_Switch: ;--------------- push AX push BX push CX push DI pushf test BH, MASK sw_flag ; is it a switch? (preserve flag word) jz arg_no_switch0 cmp [LAST_ARG], -1 ; have we encountered any REAL args yet? je arg_no_switch1 ; no, so leading switches don't matter mov BX, [LAST_ARG] ; yes, add switch info to last REAL arg mov AX, OFFSET TRANGROUP:arg.argv call argv_calc or [BX].argsw_word, BP or arg.argswinfo, BP arg_yes_switch: ; ah, sweet success... popf stc jmp short arg_switch_exit arg_no_switch0: mov AX, arg.argvcnt ; future switches should then affect mov [LAST_ARG], AX ; this argument arg_no_switch1: ; wasn't a switch, or we're pretending popf clc arg_switch_exit: pop DI pop CX pop BX pop AX ret ;--------------- ; Arg_Switch ends ;---------------------------------------------------------------------------- break <Argv_calc> ;---------------------------------------------------------------------------- ; ARGV_CALC maps an array index into a byte-offset from the base of ; the supplied array. Method used for computing the address is: ; Array Index * Array Elt Size + Base Addr = Elt Addr ; ENTRY: ; AX -- base of array ; BX -- array index ; EXIT: ; BX -- byte offset ;--------------- argv_calc: push ax ; Save base mov al,bl ; al = array index mov bl,SIZE argv_ele ; bl = size of an argv element mul bl ; ax = base offset pop bx ; Get base add ax,bx ; Add in base offset xchg ax,bx ; Restore ax and put byte offset in bx ret ;--------------- ; argv_calc ends ;---------------------------------------------------------------------------- trancode ends end 
; A171757: Even numbers whose binary expansion begins 10. ; Submitted by Simon Strandgaard ; 2,4,8,10,16,18,20,22,32,34,36,38,40,42,44,46,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,256,258,260,262,264,266,268,270,272,274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,310,312,314,316,318,320,322,324,326 mov $1,1 sub $2,$0 div $0,2 lpb $0 div $0,2 mul $1,2 lpe sub $1,$2 mov $0,$1 mul $0,2
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // // Google C++ Testing and Mocking Framework (Google Test) // // Sometimes it's desirable to build Google Test by compiling a single file. // This file serves this purpose. // This line ensures that gtest.h can be compiled on its own, even // when it's fused. #include "gtest/gtest.h" // The following lines pull in the real gtest *.cc files. // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // // The Google C++ Testing and Mocking Framework (Google Test) // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). // GOOGLETEST_CM0004 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) namespace testing { // This helper class can be used to mock out Google Test failure reporting // so that we can test Google Test or code that builds on Google Test. // // An object of this class appends a TestPartResult object to the // TestPartResultArray object given in the constructor whenever a Google Test // failure is reported. It can either intercept only failures that are // generated in the same thread that created this object or it can intercept // all generated failures. The scope of this mock object can be controlled with // the second argument to the two arguments constructor. class GTEST_API_ ScopedFakeTestPartResultReporter : public TestPartResultReporterInterface { public: // The two possible mocking modes of this object. enum InterceptMode { INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. INTERCEPT_ALL_THREADS // Intercepts all failures. }; // The c'tor sets this object as the test part result reporter used // by Google Test. The 'result' parameter specifies where to report the // results. This reporter will only catch failures generated in the current // thread. DEPRECATED explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); // Same as above, but you can choose the interception scope of this object. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, TestPartResultArray* result); // The d'tor restores the previous test part result reporter. ~ScopedFakeTestPartResultReporter() override; // Appends the TestPartResult object to the TestPartResultArray // received in the constructor. // // This method is from the TestPartResultReporterInterface // interface. void ReportTestPartResult(const TestPartResult& result) override; private: void Init(); const InterceptMode intercept_mode_; TestPartResultReporterInterface* old_reporter_; TestPartResultArray* const result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); }; namespace internal { // A helper class for implementing EXPECT_FATAL_FAILURE() and // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. class GTEST_API_ SingleFailureChecker { public: // The constructor remembers the arguments. SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const std::string& substr); ~SingleFailureChecker(); private: const TestPartResultArray* const results_; const TestPartResult::Type type_; const std::string substr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); }; } // namespace internal } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // A set of macros for testing Google Test assertions or code that's expected // to generate Google Test fatal failures. It verifies that the given // statement will cause exactly one fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_FATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - 'statement' cannot reference local non-static variables or // non-static members of the current object. // - 'statement' cannot return a value. // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. The AcceptsMacroThatExpandsToUnprotectedComma test in // gtest_unittest.cc will fail to compile if we do that. #define EXPECT_FATAL_FAILURE(statement, substr) \ do { \ class GTestExpectFatalFailureHelper {\ public:\ static void Execute() { statement; }\ };\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\ GTestExpectFatalFailureHelper::Execute();\ }\ } while (::testing::internal::AlwaysFalse()) #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do { \ class GTestExpectFatalFailureHelper {\ public:\ static void Execute() { statement; }\ };\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ALL_THREADS, &gtest_failures);\ GTestExpectFatalFailureHelper::Execute();\ }\ } while (::testing::internal::AlwaysFalse()) // A macro for testing Google Test assertions or code that's expected to // generate Google Test non-fatal failures. It asserts that the given // statement will cause exactly one non-fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // 'statement' is allowed to reference local variables and members of // the current object. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. If we do that, the code won't compile when the user gives // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that // expands to code containing an unprotected comma. The // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc // catches that. // // For the same reason, we have to write // if (::testing::internal::AlwaysTrue()) { statement; } // instead of // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // to avoid an MSVC warning on unreachable code. #define EXPECT_NONFATAL_FAILURE(statement, substr) \ do {\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ } while (::testing::internal::AlwaysFalse()) #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do {\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ &gtest_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ } while (::testing::internal::AlwaysFalse()) #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #include <ctype.h> #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <wchar.h> #include <wctype.h> #include <algorithm> #include <iomanip> #include <limits> #include <list> #include <map> #include <ostream> // NOLINT #include <sstream> #include <vector> #if GTEST_OS_LINUX # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <fcntl.h> // NOLINT # include <limits.h> // NOLINT # include <sched.h> // NOLINT // Declares vsnprintf(). This header is not available on Windows. # include <strings.h> // NOLINT # include <sys/mman.h> // NOLINT # include <sys/time.h> // NOLINT # include <unistd.h> // NOLINT # include <string> #elif GTEST_OS_ZOS # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <sys/time.h> // NOLINT // On z/OS we additionally need strings.h for strcasecmp. # include <strings.h> // NOLINT #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. # include <windows.h> // NOLINT # undef min #elif GTEST_OS_WINDOWS // We are on Windows proper. # include <io.h> // NOLINT # include <sys/timeb.h> // NOLINT # include <sys/types.h> // NOLINT # include <sys/stat.h> // NOLINT # if GTEST_OS_WINDOWS_MINGW // MinGW has gettimeofday() but not _ftime64(). # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <sys/time.h> // NOLINT # endif // GTEST_OS_WINDOWS_MINGW // cpplint thinks that the header is already included, so we want to // silence it. # include <windows.h> // NOLINT # undef min #else // Assume other platforms have gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 // cpplint thinks that the header is already included, so we want to // silence it. # include <sys/time.h> // NOLINT # include <unistd.h> // NOLINT #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS # include <stdexcept> #endif #if GTEST_CAN_STREAM_RESULTS_ # include <arpa/inet.h> // NOLINT # include <netdb.h> // NOLINT # include <sys/socket.h> // NOLINT # include <sys/types.h> // NOLINT #endif // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // Utility functions and classes used by the Google C++ testing framework.// // This file contains purely Google Test's internal implementation. Please // DO NOT #INCLUDE IT IN A USER PROGRAM. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ #define GTEST_SRC_GTEST_INTERNAL_INL_H_ #ifndef _WIN32_WCE # include <errno.h> #endif // !_WIN32_WCE #include <stddef.h> #include <stdlib.h> // For strtoll/_strtoul64/malloc/free. #include <string.h> // For memmove. #include <algorithm> #include <memory> #include <string> #include <vector> #if GTEST_CAN_STREAM_RESULTS_ # include <arpa/inet.h> // NOLINT # include <netdb.h> // NOLINT #endif #if GTEST_OS_WINDOWS # include <windows.h> // NOLINT #endif // GTEST_OS_WINDOWS GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) namespace testing { // Declares the flags. // // We don't want the users to modify this flag in the code, but want // Google Test's own unit tests to be able to access it. Therefore we // declare it here as opposed to in gtest.h. GTEST_DECLARE_bool_(death_test_use_fork); namespace internal { // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; // Names of the flags (needed for parsing Google Test flags). const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; const char kBreakOnFailureFlag[] = "break_on_failure"; const char kCatchExceptionsFlag[] = "catch_exceptions"; const char kColorFlag[] = "color"; const char kFilterFlag[] = "filter"; const char kListTestsFlag[] = "list_tests"; const char kOutputFlag[] = "output"; const char kPrintTimeFlag[] = "print_time"; const char kPrintUTF8Flag[] = "print_utf8"; const char kRandomSeedFlag[] = "random_seed"; const char kRepeatFlag[] = "repeat"; const char kShuffleFlag[] = "shuffle"; const char kStackTraceDepthFlag[] = "stack_trace_depth"; const char kStreamResultToFlag[] = "stream_result_to"; const char kThrowOnFailureFlag[] = "throw_on_failure"; const char kFlagfileFlag[] = "flagfile"; // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. GTEST_API_ extern bool g_help_flag; // Returns the current time in milliseconds. GTEST_API_ TimeInMillis GetTimeInMillis(); // Returns true iff Google Test should use colors in the output. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); // Formats the given time in milliseconds as seconds. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); // Converts the given time in milliseconds to a date string in the ISO 8601 // format, without the timezone information. N.B.: due to the use the // non-reentrant localtime() function, this function is not thread safe. Do // not use it in any code that can be called from multiple threads. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); // Parses a string for an Int32 flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. GTEST_API_ bool ParseInt32Flag( const char* str, const char* flag, Int32* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { const unsigned int raw_seed = (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis()) : static_cast<unsigned int>(random_seed_flag); // Normalizes the actual seed to range [1, kMaxRandomSeed] such that // it's easy to type. const int normalized_seed = static_cast<int>((raw_seed - 1U) % static_cast<unsigned int>(kMaxRandomSeed)) + 1; return normalized_seed; } // Returns the first valid random seed after 'seed'. The behavior is // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is // considered to be 1. inline int GetNextRandomSeed(int seed) { GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) << "Invalid random seed " << seed << " - must be in [1, " << kMaxRandomSeed << "]."; const int next_seed = seed + 1; return (next_seed > kMaxRandomSeed) ? 1 : next_seed; } // This class saves the values of all Google Test flags in its c'tor, and // restores them in its d'tor. class GTestFlagSaver { public: // The c'tor. GTestFlagSaver() { also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); break_on_failure_ = GTEST_FLAG(break_on_failure); catch_exceptions_ = GTEST_FLAG(catch_exceptions); color_ = GTEST_FLAG(color); death_test_style_ = GTEST_FLAG(death_test_style); death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); filter_ = GTEST_FLAG(filter); internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); list_tests_ = GTEST_FLAG(list_tests); output_ = GTEST_FLAG(output); print_time_ = GTEST_FLAG(print_time); print_utf8_ = GTEST_FLAG(print_utf8); random_seed_ = GTEST_FLAG(random_seed); repeat_ = GTEST_FLAG(repeat); shuffle_ = GTEST_FLAG(shuffle); stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); stream_result_to_ = GTEST_FLAG(stream_result_to); throw_on_failure_ = GTEST_FLAG(throw_on_failure); } // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. ~GTestFlagSaver() { GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; GTEST_FLAG(break_on_failure) = break_on_failure_; GTEST_FLAG(catch_exceptions) = catch_exceptions_; GTEST_FLAG(color) = color_; GTEST_FLAG(death_test_style) = death_test_style_; GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; GTEST_FLAG(filter) = filter_; GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; GTEST_FLAG(list_tests) = list_tests_; GTEST_FLAG(output) = output_; GTEST_FLAG(print_time) = print_time_; GTEST_FLAG(print_utf8) = print_utf8_; GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(repeat) = repeat_; GTEST_FLAG(shuffle) = shuffle_; GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; GTEST_FLAG(stream_result_to) = stream_result_to_; GTEST_FLAG(throw_on_failure) = throw_on_failure_; } private: // Fields for saving the original values of flags. bool also_run_disabled_tests_; bool break_on_failure_; bool catch_exceptions_; std::string color_; std::string death_test_style_; bool death_test_use_fork_; std::string filter_; std::string internal_run_death_test_; bool list_tests_; std::string output_; bool print_time_; bool print_utf8_; internal::Int32 random_seed_; internal::Int32 repeat_; bool shuffle_; internal::Int32 stack_trace_depth_; std::string stream_result_to_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded(); // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (e.g., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. GTEST_API_ bool ShouldShard(const char* total_shards_str, const char* shard_index_str, bool in_subprocess_for_death_test); // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error and // and aborts. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. GTEST_API_ bool ShouldRunTestOnShard( int total_shards, int shard_index, int test_id); // STL container utilities. // Returns the number of elements in the given container that satisfy // the given predicate. template <class Container, typename Predicate> inline int CountIf(const Container& c, Predicate predicate) { // Implemented as an explicit loop since std::count_if() in libCstd on // Solaris has a non-standard signature. int count = 0; for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { if (predicate(*it)) ++count; } return count; } // Applies a function/functor to each element in the container. template <class Container, typename Functor> void ForEach(const Container& c, Functor functor) { std::for_each(c.begin(), c.end(), functor); } // Returns the i-th element of the vector, or default_value if i is not // in range [0, v.size()). template <typename E> inline E GetElementOr(const std::vector<E>& v, int i, E default_value) { return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i]; } // Performs an in-place shuffle of a range of the vector's elements. // 'begin' and 'end' are element indices as an STL-style range; // i.e. [begin, end) are shuffled, where 'end' == size() means to // shuffle to the end of the vector. template <typename E> void ShuffleRange(internal::Random* random, int begin, int end, std::vector<E>* v) { const int size = static_cast<int>(v->size()); GTEST_CHECK_(0 <= begin && begin <= size) << "Invalid shuffle range start " << begin << ": must be in range [0, " << size << "]."; GTEST_CHECK_(begin <= end && end <= size) << "Invalid shuffle range finish " << end << ": must be in range [" << begin << ", " << size << "]."; // Fisher-Yates shuffle, from // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle for (int range_width = end - begin; range_width >= 2; range_width--) { const int last_in_range = begin + range_width - 1; const int selected = begin + random->Generate(range_width); std::swap((*v)[selected], (*v)[last_in_range]); } } // Performs an in-place shuffle of the vector's elements. template <typename E> inline void Shuffle(internal::Random* random, std::vector<E>* v) { ShuffleRange(random, 0, static_cast<int>(v->size()), v); } // A function for deleting an object. Handy for being used as a // functor. template <typename T> static void Delete(T* x) { delete x; } // A predicate that checks the key of a TestProperty against a known key. // // TestPropertyKeyIs is copyable. class TestPropertyKeyIs { public: // Constructor. // // TestPropertyKeyIs has NO default constructor. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} // Returns true iff the test name of test property matches on key_. bool operator()(const TestProperty& test_property) const { return test_property.key() == key_; } private: std::string key_; }; // Class UnitTestOptions. // // This class contains functions for processing options the user // specifies when running the tests. It has only static members. // // In most cases, the user can specify an option using either an // environment variable or a command line flag. E.g. you can set the // test filter using either GTEST_FILTER or --gtest_filter. If both // the variable and the flag are present, the latter overrides the // former. class GTEST_API_ UnitTestOptions { public: // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. static std::string GetOutputFormat(); // Returns the absolute path of the requested output file, or the // default (test_detail.xml in the original working directory) if // none was explicitly specified. static std::string GetAbsolutePathToOutputFile(); // Functions for processing the gtest_filter flag. // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. static bool PatternMatchesString(const char *pattern, const char *str); // Returns true iff the user-specified filter matches the test suite // name and the test name. static bool FilterMatchesTest(const std::string& test_suite_name, const std::string& test_name); #if GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. static int GTestShouldProcessSEH(DWORD exception_code); #endif // GTEST_OS_WINDOWS // Returns true if "name" matches the ':' separated list of glob-style // filters in "filter". static bool MatchesFilter(const std::string& name, const char* filter); }; // Returns the current application's name, removing directory path if that // is present. Used by UnitTestOptions::GetOutputFile. GTEST_API_ FilePath GetCurrentExecutableName(); // The role interface for getting the OS stack trace as a string. class OsStackTraceGetterInterface { public: OsStackTraceGetterInterface() {} virtual ~OsStackTraceGetterInterface() {} // Returns the current OS stack trace as an std::string. Parameters: // // max_depth - the maximum number of stack frames to be included // in the trace. // skip_count - the number of top frames to be skipped; doesn't count // against max_depth. virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0; // UponLeavingGTest() should be called immediately before Google Test calls // user code. It saves some information about the current stack that // CurrentStackTrace() will use to find and hide Google Test stack frames. virtual void UponLeavingGTest() = 0; // This string is inserted in place of stack frames that are part of // Google Test's implementation. static const char* const kElidedFramesMarker; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); }; // A working implementation of the OsStackTraceGetterInterface interface. class OsStackTraceGetter : public OsStackTraceGetterInterface { public: OsStackTraceGetter() {} std::string CurrentStackTrace(int max_depth, int skip_count) override; void UponLeavingGTest() override; private: #if GTEST_HAS_ABSL Mutex mutex_; // Protects all internal state. // We save the stack frame below the frame that calls user code. // We do this because the address of the frame immediately below // the user code changes between the call to UponLeavingGTest() // and any calls to the stack trace code from within the user code. void* caller_frame_ = nullptr; #endif // GTEST_HAS_ABSL GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); }; // Information about a Google Test trace point. struct TraceInfo { const char* file; int line; std::string message; }; // This is the default global test part result reporter used in UnitTestImpl. // This class should only be used by UnitTestImpl. class DefaultGlobalTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part // result in the current test. void ReportTestPartResult(const TestPartResult& result) override; private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); }; // This is the default per thread test part result reporter used in // UnitTestImpl. This class should only be used by UnitTestImpl. class DefaultPerThreadTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. The implementation just // delegates to the current global test part result reporter of *unit_test_. void ReportTestPartResult(const TestPartResult& result) override; private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); }; // The private implementation of the UnitTest class. We don't protect // the methods under a mutex, as this class is not accessible by a // user and the UnitTest class that delegates work to this class does // proper locking. class GTEST_API_ UnitTestImpl { public: explicit UnitTestImpl(UnitTest* parent); virtual ~UnitTestImpl(); // There are two different ways to register your own TestPartResultReporter. // You can register your own repoter to listen either only for test results // from the current thread or for results from all threads. // By default, each per-thread test result repoter just passes a new // TestPartResult to the global test result reporter, which registers the // test part result for the currently running test. // Returns the global test part result reporter. TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); // Sets the global test part result reporter. void SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter); // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); // Sets the test part result reporter for the current thread. void SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter); // Gets the number of successful test suites. int successful_test_suite_count() const; // Gets the number of failed test suites. int failed_test_suite_count() const; // Gets the number of all test suites. int total_test_suite_count() const; // Gets the number of all test suites that contain at least one test // that should run. int test_suite_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; // Gets the number of skipped tests. int skipped_test_count() const; // Gets the number of failed tests. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; // Gets the number of disabled tests. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; // Gets the time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp() const { return start_timestamp_; } // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns true iff the unit test passed (i.e. all test suites passed). bool Passed() const { return !Failed(); } // Returns true iff the unit test failed (i.e. some test suite failed // or something outside of all tests failed). bool Failed() const { return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed(); } // Gets the i-th test suite among all the test suites. i can range from 0 to // total_test_suite_count() - 1. If i is not in that range, returns NULL. const TestSuite* GetTestSuite(int i) const { const int index = GetElementOr(test_suite_indices_, i, -1); return index < 0 ? nullptr : test_suites_[i]; } // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* GetTestCase(int i) const { return GetTestSuite(i); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Gets the i-th test suite among all the test suites. i can range from 0 to // total_test_suite_count() - 1. If i is not in that range, returns NULL. TestSuite* GetMutableSuiteCase(int i) { const int index = GetElementOr(test_suite_indices_, i, -1); return index < 0 ? nullptr : test_suites_[index]; } // Provides access to the event listener list. TestEventListeners* listeners() { return &listeners_; } // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* current_test_result(); // Returns the TestResult for the ad hoc test. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter // are the same; otherwise, deletes the old getter and makes the // input the current getter. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* os_stack_trace_getter(); // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; // Finds and returns a TestSuite with the given name. If one doesn't // exist, creates one and returns it. // // Arguments: // // test_suite_name: name of the test suite // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc); // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ TestCase* GetTestCase(const char* test_case_name, const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) { return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Adds a TestInfo to the unit test. // // Arguments: // // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite // test_info: the TestInfo object void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc, TestInfo* test_info) { // In order to support thread-safe death tests, we need to // remember the original working directory when the test program // was first invoked. We cannot do this in RUN_ALL_TESTS(), as // the user may have changed the current directory before calling // RUN_ALL_TESTS(). Therefore we capture the current directory in // AddTestInfo(), which is called to register a TEST or TEST_F // before main() is reached. if (original_working_dir_.IsEmpty()) { original_working_dir_.Set(FilePath::GetCurrentDir()); GTEST_CHECK_(!original_working_dir_.IsEmpty()) << "Failed to get the current working directory."; } GetTestSuite(test_info->test_suite_name(), test_info->type_param(), set_up_tc, tear_down_tc) ->AddTestInfo(test_info); } // Returns ParameterizedTestSuiteRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() { return parameterized_test_registry_; } // Sets the TestSuite object for the test that's currently running. void set_current_test_suite(TestSuite* a_current_test_suite) { current_test_suite_ = a_current_test_suite; } // Sets the TestInfo object for the test that's currently running. If // current_test_info is NULL, the assertion results will be stored in // ad_hoc_test_result_. void set_current_test_info(TestInfo* a_current_test_info) { current_test_info_ = a_current_test_info; } // Registers all parameterized tests defined using TEST_P and // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter // combination. This method can be called more then once; it has guards // protecting from registering the tests more then once. If // value-parameterized tests are disabled, RegisterParameterizedTests is // present but does nothing. void RegisterParameterizedTests(); // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, this test is considered to be failed, but // the rest of the tests will still be run. bool RunAllTests(); // Clears the results of all tests, except the ad hoc tests. void ClearNonAdHocTestResult() { ForEach(test_suites_, TestSuite::ClearTestSuiteResult); } // Clears the results of ad-hoc test assertions. void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test or a test suite, or to the global property set. If the // result already contains a property with the same key, the value will be // updated. void RecordProperty(const TestProperty& test_property); enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL }; // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the // result in each TestSuite and TestInfo object. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests // based on sharding variables in the environment. // Returns the number of tests that should run. int FilterTests(ReactionToSharding shard_tests); // Prints the names of the tests matching the user-specified filter flag. void ListTestsMatchingFilter(); const TestSuite* current_test_suite() const { return current_test_suite_; } TestInfo* current_test_info() { return current_test_info_; } const TestInfo* current_test_info() const { return current_test_info_; } // Returns the vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector<Environment*>& environments() { return environments_; } // Getters for the per-thread Google Test trace stack. std::vector<TraceInfo>& gtest_trace_stack() { return *(gtest_trace_stack_.pointer()); } const std::vector<TraceInfo>& gtest_trace_stack() const { return gtest_trace_stack_.get(); } #if GTEST_HAS_DEATH_TEST void InitDeathTestSubprocessControlInfo() { internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); } // Returns a pointer to the parsed --gtest_internal_run_death_test // flag, or NULL if that flag was not specified. // This information is useful only in a death test child process. // Must not be called before a call to InitGoogleTest. const InternalRunDeathTestFlag* internal_run_death_test_flag() const { return internal_run_death_test_flag_.get(); } // Returns a pointer to the current death test factory. internal::DeathTestFactory* death_test_factory() { return death_test_factory_.get(); } void SuppressTestEventsIfInSubprocess(); friend class ReplaceDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST // Initializes the event listener performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Initializes the event listener for streaming test results to a socket. // Must not be called before InitGoogleTest. void ConfigureStreamingOutput(); #endif // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void PostFlagParsingInit(); // Gets the random seed used at the start of the current test iteration. int random_seed() const { return random_seed_; } // Gets the random number generator. internal::Random* random() { return &random_; } // Shuffles all test suites, and the tests within each test suite, // making sure that death tests are still run first. void ShuffleTests(); // Restores the test suites and tests to their order before the first shuffle. void UnshuffleTests(); // Returns the value of GTEST_FLAG(catch_exceptions) at the moment // UnitTest::Run() starts. bool catch_exceptions() const { return catch_exceptions_; } private: friend class ::testing::UnitTest; // Used by UnitTest::Run() to capture the state of // GTEST_FLAG(catch_exceptions) at the moment it starts. void set_catch_exceptions(bool value) { catch_exceptions_ = value; } // The UnitTest object that owns this implementation object. UnitTest* const parent_; // The working directory when the first TEST() or TEST_F() was // executed. internal::FilePath original_working_dir_; // The default test part result reporters. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; DefaultPerThreadTestPartResultReporter default_per_thread_test_part_result_reporter_; // Points to (but doesn't own) the global test part result reporter. TestPartResultReporterInterface* global_test_part_result_repoter_; // Protects read and write access to global_test_part_result_reporter_. internal::Mutex global_test_part_result_reporter_mutex_; // Points to (but doesn't own) the per-thread test part result reporter. internal::ThreadLocal<TestPartResultReporterInterface*> per_thread_test_part_result_reporter_; // The vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector<Environment*> environments_; // The vector of TestSuites in their original order. It owns the // elements in the vector. std::vector<TestSuite*> test_suites_; // Provides a level of indirection for the test suite list to allow // easy shuffling and restoring the test suite order. The i-th // element of this vector is the index of the i-th test suite in the // shuffled order. std::vector<int> test_suite_indices_; // ParameterizedTestRegistry object used to register value-parameterized // tests. internal::ParameterizedTestSuiteRegistry parameterized_test_registry_; // Indicates whether RegisterParameterizedTests() has been called already. bool parameterized_tests_registered_; // Index of the last death test suite registered. Initially -1. int last_death_test_suite_; // This points to the TestSuite for the currently running test. It // changes as Google Test goes through one test suite after another. // When no test is running, this is set to NULL and Google Test // stores assertion results in ad_hoc_test_result_. Initially NULL. TestSuite* current_test_suite_; // This points to the TestInfo for the currently running test. It // changes as Google Test goes through one test after another. When // no test is running, this is set to NULL and Google Test stores // assertion results in ad_hoc_test_result_. Initially NULL. TestInfo* current_test_info_; // Normally, a user only writes assertions inside a TEST or TEST_F, // or inside a function called by a TEST or TEST_F. Since Google // Test keeps track of which test is current running, it can // associate such an assertion with the test it belongs to. // // If an assertion is encountered when no TEST or TEST_F is running, // Google Test attributes the assertion result to an imaginary "ad hoc" // test, and records the result in ad_hoc_test_result_. TestResult ad_hoc_test_result_; // The list of event listeners that can be used to track events inside // Google Test. TestEventListeners listeners_; // The OS stack trace getter. Will be deleted when the UnitTest // object is destructed. By default, an OsStackTraceGetter is used, // but the user can set this field to use a custom getter if that is // desired. OsStackTraceGetterInterface* os_stack_trace_getter_; // True iff PostFlagParsingInit() has been called. bool post_flag_parse_init_performed_; // The random number seed used at the beginning of the test run. int random_seed_; // Our random number generator. internal::Random random_; // The time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp_; // How long the test took to run, in milliseconds. TimeInMillis elapsed_time_; #if GTEST_HAS_DEATH_TEST // The decomposed components of the gtest_internal_run_death_test flag, // parsed when RUN_ALL_TESTS is called. std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; std::unique_ptr<internal::DeathTestFactory> death_test_factory_; #endif // GTEST_HAS_DEATH_TEST // A per-thread stack of traces created by the SCOPED_TRACE() macro. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() // starts. bool catch_exceptions_; GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); }; // class UnitTestImpl // Convenience function for accessing the global UnitTest // implementation object. inline UnitTestImpl* GetUnitTestImpl() { return UnitTest::GetInstance()->impl(); } #if GTEST_USES_SIMPLE_RE // Internal helper functions for implementing the simple regular // expression matcher. GTEST_API_ bool IsInSet(char ch, const char* str); GTEST_API_ bool IsAsciiDigit(char ch); GTEST_API_ bool IsAsciiPunct(char ch); GTEST_API_ bool IsRepeat(char ch); GTEST_API_ bool IsAsciiWhiteSpace(char ch); GTEST_API_ bool IsAsciiWordChar(char ch); GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); GTEST_API_ bool MatchRepetitionAndRegexAtHead( bool escaped, char ch, char repeat, const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); #endif // GTEST_USES_SIMPLE_RE // Parses the command line for Google Test flags, without initializing // other parts of Google Test. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); #if GTEST_HAS_DEATH_TEST // Returns the message describing the last system error, regardless of the // platform. GTEST_API_ std::string GetLastErrnoDescription(); // Attempts to parse a string into a positive integer pointed to by the // number parameter. Returns true if that is possible. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use // it here. template <typename Integer> bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // Fail fast if the given string does not begin with a digit; // this bypasses strtoXXX's "optional leading whitespace and plus // or minus sign" semantics, which are undesirable here. if (str.empty() || !IsDigit(str[0])) { return false; } errno = 0; char* end; // BiggestConvertible is the largest integer type that system-provided // string-to-number conversion routines can return. # if GTEST_OS_WINDOWS && !defined(__GNUC__) // MSVC and C++ Builder define __int64 instead of the standard long long. typedef unsigned __int64 BiggestConvertible; const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); # else typedef unsigned long long BiggestConvertible; // NOLINT const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); # endif // GTEST_OS_WINDOWS && !defined(__GNUC__) const bool parse_success = *end == '\0' && errno == 0; GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); const Integer result = static_cast<Integer>(parsed); if (parse_success && static_cast<BiggestConvertible>(result) == parsed) { *number = result; return true; } return false; } #endif // GTEST_HAS_DEATH_TEST // TestResult contains some private methods that should be hidden from // Google Test user but are required for testing. This class allow our tests // to access them. // // This class is supplied only for the purpose of testing Google Test's own // constructs. Do not use it in user tests, either directly or indirectly. class TestResultAccessor { public: static void RecordProperty(TestResult* test_result, const std::string& xml_element, const TestProperty& property) { test_result->RecordProperty(xml_element, property); } static void ClearTestPartResults(TestResult* test_result) { test_result->ClearTestPartResults(); } static const std::vector<testing::TestPartResult>& test_part_results( const TestResult& test_result) { return test_result.test_part_results(); } }; #if GTEST_CAN_STREAM_RESULTS_ // Streams test results to the given port on the given host machine. class StreamingListener : public EmptyTestEventListener { public: // Abstract base class for writing strings to a socket. class AbstractSocketWriter { public: virtual ~AbstractSocketWriter() {} // Sends a string to the socket. virtual void Send(const std::string& message) = 0; // Closes the socket. virtual void CloseConnection() {} // Sends a string and a newline to the socket. void SendLn(const std::string& message) { Send(message + "\n"); } }; // Concrete class for actually writing strings to a socket. class SocketWriter : public AbstractSocketWriter { public: SocketWriter(const std::string& host, const std::string& port) : sockfd_(-1), host_name_(host), port_num_(port) { MakeConnection(); } ~SocketWriter() override { if (sockfd_ != -1) CloseConnection(); } // Sends a string to the socket. void Send(const std::string& message) override { GTEST_CHECK_(sockfd_ != -1) << "Send() can be called only when there is a connection."; const int len = static_cast<int>(message.length()); if (write(sockfd_, message.c_str(), len) != len) { GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to " << host_name_ << ":" << port_num_; } } private: // Creates a client socket and connects to the server. void MakeConnection(); // Closes the socket. void CloseConnection() override { GTEST_CHECK_(sockfd_ != -1) << "CloseConnection() can be called only when there is a connection."; close(sockfd_); sockfd_ = -1; } int sockfd_; // socket file descriptor const std::string host_name_; const std::string port_num_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); }; // class SocketWriter // Escapes '=', '&', '%', and '\n' characters in str as "%xx". static std::string UrlEncode(const char* str); StreamingListener(const std::string& host, const std::string& port) : socket_writer_(new SocketWriter(host, port)) { Start(); } explicit StreamingListener(AbstractSocketWriter* socket_writer) : socket_writer_(socket_writer) { Start(); } void OnTestProgramStart(const UnitTest& /* unit_test */) override { SendLn("event=TestProgramStart"); } void OnTestProgramEnd(const UnitTest& unit_test) override { // Note that Google Test current only report elapsed time for each // test iteration, not for the entire test program. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); // Notify the streaming server to stop. socket_writer_->CloseConnection(); } void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) override { SendLn("event=TestIterationStart&iteration=" + StreamableToString(iteration)); } void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) override { SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) + "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) + "ms"); } // Note that "event=TestCaseStart" is a wire format and has to remain // "case" for compatibilty void OnTestCaseStart(const TestCase& test_case) override { SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); } // Note that "event=TestCaseEnd" is a wire format and has to remain // "case" for compatibilty void OnTestCaseEnd(const TestCase& test_case) override { SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + "ms"); } void OnTestStart(const TestInfo& test_info) override { SendLn(std::string("event=TestStart&name=") + test_info.name()); } void OnTestEnd(const TestInfo& test_info) override { SendLn("event=TestEnd&passed=" + FormatBool((test_info.result())->Passed()) + "&elapsed_time=" + StreamableToString((test_info.result())->elapsed_time()) + "ms"); } void OnTestPartResult(const TestPartResult& test_part_result) override { const char* file_name = test_part_result.file_name(); if (file_name == nullptr) file_name = ""; SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + "&line=" + StreamableToString(test_part_result.line_number()) + "&message=" + UrlEncode(test_part_result.message())); } private: // Sends the given message and a newline to the socket. void SendLn(const std::string& message) { socket_writer_->SendLn(message); } // Called at the start of streaming to notify the receiver what // protocol we are using. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } std::string FormatBool(bool value) { return value ? "1" : "0"; } const std::unique_ptr<AbstractSocketWriter> socket_writer_; GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); }; // class StreamingListener #endif // GTEST_CAN_STREAM_RESULTS_ } // namespace internal } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ #if GTEST_OS_WINDOWS # define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC #ifndef GTEST_OS_IOS #include <crt_externs.h> #endif #endif #if GTEST_HAS_ABSL #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/strings/str_cat.h" #endif // GTEST_HAS_ABSL namespace testing { using internal::CountIf; using internal::ForEach; using internal::GetElementOr; using internal::Shuffle; // Constants. // A test whose test suite name or test name matches this filter is // disabled and not run. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; // A test suite whose name matches this filter is considered a death // test suite and will be run before test suites whose name doesn't // match this filter. static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*"; // A test filter that matches everything. static const char kUniversalFilter[] = "*"; // The default output format. static const char kDefaultOutputFormat[] = "xml"; // The default output file. static const char kDefaultOutputFile[] = "test_detail"; // The environment variable name for the test shard index. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; // The environment variable name for the total number of test shards. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; // The environment variable name for the test shard status file. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; namespace internal { // The text used in failure messages to indicate the start of the // stack trace. const char kStackTraceMarker[] = "\nStack trace:\n"; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. bool g_help_flag = false; // Utilty function to Open File for Writing static FILE* OpenFileForWriting(const std::string& output_file) { FILE* fileout = nullptr; FilePath output_file_path(output_file); FilePath output_dir(output_file_path.RemoveFileName()); if (output_dir.CreateDirectoriesRecursively()) { fileout = posix::FOpen(output_file.c_str(), "w"); } if (fileout == nullptr) { GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\""; } return fileout; } } // namespace internal // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY // environment variable. static const char* GetDefaultFilter() { const char* const testbridge_test_only = internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY"); if (testbridge_test_only != nullptr) { return testbridge_test_only; } return kUniversalFilter; } GTEST_DEFINE_bool_( also_run_disabled_tests, internal::BoolFromGTestEnv("also_run_disabled_tests", false), "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), "True iff a failed assertion should be a debugger break-point."); GTEST_DEFINE_bool_( catch_exceptions, internal::BoolFromGTestEnv("catch_exceptions", true), "True iff " GTEST_NAME_ " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( color, internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to a terminal type that supports colors."); GTEST_DEFINE_string_( filter, internal::StringFromGTestEnv("filter", GetDefaultFilter()), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " "exclude). A test is run if it matches one of the positive " "patterns and does not match any of the negative patterns."); GTEST_DEFINE_bool_( install_failure_signal_handler, internal::BoolFromGTestEnv("install_failure_signal_handler", false), "If true and supported on the current platform, " GTEST_NAME_ " should " "install a signal handler that dumps debugging information when fatal " "signals are raised."); GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); // The net priority order after flag processing is thus: // --gtest_output command line flag // GTEST_OUTPUT environment variable // XML_OUTPUT_FILE environment variable // '' GTEST_DEFINE_string_( output, internal::StringFromGTestEnv("output", internal::OutputFlagAlsoCheckEnvVar().c_str()), "A format (defaults to \"xml\" but can be specified to be \"json\"), " "optionally followed by a colon and an output file name or directory. " "A directory is indicated by a trailing pathname separator. " "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " "If a directory is specified, output files will be created " "within that directory, with file-names based on the test " "executable's name and, if necessary, made unique by adding " "digits."); GTEST_DEFINE_bool_( print_time, internal::BoolFromGTestEnv("print_time", true), "True iff " GTEST_NAME_ " should display elapsed time in text output."); GTEST_DEFINE_bool_( print_utf8, internal::BoolFromGTestEnv("print_utf8", true), "True iff " GTEST_NAME_ " prints UTF8 characters as text."); GTEST_DEFINE_int32_( random_seed, internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time."); GTEST_DEFINE_int32_( repeat, internal::Int32FromGTestEnv("repeat", 1), "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); GTEST_DEFINE_bool_( show_internal_stack_frames, false, "True iff " GTEST_NAME_ " should include internal stack frames when " "printing test failure stack traces."); GTEST_DEFINE_bool_( shuffle, internal::BoolFromGTestEnv("shuffle", false), "True iff " GTEST_NAME_ " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); GTEST_DEFINE_string_( stream_result_to, internal::StringFromGTestEnv("stream_result_to", ""), "This flag specifies the host name and the port number on which to stream " "test results. Example: \"localhost:555\". The flag is effective only on " "Linux."); GTEST_DEFINE_bool_( throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false), "When this flag is specified, a failed assertion will throw an exception " "if exceptions are enabled or exit the program with a non-zero code " "otherwise. For use with an external test framework."); #if GTEST_USE_OWN_FLAGFILE_FLAG_ GTEST_DEFINE_string_( flagfile, internal::StringFromGTestEnv("flagfile", ""), "This flag specifies the flagfile to read command-line flags from."); #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ namespace internal { // Generates a random number from [0, range), using a Linear // Congruential Generator (LCG). Crashes if 'range' is 0 or greater // than kMaxRange. UInt32 Random::Generate(UInt32 range) { // These constants are the same as are used in glibc's rand(3). // Use wider types than necessary to prevent unsigned overflow diagnostics. state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange; GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; GTEST_CHECK_(range <= kMaxRange) << "Generation of a number in [0, " << range << ") was requested, " << "but this can only generate numbers in [0, " << kMaxRange << ")."; // Converting via modulus introduces a bit of downward bias, but // it's simple, and a linear congruential generator isn't too good // to begin with. return state_ % range; } // GTestIsInitialized() returns true iff the user has initialized // Google Test. Useful for catching the user mistake of not initializing // Google Test before calling RUN_ALL_TESTS(). static bool GTestIsInitialized() { return GetArgvs().size() > 0; } // Iterates over a vector of TestSuites, keeping a running sum of the // results of calling a given int-returning method on each. // Returns the sum. static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list, int (TestSuite::*method)() const) { int sum = 0; for (size_t i = 0; i < case_list.size(); i++) { sum += (case_list[i]->*method)(); } return sum; } // Returns true iff the test suite passed. static bool TestSuitePassed(const TestSuite* test_suite) { return test_suite->should_run() && test_suite->Passed(); } // Returns true iff the test suite failed. static bool TestSuiteFailed(const TestSuite* test_suite) { return test_suite->should_run() && test_suite->Failed(); } // Returns true iff test_suite contains at least one test that should // run. static bool ShouldRunTestSuite(const TestSuite* test_suite) { return test_suite->should_run(); } // AssertHelper constructor. AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) : data_(new AssertHelperData(type, file, line, message)) { } AssertHelper::~AssertHelper() { delete data_; } // Message assignment, for assertion streaming support. void AssertHelper::operator=(const Message& message) const { UnitTest::GetInstance()-> AddTestPartResult(data_->type, data_->file, data_->line, AppendUserMessage(data_->message, message), UnitTest::GetInstance()->impl() ->CurrentOsStackTraceExceptTop(1) // Skips the stack frame for this function itself. ); // NOLINT } // A copy of all command line arguments. Set by InitGoogleTest(). static ::std::vector<std::string> g_argvs; ::std::vector<std::string> GetArgvs() { #if defined(GTEST_CUSTOM_GET_ARGVS_) // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or // ::string. This code converts it to the appropriate type. const auto& custom = GTEST_CUSTOM_GET_ARGVS_(); return ::std::vector<std::string>(custom.begin(), custom.end()); #else // defined(GTEST_CUSTOM_GET_ARGVS_) return g_argvs; #endif // defined(GTEST_CUSTOM_GET_ARGVS_) } // Returns the current application's name, removing directory path if that // is present. FilePath GetCurrentExecutableName() { FilePath result; #if GTEST_OS_WINDOWS || GTEST_OS_OS2 result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); #else result.Set(FilePath(GetArgvs()[0])); #endif // GTEST_OS_WINDOWS return result.RemoveDirectoryName(); } // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. std::string UnitTestOptions::GetOutputFormat() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); const char* const colon = strchr(gtest_output_flag, ':'); return (colon == nullptr) ? std::string(gtest_output_flag) : std::string(gtest_output_flag, colon - gtest_output_flag); } // Returns the name of the requested output file, or the default if none // was explicitly specified. std::string UnitTestOptions::GetAbsolutePathToOutputFile() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); std::string format = GetOutputFormat(); if (format.empty()) format = std::string(kDefaultOutputFormat); const char* const colon = strchr(gtest_output_flag, ':'); if (colon == nullptr) return internal::FilePath::MakeFileName( internal::FilePath( UnitTest::GetInstance()->original_working_dir()), internal::FilePath(kDefaultOutputFile), 0, format.c_str()).string(); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) output_name = internal::FilePath::ConcatPaths( internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); if (!output_name.IsDirectory()) return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), GetOutputFormat().c_str())); return result.string(); } // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. bool UnitTestOptions::PatternMatchesString(const char *pattern, const char *str) { switch (*pattern) { case '\0': case ':': // Either ':' or '\0' marks the end of the pattern. return *str == '\0'; case '?': // Matches any single character. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); case '*': // Matches any string (possibly empty) of characters. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || PatternMatchesString(pattern + 1, str); default: // Non-special character. Matches itself. return *pattern == *str && PatternMatchesString(pattern + 1, str + 1); } } bool UnitTestOptions::MatchesFilter( const std::string& name, const char* filter) { const char *cur_pattern = filter; for (;;) { if (PatternMatchesString(cur_pattern, name.c_str())) { return true; } // Finds the next pattern in the filter. cur_pattern = strchr(cur_pattern, ':'); // Returns if no more pattern can be found. if (cur_pattern == nullptr) { return false; } // Skips the pattern separater (the ':' character). cur_pattern++; } } // Returns true iff the user-specified filter matches the test suite // name and the test name. bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, const std::string& test_name) { const std::string& full_name = test_suite_name + "." + test_name.c_str(); // Split --gtest_filter at '-', if there is one, to separate into // positive filter and negative filter portions const char* const p = GTEST_FLAG(filter).c_str(); const char* const dash = strchr(p, '-'); std::string positive; std::string negative; if (dash == nullptr) { positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter negative = ""; } else { positive = std::string(p, dash); // Everything up to the dash negative = std::string(dash + 1); // Everything after the dash if (positive.empty()) { // Treat '-test1' as the same as '*-test1' positive = kUniversalFilter; } } // A filter is a colon-separated list of patterns. It matches a // test if any pattern in it matches the test. return (MatchesFilter(full_name, positive.c_str()) && !MatchesFilter(full_name, negative.c_str())); } #if GTEST_HAS_SEH // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { // Google Test should handle a SEH exception if: // 1. the user wants it to, AND // 2. this is not a breakpoint exception, AND // 3. this is not a C++ exception (VC++ implements them via SEH, // apparently). // // SEH exception code for C++ exceptions. // (see http://support.microsoft.com/kb/185294 for more information). const DWORD kCxxExceptionCode = 0xe06d7363; bool should_handle = true; if (!GTEST_FLAG(catch_exceptions)) should_handle = false; else if (exception_code == EXCEPTION_BREAKPOINT) should_handle = false; else if (exception_code == kCxxExceptionCode) should_handle = false; return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; } #endif // GTEST_HAS_SEH } // namespace internal // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. Intercepts only failures from the current thread. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( TestPartResultArray* result) : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) { Init(); } // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( InterceptMode intercept_mode, TestPartResultArray* result) : intercept_mode_(intercept_mode), result_(result) { Init(); } void ScopedFakeTestPartResultReporter::Init() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); if (intercept_mode_ == INTERCEPT_ALL_THREADS) { old_reporter_ = impl->GetGlobalTestPartResultReporter(); impl->SetGlobalTestPartResultReporter(this); } else { old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); impl->SetTestPartResultReporterForCurrentThread(this); } } // The d'tor restores the test part result reporter used by Google Test // before. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); if (intercept_mode_ == INTERCEPT_ALL_THREADS) { impl->SetGlobalTestPartResultReporter(old_reporter_); } else { impl->SetTestPartResultReporterForCurrentThread(old_reporter_); } } // Increments the test part result count and remembers the result. // This method is from the TestPartResultReporterInterface interface. void ScopedFakeTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { result_->Append(result); } namespace internal { // Returns the type ID of ::testing::Test. We should always call this // instead of GetTypeId< ::testing::Test>() to get the type ID of // testing::Test. This is to work around a suspected linker bug when // using Google Test as a framework on Mac OS X. The bug causes // GetTypeId< ::testing::Test>() to return different values depending // on whether the call is from the Google Test framework itself or // from user test code. GetTestTypeId() is guaranteed to always // return the same value, as it always calls GetTypeId<>() from the // gtest.cc, which is within the Google Test framework. TypeId GetTestTypeId() { return GetTypeId<Test>(); } // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); // This predicate-formatter checks that 'results' contains a test part // failure of the given type and that the failure message contains the // given substring. static AssertionResult HasOneFailure(const char* /* results_expr */, const char* /* type_expr */, const char* /* substr_expr */, const TestPartResultArray& results, TestPartResult::Type type, const std::string& substr) { const std::string expected(type == TestPartResult::kFatalFailure ? "1 fatal failure" : "1 non-fatal failure"); Message msg; if (results.size() != 1) { msg << "Expected: " << expected << "\n" << " Actual: " << results.size() << " failures"; for (int i = 0; i < results.size(); i++) { msg << "\n" << results.GetTestPartResult(i); } return AssertionFailure() << msg; } const TestPartResult& r = results.GetTestPartResult(0); if (r.type() != type) { return AssertionFailure() << "Expected: " << expected << "\n" << " Actual:\n" << r; } if (strstr(r.message(), substr.c_str()) == nullptr) { return AssertionFailure() << "Expected: " << expected << " containing \"" << substr << "\"\n" << " Actual:\n" << r; } return AssertionSuccess(); } // The constructor of SingleFailureChecker remembers where to look up // test part results, what type of failure we expect, and what // substring the failure message should contain. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const std::string& substr) : results_(results), type_(type), substr_(substr) {} // The destructor of SingleFailureChecker verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. SingleFailureChecker::~SingleFailureChecker() { EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultGlobalTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->current_test_result()->AddTestPartResult(result); unit_test_->listeners()->repeater()->OnTestPartResult(result); } DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); } // Returns the global test part result reporter. TestPartResultReporterInterface* UnitTestImpl::GetGlobalTestPartResultReporter() { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); return global_test_part_result_repoter_; } // Sets the global test part result reporter. void UnitTestImpl::SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter) { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); global_test_part_result_repoter_ = reporter; } // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* UnitTestImpl::GetTestPartResultReporterForCurrentThread() { return per_thread_test_part_result_reporter_.get(); } // Sets the test part result reporter for the current thread. void UnitTestImpl::SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter) { per_thread_test_part_result_reporter_.set(reporter); } // Gets the number of successful test suites. int UnitTestImpl::successful_test_suite_count() const { return CountIf(test_suites_, TestSuitePassed); } // Gets the number of failed test suites. int UnitTestImpl::failed_test_suite_count() const { return CountIf(test_suites_, TestSuiteFailed); } // Gets the number of all test suites. int UnitTestImpl::total_test_suite_count() const { return static_cast<int>(test_suites_.size()); } // Gets the number of all test suites that contain at least one test // that should run. int UnitTestImpl::test_suite_to_run_count() const { return CountIf(test_suites_, ShouldRunTestSuite); } // Gets the number of successful tests. int UnitTestImpl::successful_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count); } // Gets the number of skipped tests. int UnitTestImpl::skipped_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count); } // Gets the number of failed tests. int UnitTestImpl::failed_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count); } // Gets the number of disabled tests that will be reported in the XML report. int UnitTestImpl::reportable_disabled_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_disabled_test_count); } // Gets the number of disabled tests. int UnitTestImpl::disabled_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count); } // Gets the number of tests to be printed in the XML report. int UnitTestImpl::reportable_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count); } // Gets the number of all tests. int UnitTestImpl::total_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count); } // Gets the number of tests that should run. int UnitTestImpl::test_to_run_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count); } // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { return os_stack_trace_getter()->CurrentStackTrace( static_cast<int>(GTEST_FLAG(stack_trace_depth)), skip_count + 1 // Skips the user-specified number of frames plus this function // itself. ); // NOLINT } // Returns the current time in milliseconds. TimeInMillis GetTimeInMillis() { #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) // Difference between 1970-01-01 and 1601-01-01 in milliseconds. // http://analogous.blogspot.com/2005/04/epoch.html const TimeInMillis kJavaEpochToWinFileTimeDelta = static_cast<TimeInMillis>(116444736UL) * 100000UL; const DWORD kTenthMicrosInMilliSecond = 10000; SYSTEMTIME now_systime; FILETIME now_filetime; ULARGE_INTEGER now_int64; GetSystemTime(&now_systime); if (SystemTimeToFileTime(&now_systime, &now_filetime)) { now_int64.LowPart = now_filetime.dwLowDateTime; now_int64.HighPart = now_filetime.dwHighDateTime; now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - kJavaEpochToWinFileTimeDelta; return now_int64.QuadPart; } return 0; #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ __timeb64 now; // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 // (deprecated function) there. GTEST_DISABLE_MSC_DEPRECATED_PUSH_() _ftime64(&now); GTEST_DISABLE_MSC_DEPRECATED_POP_() return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm; #elif GTEST_HAS_GETTIMEOFDAY_ struct timeval now; gettimeofday(&now, nullptr); return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000; #else # error "Don't know how to get the current time on your system." #endif } // Utilities // class String. #if GTEST_OS_WINDOWS_MOBILE // Creates a UTF-16 wide string from the given ANSI string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the wide string, or NULL if the // input is NULL. LPCWSTR String::AnsiToUtf16(const char* ansi) { if (!ansi) return nullptr; const int length = strlen(ansi); const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } // Creates an ANSI string from the given wide string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return nullptr; const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, 0, nullptr, nullptr); char* ansi = new char[ansi_length + 1]; WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr, nullptr); ansi[ansi_length] = 0; return ansi; } #endif // GTEST_OS_WINDOWS_MOBILE // Compares two C strings. Returns true iff they have the same content. // // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::CStringEquals(const char * lhs, const char * rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; return strcmp(lhs, rhs) == 0; } #if GTEST_HAS_STD_WSTRING // Converts an array of wide chars to a narrow string using the UTF-8 // encoding, and streams the result to the given Message object. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { for (size_t i = 0; i != length; ) { // NOLINT if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); while (i != length && wstr[i] != L'\0') i++; } else { *msg << '\0'; i++; } } } #endif // GTEST_HAS_STD_WSTRING void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest) { ::std::vector< ::std::string> parsed; ::std::string::size_type pos = 0; while (::testing::internal::AlwaysTrue()) { const ::std::string::size_type colon = str.find(delimiter, pos); if (colon == ::std::string::npos) { parsed.push_back(str.substr(pos)); break; } else { parsed.push_back(str.substr(pos, colon - pos)); pos = colon + 1; } } dest->swap(parsed); } } // namespace internal // Constructs an empty Message. // We allocate the stringstream separately because otherwise each use of // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's // stack frame leading to huge stack frames in some cases; gcc does not reuse // the stack space. Message::Message() : ss_(new ::std::stringstream) { // By default, we want there to be enough precision when printing // a double to a Message. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. Message& Message::operator <<(const wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } Message& Message::operator <<(wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& Message::operator <<(const ::std::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } #endif // GTEST_HAS_STD_WSTRING // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". std::string Message::GetString() const { return internal::StringStreamToString(ss_.get()); } // AssertionResult constructors. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult::AssertionResult(const AssertionResult& other) : success_(other.success_), message_(other.message_.get() != nullptr ? new ::std::string(*other.message_) : static_cast< ::std::string*>(nullptr)) {} // Swaps two AssertionResults. void AssertionResult::swap(AssertionResult& other) { using std::swap; swap(success_, other.success_); swap(message_, other.message_); } // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult AssertionResult::operator!() const { AssertionResult negation(!success_); if (message_.get() != nullptr) negation << *message_; return negation; } // Makes a successful assertion result. AssertionResult AssertionSuccess() { return AssertionResult(true); } // Makes a failed assertion result. AssertionResult AssertionFailure() { return AssertionResult(false); } // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << message. AssertionResult AssertionFailure(const Message& message) { return AssertionFailure() << message; } namespace internal { namespace edit_distance { std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left, const std::vector<size_t>& right) { std::vector<std::vector<double> > costs( left.size() + 1, std::vector<double>(right.size() + 1)); std::vector<std::vector<EditType> > best_move( left.size() + 1, std::vector<EditType>(right.size() + 1)); // Populate for empty right. for (size_t l_i = 0; l_i < costs.size(); ++l_i) { costs[l_i][0] = static_cast<double>(l_i); best_move[l_i][0] = kRemove; } // Populate for empty left. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) { costs[0][r_i] = static_cast<double>(r_i); best_move[0][r_i] = kAdd; } for (size_t l_i = 0; l_i < left.size(); ++l_i) { for (size_t r_i = 0; r_i < right.size(); ++r_i) { if (left[l_i] == right[r_i]) { // Found a match. Consume it. costs[l_i + 1][r_i + 1] = costs[l_i][r_i]; best_move[l_i + 1][r_i + 1] = kMatch; continue; } const double add = costs[l_i + 1][r_i]; const double remove = costs[l_i][r_i + 1]; const double replace = costs[l_i][r_i]; if (add < remove && add < replace) { costs[l_i + 1][r_i + 1] = add + 1; best_move[l_i + 1][r_i + 1] = kAdd; } else if (remove < add && remove < replace) { costs[l_i + 1][r_i + 1] = remove + 1; best_move[l_i + 1][r_i + 1] = kRemove; } else { // We make replace a little more expensive than add/remove to lower // their priority. costs[l_i + 1][r_i + 1] = replace + 1.00001; best_move[l_i + 1][r_i + 1] = kReplace; } } } // Reconstruct the best path. We do it in reverse order. std::vector<EditType> best_path; for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) { EditType move = best_move[l_i][r_i]; best_path.push_back(move); l_i -= move != kAdd; r_i -= move != kRemove; } std::reverse(best_path.begin(), best_path.end()); return best_path; } namespace { // Helper class to convert string into ids with deduplication. class InternalStrings { public: size_t GetId(const std::string& str) { IdMap::iterator it = ids_.find(str); if (it != ids_.end()) return it->second; size_t id = ids_.size(); return ids_[str] = id; } private: typedef std::map<std::string, size_t> IdMap; IdMap ids_; }; } // namespace std::vector<EditType> CalculateOptimalEdits( const std::vector<std::string>& left, const std::vector<std::string>& right) { std::vector<size_t> left_ids, right_ids; { InternalStrings intern_table; for (size_t i = 0; i < left.size(); ++i) { left_ids.push_back(intern_table.GetId(left[i])); } for (size_t i = 0; i < right.size(); ++i) { right_ids.push_back(intern_table.GetId(right[i])); } } return CalculateOptimalEdits(left_ids, right_ids); } namespace { // Helper class that holds the state for one hunk and prints it out to the // stream. // It reorders adds/removes when possible to group all removes before all // adds. It also adds the hunk header before printint into the stream. class Hunk { public: Hunk(size_t left_start, size_t right_start) : left_start_(left_start), right_start_(right_start), adds_(), removes_(), common_() {} void PushLine(char edit, const char* line) { switch (edit) { case ' ': ++common_; FlushEdits(); hunk_.push_back(std::make_pair(' ', line)); break; case '-': ++removes_; hunk_removes_.push_back(std::make_pair('-', line)); break; case '+': ++adds_; hunk_adds_.push_back(std::make_pair('+', line)); break; } } void PrintTo(std::ostream* os) { PrintHeader(os); FlushEdits(); for (std::list<std::pair<char, const char*> >::const_iterator it = hunk_.begin(); it != hunk_.end(); ++it) { *os << it->first << it->second << "\n"; } } bool has_edits() const { return adds_ || removes_; } private: void FlushEdits() { hunk_.splice(hunk_.end(), hunk_removes_); hunk_.splice(hunk_.end(), hunk_adds_); } // Print a unified diff header for one hunk. // The format is // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@" // where the left/right parts are omitted if unnecessary. void PrintHeader(std::ostream* ss) const { *ss << "@@ "; if (removes_) { *ss << "-" << left_start_ << "," << (removes_ + common_); } if (removes_ && adds_) { *ss << " "; } if (adds_) { *ss << "+" << right_start_ << "," << (adds_ + common_); } *ss << " @@\n"; } size_t left_start_, right_start_; size_t adds_, removes_, common_; std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_; }; } // namespace // Create a list of diff hunks in Unified diff format. // Each hunk has a header generated by PrintHeader above plus a body with // lines prefixed with ' ' for no change, '-' for deletion and '+' for // addition. // 'context' represents the desired unchanged prefix/suffix around the diff. // If two hunks are close enough that their contexts overlap, then they are // joined into one hunk. std::string CreateUnifiedDiff(const std::vector<std::string>& left, const std::vector<std::string>& right, size_t context) { const std::vector<EditType> edits = CalculateOptimalEdits(left, right); size_t l_i = 0, r_i = 0, edit_i = 0; std::stringstream ss; while (edit_i < edits.size()) { // Find first edit. while (edit_i < edits.size() && edits[edit_i] == kMatch) { ++l_i; ++r_i; ++edit_i; } // Find the first line to include in the hunk. const size_t prefix_context = std::min(l_i, context); Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1); for (size_t i = prefix_context; i > 0; --i) { hunk.PushLine(' ', left[l_i - i].c_str()); } // Iterate the edits until we found enough suffix for the hunk or the input // is over. size_t n_suffix = 0; for (; edit_i < edits.size(); ++edit_i) { if (n_suffix >= context) { // Continue only if the next hunk is very close. std::vector<EditType>::const_iterator it = edits.begin() + edit_i; while (it != edits.end() && *it == kMatch) ++it; if (it == edits.end() || (it - edits.begin()) - edit_i >= context) { // There is no next edit or it is too far away. break; } } EditType edit = edits[edit_i]; // Reset count when a non match is found. n_suffix = edit == kMatch ? n_suffix + 1 : 0; if (edit == kMatch || edit == kRemove || edit == kReplace) { hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str()); } if (edit == kAdd || edit == kReplace) { hunk.PushLine('+', right[r_i].c_str()); } // Advance indices, depending on edit type. l_i += edit != kAdd; r_i += edit != kRemove; } if (!hunk.has_edits()) { // We are done. We don't want this hunk. break; } hunk.PrintTo(&ss); } return ss.str(); } } // namespace edit_distance namespace { // The string representation of the values received in EqFailure() are already // escaped. Split them on escaped '\n' boundaries. Leave all other escaped // characters the same. std::vector<std::string> SplitEscapedString(const std::string& str) { std::vector<std::string> lines; size_t start = 0, end = str.size(); if (end > 2 && str[0] == '"' && str[end - 1] == '"') { ++start; --end; } bool escaped = false; for (size_t i = start; i + 1 < end; ++i) { if (escaped) { escaped = false; if (str[i] == 'n') { lines.push_back(str.substr(start, i - start - 1)); start = i + 1; } } else { escaped = str[i] == '\\'; } } lines.push_back(str.substr(start, end - start)); return lines; } } // namespace // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // // The first four parameters are the expressions used in the assertion // and their values, as strings. For example, for ASSERT_EQ(foo, bar) // where foo is 5 and bar is 6, we have: // // lhs_expression: "foo" // rhs_expression: "bar" // lhs_value: "5" // rhs_value: "6" // // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string "Ignoring case" will // be inserted into the message. AssertionResult EqFailure(const char* lhs_expression, const char* rhs_expression, const std::string& lhs_value, const std::string& rhs_value, bool ignoring_case) { Message msg; msg << "Expected equality of these values:"; msg << "\n " << lhs_expression; if (lhs_value != lhs_expression) { msg << "\n Which is: " << lhs_value; } msg << "\n " << rhs_expression; if (rhs_value != rhs_expression) { msg << "\n Which is: " << rhs_value; } if (ignoring_case) { msg << "\nIgnoring case"; } if (!lhs_value.empty() && !rhs_value.empty()) { const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value); const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value); if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { msg << "\nWith diff:\n" << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); } } return AssertionFailure() << msg; } // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. std::string GetBoolAssertionFailureMessage( const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; msg << "Value of: " << expression_text << "\n Actual: " << actual_predicate_value; if (actual_message[0] != '\0') msg << " (" << actual_message << ")"; msg << "\nExpected: " << expected_predicate_value; return msg.GetString(); } // Helper function for implementing ASSERT_NEAR. AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error) { const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" << expr1 << " evaluates to " << val1 << ",\n" << expr2 << " evaluates to " << val2 << ", and\n" << abs_error_expr << " evaluates to " << abs_error << "."; } // Helper template for implementing FloatLE() and DoubleLE(). template <typename RawType> AssertionResult FloatingPointLE(const char* expr1, const char* expr2, RawType val1, RawType val2) { // Returns success if val1 is less than val2, if (val1 < val2) { return AssertionSuccess(); } // or if val1 is almost equal to val2. const FloatingPoint<RawType> lhs(val1), rhs(val2); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } // Note that the above two checks will both fail if either val1 or // val2 is NaN, as the IEEE floating-point standard requires that // any predicate involving a NaN must return false. ::std::stringstream val1_ss; val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val1; ::std::stringstream val2_ss; val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val2; return AssertionFailure() << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" << " Actual: " << StringStreamToString(&val1_ss) << " vs " << StringStreamToString(&val2_ss); } } // namespace internal // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2) { return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); } // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2) { return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); } namespace internal { // The helper function for {ASSERT|EXPECT}_EQ with int or enum // arguments. AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { if (lhs == rhs) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, FormatForComparisonFailureMessage(lhs, rhs), FormatForComparisonFailureMessage(rhs, lhs), false); } // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here // just to avoid copy-and-paste of similar code. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ BiggestInt val1, BiggestInt val2) {\ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ return AssertionFailure() \ << "Expected: (" << expr1 << ") " #op " (" << expr2\ << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ << " vs " << FormatForComparisonFailureMessage(val2, val1);\ }\ } // Implements the helper function for {ASSERT|EXPECT}_NE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(NE, !=) // Implements the helper function for {ASSERT|EXPECT}_LE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(LE, <=) // Implements the helper function for {ASSERT|EXPECT}_LT with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(LT, < ) // Implements the helper function for {ASSERT|EXPECT}_GE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GE, >=) // Implements the helper function for {ASSERT|EXPECT}_GT with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GT, > ) #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), true); } // The helper function for {ASSERT|EXPECT}_STRNE. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } // The helper function for {ASSERT|EXPECT}_STRCASENE. AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } } // namespace internal namespace { // Helper functions for implementing IsSubString() and IsNotSubstring(). // This group of overloaded functions return true iff needle is a // substring of haystack. NULL is considered a substring of itself // only. bool IsSubstringPred(const char* needle, const char* haystack) { if (needle == nullptr || haystack == nullptr) return needle == haystack; return strstr(haystack, needle) != nullptr; } bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { if (needle == nullptr || haystack == nullptr) return needle == haystack; return wcsstr(haystack, needle) != nullptr; } // StringType here can be either ::std::string or ::std::wstring. template <typename StringType> bool IsSubstringPred(const StringType& needle, const StringType& haystack) { return haystack.find(needle) != StringType::npos; } // This function implements either IsSubstring() or IsNotSubstring(), // depending on the value of the expected_to_be_substring parameter. // StringType here can be const char*, const wchar_t*, ::std::string, // or ::std::wstring. template <typename StringType> AssertionResult IsSubstringImpl( bool expected_to_be_substring, const char* needle_expr, const char* haystack_expr, const StringType& needle, const StringType& haystack) { if (IsSubstringPred(needle, haystack) == expected_to_be_substring) return AssertionSuccess(); const bool is_wide_string = sizeof(needle[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; return AssertionFailure() << "Value of: " << needle_expr << "\n" << " Actual: " << begin_string_quote << needle << "\"\n" << "Expected: " << (expected_to_be_substring ? "" : "not ") << "a substring of " << haystack_expr << "\n" << "Which is: " << begin_string_quote << haystack << "\""; } } // namespace // IsSubstring() and IsNotSubstring() check whether needle is a // substring of haystack (NULL is considered a substring of itself // only), and return an appropriate error message when they fail. AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #if GTEST_HAS_STD_WSTRING AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #endif // GTEST_HAS_STD_WSTRING namespace internal { #if GTEST_OS_WINDOWS namespace { // Helper function for IsHRESULT{SuccessFailure} predicates AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE // Windows CE doesn't support FormatMessage. const char error_text[] = ""; # else // Looks up the human-readable system message for the HRESULT code // and since we're not passing any params to FormatMessage, we don't // want inserts expanded. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; // Gets the system's human readable message string for this HRESULT. char error_text[kBufSize] = { '\0' }; DWORD message_length = ::FormatMessageA(kFlags, 0, // no source, we're asking system hr, // the error 0, // no line width restrictions error_text, // output buffer kBufSize, // buf size nullptr); // no arguments for inserts // Trims tailing white space (FormatMessage leaves a trailing CR-LF) for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; } # endif // GTEST_OS_WINDOWS_MOBILE const std::string error_hex("0x" + String::FormatHexInt(hr)); return ::testing::AssertionFailure() << "Expected: " << expr << " " << expected << ".\n" << " Actual: " << error_hex << " " << error_text << "\n"; } } // namespace AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT if (SUCCEEDED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "succeeds", hr); } AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT if (FAILED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "fails", hr); } #endif // GTEST_OS_WINDOWS // Utility functions for encoding Unicode text (wide strings) in // UTF-8. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8 // like this: // // Code-point length Encoding // 0 - 7 bits 0xxxxxxx // 8 - 11 bits 110xxxxx 10xxxxxx // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1; // The maximum code-point a two-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1; // The maximum code-point a three-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1; // The maximum code-point a four-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1; // Chops off the n lowest bits from a bit pattern. Returns the n // lowest bits. As a side effect, the original bit pattern will be // shifted to the right by n bits. inline UInt32 ChopLowBits(UInt32* bits, int n) { const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1); *bits >>= n; return low_bits; } // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". std::string CodePointToUtf8(UInt32 code_point) { if (code_point > kMaxCodePoint4) { return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; } char str[5]; // Big enough for the largest valid code point. if (code_point <= kMaxCodePoint1) { str[1] = '\0'; str[0] = static_cast<char>(code_point); // 0xxxxxxx } else if (code_point <= kMaxCodePoint2) { str[2] = '\0'; str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx } else if (code_point <= kMaxCodePoint3) { str[3] = '\0'; str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx } else { // code_point <= kMaxCodePoint4 str[4] = '\0'; str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx } return str; } // The following two functions only make sense if the system // uses UTF-16 for wide string encoding. All supported systems // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16. // Determines if the arguments constitute UTF-16 surrogate pair // and thus should be combined into a single Unicode code point // using CreateCodePointFromUtf16SurrogatePair. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; } // Creates a Unicode code point from UTF16 surrogate pair. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second) { const UInt32 mask = (1 << 10) - 1; return (sizeof(wchar_t) == 2) ? (((first & mask) << 10) | (second & mask)) + 0x10000 : // This function should not be called when the condition is // false, but we provide a sensible default in case it is. static_cast<UInt32>(first); } // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. std::string WideStringToUtf8(const wchar_t* str, int num_chars) { if (num_chars == -1) num_chars = static_cast<int>(wcslen(str)); ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { UInt32 unicode_code_point; if (str[i] == L'\0') { break; } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); i++; } else { unicode_code_point = static_cast<UInt32>(str[i]); } stream << CodePointToUtf8(unicode_code_point); } return StringStreamToString(&stream); } // Converts a wide C string to an std::string using the UTF-8 encoding. // NULL will be converted to "(null)". std::string String::ShowWideCString(const wchar_t * wide_c_str) { if (wide_c_str == nullptr) return "(null)"; return internal::WideStringToUtf8(wide_c_str, -1); } // Compares two wide C strings. Returns true iff they have the same // content. // // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; return wcscmp(lhs, rhs) == 0; } // Helper function for *_STREQ on wide strings. AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const wchar_t* lhs, const wchar_t* rhs) { if (String::WideCStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } // Helper function for *_STRNE on wide strings. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { if (!String::WideCStringEquals(s1, s2)) { return AssertionSuccess(); } return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2); } // Compares two C strings, ignoring case. Returns true iff they have // the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; return posix::StrCaseCmp(lhs, rhs) == 0; } // Compares two wide C strings, ignoring case. Returns true iff they // have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, // including the empty string. // NB: The implementations on different platforms slightly differ. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE // environment variable. On GNU platform this method uses wcscasecmp // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; #if GTEST_OS_WINDOWS return _wcsicmp(lhs, rhs) == 0; #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID return wcscasecmp(lhs, rhs) == 0; #else // Android, Mac OS X and Cygwin don't define wcscasecmp. // Other unknown OSes may not define it either. wint_t left, right; do { left = towlower(*lhs++); right = towlower(*rhs++); } while (left && left == right); return left == right; #endif // OS selector } // Returns true iff str ends with the given suffix, ignoring case. // Any string is considered to end with an empty suffix. bool String::EndsWithCaseInsensitive( const std::string& str, const std::string& suffix) { const size_t str_len = str.length(); const size_t suffix_len = suffix.length(); return (str_len >= suffix_len) && CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, suffix.c_str()); } // Formats an int value as "%02d". std::string String::FormatIntWidth2(int value) { std::stringstream ss; ss << std::setfill('0') << std::setw(2) << value; return ss.str(); } // Formats an int value as "%X". std::string String::FormatHexInt(int value) { std::stringstream ss; ss << std::hex << std::uppercase << value; return ss.str(); } // Formats a byte as "%02X". std::string String::FormatByte(unsigned char value) { std::stringstream ss; ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase << static_cast<unsigned int>(value); return ss.str(); } // Converts the buffer in a stringstream to an std::string, converting NUL // bytes to "\\0" along the way. std::string StringStreamToString(::std::stringstream* ss) { const ::std::string& str = ss->str(); const char* const start = str.c_str(); const char* const end = start + str.length(); std::string result; result.reserve(2 * (end - start)); for (const char* ch = start; ch != end; ++ch) { if (*ch == '\0') { result += "\\0"; // Replaces NUL with "\\0"; } else { result += *ch; } } return result; } // Appends the user-supplied message to the Google-Test-generated message. std::string AppendUserMessage(const std::string& gtest_msg, const Message& user_msg) { // Appends the user message if it's non-empty. const std::string user_msg_string = user_msg.GetString(); if (user_msg_string.empty()) { return gtest_msg; } return gtest_msg + "\n" + user_msg_string; } } // namespace internal // class TestResult // Creates an empty TestResult. TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) { } // D'tor. TestResult::~TestResult() { } // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(i); } // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { if (i < 0 || i >= test_property_count()) internal::posix::Abort(); return test_properties_.at(i); } // Clears the test part results. void TestResult::ClearTestPartResults() { test_part_results_.clear(); } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { test_part_results_.push_back(test_part_result); } // Adds a test property to the list. If a property with the same key as the // supplied property is already represented, the value of this test_property // replaces the old value for that key. void TestResult::RecordProperty(const std::string& xml_element, const TestProperty& test_property) { if (!ValidateTestProperty(xml_element, test_property)) { return; } internal::MutexLock lock(&test_properites_mutex_); const std::vector<TestProperty>::iterator property_with_matching_key = std::find_if(test_properties_.begin(), test_properties_.end(), internal::TestPropertyKeyIs(test_property.key())); if (property_with_matching_key == test_properties_.end()) { test_properties_.push_back(test_property); return; } property_with_matching_key->SetValue(test_property.value()); } // The list of reserved attributes used in the <testsuites> element of XML // output. static const char* const kReservedTestSuitesAttributes[] = { "disabled", "errors", "failures", "name", "random_seed", "tests", "time", "timestamp" }; // The list of reserved attributes used in the <testsuite> element of XML // output. static const char* const kReservedTestSuiteAttributes[] = { "disabled", "errors", "failures", "name", "tests", "time" }; // The list of reserved attributes used in the <testcase> element of XML output. static const char* const kReservedTestCaseAttributes[] = { "classname", "name", "status", "time", "type_param", "value_param", "file", "line"}; // Use a slightly different set for allowed output to ensure existing tests can // still RecordProperty("result") static const char* const kReservedOutputTestCaseAttributes[] = { "classname", "name", "status", "time", "type_param", "value_param", "file", "line", "result"}; template <int kSize> std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) { return std::vector<std::string>(array, array + kSize); } static std::vector<std::string> GetReservedAttributesForElement( const std::string& xml_element) { if (xml_element == "testsuites") { return ArrayAsVector(kReservedTestSuitesAttributes); } else if (xml_element == "testsuite") { return ArrayAsVector(kReservedTestSuiteAttributes); } else if (xml_element == "testcase") { return ArrayAsVector(kReservedTestCaseAttributes); } else { GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; } // This code is unreachable but some compilers may not realizes that. return std::vector<std::string>(); } // TODO(jdesprez): Merge the two getReserved attributes once skip is improved static std::vector<std::string> GetReservedOutputAttributesForElement( const std::string& xml_element) { if (xml_element == "testsuites") { return ArrayAsVector(kReservedTestSuitesAttributes); } else if (xml_element == "testsuite") { return ArrayAsVector(kReservedTestSuiteAttributes); } else if (xml_element == "testcase") { return ArrayAsVector(kReservedOutputTestCaseAttributes); } else { GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; } // This code is unreachable but some compilers may not realizes that. return std::vector<std::string>(); } static std::string FormatWordList(const std::vector<std::string>& words) { Message word_list; for (size_t i = 0; i < words.size(); ++i) { if (i > 0 && words.size() > 2) { word_list << ", "; } if (i == words.size() - 1) { word_list << "and "; } word_list << "'" << words[i] << "'"; } return word_list.GetString(); } static bool ValidateTestPropertyName( const std::string& property_name, const std::vector<std::string>& reserved_names) { if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != reserved_names.end()) { ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name << " (" << FormatWordList(reserved_names) << " are reserved by " << GTEST_NAME_ << ")"; return false; } return true; } // Adds a failure if the key is a reserved attribute of the element named // xml_element. Returns true if the property is valid. bool TestResult::ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property) { return ValidateTestPropertyName(test_property.key(), GetReservedAttributesForElement(xml_element)); } // Clears the object. void TestResult::Clear() { test_part_results_.clear(); test_properties_.clear(); death_test_count_ = 0; elapsed_time_ = 0; } // Returns true off the test part was skipped. static bool TestPartSkipped(const TestPartResult& result) { return result.skipped(); } // Returns true iff the test was skipped. bool TestResult::Skipped() const { return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0; } // Returns true iff the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { if (GetTestPartResult(i).failed()) return true; } return false; } // Returns true iff the test part fatally failed. static bool TestPartFatallyFailed(const TestPartResult& result) { return result.fatally_failed(); } // Returns true iff the test fatally failed. bool TestResult::HasFatalFailure() const { return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } // Returns true iff the test part non-fatally failed. static bool TestPartNonfatallyFailed(const TestPartResult& result) { return result.nonfatally_failed(); } // Returns true iff the test has a non-fatal failure. bool TestResult::HasNonfatalFailure() const { return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int TestResult::total_part_count() const { return static_cast<int>(test_part_results_.size()); } // Returns the number of the test properties. int TestResult::test_property_count() const { return static_cast<int>(test_properties_.size()); } // class Test // Creates a Test object. // The c'tor saves the states of all flags. Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { } // The d'tor restores the states of all flags. The actual work is // done by the d'tor of the gtest_flag_saver_ field, and thus not // visible here. Test::~Test() { } // Sets up the test fixture. // // A sub-class may override this. void Test::SetUp() { } // Tears down the test fixture. // // A sub-class may override this. void Test::TearDown() { } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, const std::string& value) { UnitTest::GetInstance()->RecordProperty(key, value); } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, int value) { Message value_message; value_message << value; RecordProperty(key, value_message.GetString().c_str()); } namespace internal { void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message) { // This function is a friend of UnitTest and as such has access to // AddTestPartResult. UnitTest::GetInstance()->AddTestPartResult( result_type, nullptr, // No info about the source file where the exception occurred. -1, // We have no info on which line caused the exception. message, ""); // No stack trace, either. } } // namespace internal // Google Test requires all tests in the same test suite to use the same test // fixture class. This function checks if the current test has the // same fixture class as the first test in the current test suite. If // yes, it returns true; otherwise it generates a Google Test failure and // returns false. bool Test::HasSameFixtureClass() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); const TestSuite* const test_suite = impl->current_test_suite(); // Info about the first test in the current test suite. const TestInfo* const first_test_info = test_suite->test_info_list()[0]; const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; const char* const first_test_name = first_test_info->name(); // Info about the current test. const TestInfo* const this_test_info = impl->current_test_info(); const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; const char* const this_test_name = this_test_info->name(); if (this_fixture_id != first_fixture_id) { // Is the first test defined using TEST? const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); // Is this test defined using TEST? const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); if (first_is_TEST || this_is_TEST) { // Both TEST and TEST_F appear in same test suite, which is incorrect. // Tell the user how to fix this. // Gets the name of the TEST and the name of the TEST_F. Note // that first_is_TEST and this_is_TEST cannot both be true, as // the fixture IDs are different for the two tests. const char* const TEST_name = first_is_TEST ? first_test_name : this_test_name; const char* const TEST_F_name = first_is_TEST ? this_test_name : first_test_name; ADD_FAILURE() << "All tests in the same test suite must use the same test fixture\n" << "class, so mixing TEST_F and TEST in the same test suite is\n" << "illegal. In test suite " << this_test_info->test_suite_name() << ",\n" << "test " << TEST_F_name << " is defined using TEST_F but\n" << "test " << TEST_name << " is defined using TEST. You probably\n" << "want to change the TEST to TEST_F or move it to another test\n" << "case."; } else { // Two fixture classes with the same name appear in two different // namespaces, which is not allowed. Tell the user how to fix this. ADD_FAILURE() << "All tests in the same test suite must use the same test fixture\n" << "class. However, in test suite " << this_test_info->test_suite_name() << ",\n" << "you defined test " << first_test_name << " and test " << this_test_name << "\n" << "using two different test fixture classes. This can happen if\n" << "the two classes are from different namespaces or translation\n" << "units and have the same name. You should probably rename one\n" << "of the classes to put the tests into different test suites."; } return false; } return true; } #if GTEST_HAS_SEH // Adds an "exception thrown" fatal failure to the current test. This // function returns its result via an output parameter pointer because VC++ // prohibits creation of objects with destructors on stack in functions // using __try (see error C2712). static std::string* FormatSehExceptionMessage(DWORD exception_code, const char* location) { Message message; message << "SEH exception with code 0x" << std::setbase(16) << exception_code << std::setbase(10) << " thrown in " << location << "."; return new std::string(message.GetString()); } #endif // GTEST_HAS_SEH namespace internal { #if GTEST_HAS_EXCEPTIONS // Adds an "exception thrown" fatal failure to the current test. static std::string FormatCxxExceptionMessage(const char* description, const char* location) { Message message; if (description != nullptr) { message << "C++ exception with description \"" << description << "\""; } else { message << "Unknown C++ exception"; } message << " thrown in " << location << "."; return message.GetString(); } static std::string PrintTestPartResultToString( const TestPartResult& test_part_result); GoogleTestFailureException::GoogleTestFailureException( const TestPartResult& failure) : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} #endif // GTEST_HAS_EXCEPTIONS // We put these helper functions in the internal namespace as IBM's xlC // compiler rejects the code if they were declared static. // Runs the given method and handles SEH exceptions it throws, when // SEH is supported; returns the 0-value for type Result in case of an // SEH exception. (Microsoft compilers cannot handle SEH and C++ // exceptions in the same function. Therefore, we provide a separate // wrapper function for handling SEH exceptions.) template <class T, typename Result> Result HandleSehExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { #if GTEST_HAS_SEH __try { return (object->*method)(); } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT GetExceptionCode())) { // We create the exception message on the heap because VC++ prohibits // creation of objects with destructors on stack in functions using __try // (see error C2712). std::string* exception_message = FormatSehExceptionMessage( GetExceptionCode(), location); internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, *exception_message); delete exception_message; return static_cast<Result>(0); } #else (void)location; return (object->*method)(); #endif // GTEST_HAS_SEH } // Runs the given method and catches and reports C++ and/or SEH-style // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template <class T, typename Result> Result HandleExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { // NOTE: The user code can affect the way in which Google Test handles // exceptions by setting GTEST_FLAG(catch_exceptions), but only before // RUN_ALL_TESTS() starts. It is technically possible to check the flag // after the exception is caught and either report or re-throw the // exception based on the flag's value: // // try { // // Perform the test method. // } catch (...) { // if (GTEST_FLAG(catch_exceptions)) // // Report the exception as failure. // else // throw; // Re-throws the original exception. // } // // However, the purpose of this flag is to allow the program to drop into // the debugger when the exception is thrown. On most platforms, once the // control enters the catch block, the exception origin information is // lost and the debugger will stop the program at the point of the // re-throw in this function -- instead of at the point of the original // throw statement in the code under test. For this reason, we perform // the check early, sacrificing the ability to affect Google Test's // exception handling in the method where the exception is thrown. if (internal::GetUnitTestImpl()->catch_exceptions()) { #if GTEST_HAS_EXCEPTIONS try { return HandleSehExceptionsInMethodIfSupported(object, method, location); } catch (const AssertionException&) { // NOLINT // This failure was reported already. } catch (const internal::GoogleTestFailureException&) { // NOLINT // This exception type can only be thrown by a failed Google // Test assertion with the intention of letting another testing // framework catch it. Therefore we just re-throw it. throw; } catch (const std::exception& e) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(e.what(), location)); } catch (...) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(nullptr, location)); } return static_cast<Result>(0); #else return HandleSehExceptionsInMethodIfSupported(object, method, location); #endif // GTEST_HAS_EXCEPTIONS } else { return (object->*method)(); } } } // namespace internal // Runs the test and updates the test result. void Test::Run() { if (!HasSameFixtureClass()) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); // We will run the test only if SetUp() was successful and didn't call // GTEST_SKIP(). if (!HasFatalFailure() && !IsSkipped()) { impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &Test::TestBody, "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &Test::TearDown, "TearDown()"); } // Returns true iff the current test has a fatal failure. bool Test::HasFatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); } // Returns true iff the current test has a non-fatal failure. bool Test::HasNonfatalFailure() { return internal::GetUnitTestImpl()->current_test_result()-> HasNonfatalFailure(); } // Returns true iff the current test was skipped. bool Test::IsSkipped() { return internal::GetUnitTestImpl()->current_test_result()->Skipped(); } // class TestInfo // Constructs a TestInfo object. It assumes ownership of the test factory // object. TestInfo::TestInfo(const std::string& a_test_suite_name, const std::string& a_name, const char* a_type_param, const char* a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) : test_suite_name_(a_test_suite_name), name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : nullptr), value_param_(a_value_param ? new std::string(a_value_param) : nullptr), location_(a_code_location), fixture_class_id_(fixture_class_id), should_run_(false), is_disabled_(false), matches_filter_(false), factory_(factory), result_() {} // Destructs a TestInfo object. TestInfo::~TestInfo() { delete factory_; } namespace internal { // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // // test_suite_name: name of the test suite // name: name of the test // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param: text representation of the test's value parameter, // or NULL if this is not a value-parameterized test. // code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( const char* test_suite_name, const char* name, const char* type_param, const char* value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = new TestInfo(test_suite_name, name, type_param, value_param, code_location, fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } void ReportInvalidTestSuiteType(const char* test_suite_name, CodeLocation code_location) { Message errors; errors << "Attempted redefinition of test suite " << test_suite_name << ".\n" << "All tests in the same test suite must use the same test fixture\n" << "class. However, in test suite " << test_suite_name << ", you tried\n" << "to define a test using a fixture class different from the one\n" << "used earlier. This can happen if the two fixture classes are\n" << "from different namespaces and have the same name. You should\n" << "probably rename one of the classes to put the tests into different\n" << "test suites."; GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(), code_location.line) << " " << errors.GetString(); } } // namespace internal namespace { // A predicate that checks the test name of a TestInfo against a known // value. // // This is used for implementation of the TestSuite class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // // TestNameIs is copyable. class TestNameIs { public: // Constructor. // // TestNameIs has NO default constructor. explicit TestNameIs(const char* name) : name_(name) {} // Returns true iff the test name of test_info matches name_. bool operator()(const TestInfo * test_info) const { return test_info && test_info->name() == name_; } private: std::string name_; }; } // namespace namespace internal { // This method expands all parameterized tests registered with macros TEST_P // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those. // This will be done just once during the program runtime. void UnitTestImpl::RegisterParameterizedTests() { if (!parameterized_tests_registered_) { parameterized_test_registry_.RegisterTests(); parameterized_tests_registered_ = true; } } } // namespace internal // Creates the test object, runs it, records its result, and then // deletes it. void TestInfo::Run() { if (!should_run_) return; // Tells UnitTest where to store test result. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_info(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); // Notifies the unit test event listeners that a test is about to start. repeater->OnTestStart(*this); const TimeInMillis start = internal::GetTimeInMillis(); impl->os_stack_trace_getter()->UponLeavingGTest(); // Creates the test object. Test* const test = internal::HandleExceptionsInMethodIfSupported( factory_, &internal::TestFactoryBase::CreateTest, "the test fixture's constructor"); // Runs the test if the constructor didn't generate a fatal failure or invoke // GTEST_SKIP(). // Note that the object will not be null if (!Test::HasFatalFailure() && !Test::IsSkipped()) { // This doesn't throw as all user code that can throw are wrapped into // exception handling code. test->Run(); } if (test != nullptr) { // Deletes the test object. impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( test, &Test::DeleteSelf_, "the test fixture's destructor"); } result_.set_elapsed_time(internal::GetTimeInMillis() - start); // Notifies the unit test event listener that a test has just finished. repeater->OnTestEnd(*this); // Tells UnitTest to stop associating assertion results to this // test. impl->set_current_test_info(nullptr); } // class TestSuite // Gets the number of successful tests in this test suite. int TestSuite::successful_test_count() const { return CountIf(test_info_list_, TestPassed); } // Gets the number of successful tests in this test suite. int TestSuite::skipped_test_count() const { return CountIf(test_info_list_, TestSkipped); } // Gets the number of failed tests in this test suite. int TestSuite::failed_test_count() const { return CountIf(test_info_list_, TestFailed); } // Gets the number of disabled tests that will be reported in the XML report. int TestSuite::reportable_disabled_test_count() const { return CountIf(test_info_list_, TestReportableDisabled); } // Gets the number of disabled tests in this test suite. int TestSuite::disabled_test_count() const { return CountIf(test_info_list_, TestDisabled); } // Gets the number of tests to be printed in the XML report. int TestSuite::reportable_test_count() const { return CountIf(test_info_list_, TestReportable); } // Get the number of tests in this test suite that should run. int TestSuite::test_to_run_count() const { return CountIf(test_info_list_, ShouldRunTest); } // Gets the number of all tests. int TestSuite::total_test_count() const { return static_cast<int>(test_info_list_.size()); } // Creates a TestSuite with the given name. // // Arguments: // // name: name of the test suite // a_type_param: the name of the test suite's type parameter, or NULL if // this is not a typed or a type-parameterized test suite. // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite TestSuite::TestSuite(const char* a_name, const char* a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) : name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : nullptr), set_up_tc_(set_up_tc), tear_down_tc_(tear_down_tc), should_run_(false), elapsed_time_(0) {} // Destructor of TestSuite. TestSuite::~TestSuite() { // Deletes every Test in the collection. ForEach(test_info_list_, internal::Delete<TestInfo>); } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* TestSuite::GetTestInfo(int i) const { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? nullptr : test_info_list_[index]; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* TestSuite::GetMutableTestInfo(int i) { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? nullptr : test_info_list_[index]; } // Adds a test to this test suite. Will delete the test upon // destruction of the TestSuite object. void TestSuite::AddTestInfo(TestInfo* test_info) { test_info_list_.push_back(test_info); test_indices_.push_back(static_cast<int>(test_indices_.size())); } // Runs every test in this TestSuite. void TestSuite::Run() { if (!should_run_) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_suite(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); // Call both legacy and the new API repeater->OnTestSuiteStart(*this); // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI repeater->OnTestCaseStart(*this); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()"); const internal::TimeInMillis start = internal::GetTimeInMillis(); for (int i = 0; i < total_test_count(); i++) { GetMutableTestInfo(i)->Run(); } elapsed_time_ = internal::GetTimeInMillis() - start; impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()"); // Call both legacy and the new API repeater->OnTestSuiteEnd(*this); // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI repeater->OnTestCaseEnd(*this); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI impl->set_current_test_suite(nullptr); } // Clears the results of all tests in this test suite. void TestSuite::ClearResult() { ad_hoc_test_result_.Clear(); ForEach(test_info_list_, TestInfo::ClearTestResult); } // Shuffles the tests in this test suite. void TestSuite::ShuffleTests(internal::Random* random) { Shuffle(random, &test_indices_); } // Restores the test order to before the first shuffle. void TestSuite::UnshuffleTests() { for (size_t i = 0; i < test_indices_.size(); i++) { test_indices_[i] = static_cast<int>(i); } } // Formats a countable noun. Depending on its quantity, either the // singular form or the plural form is used. e.g. // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". static std::string FormatCountableNoun(int count, const char * singular_form, const char * plural_form) { return internal::StreamableToString(count) + " " + (count == 1 ? singular_form : plural_form); } // Formats the count of tests. static std::string FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } // Formats the count of test suites. static std::string FormatTestSuiteCount(int test_suite_count) { return FormatCountableNoun(test_suite_count, "test suite", "test suites"); } // Converts a TestPartResult::Type enum to human-friendly string // representation. Both kNonFatalFailure and kFatalFailure are translated // to "Failure", as the user usually doesn't care about the difference // between the two when viewing the test result. static const char * TestPartResultTypeToString(TestPartResult::Type type) { switch (type) { case TestPartResult::kSkip: return "Skipped"; case TestPartResult::kSuccess: return "Success"; case TestPartResult::kNonFatalFailure: case TestPartResult::kFatalFailure: #ifdef _MSC_VER return "error: "; #else return "Failure\n"; #endif default: return "Unknown result type"; } } namespace internal { // Prints a TestPartResult to an std::string. static std::string PrintTestPartResultToString( const TestPartResult& test_part_result) { return (Message() << internal::FormatFileLocation(test_part_result.file_name(), test_part_result.line_number()) << " " << TestPartResultTypeToString(test_part_result.type()) << test_part_result.message()).GetString(); } // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { const std::string& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); // If the test program runs in Visual Studio or a debugger, the // following statements add the test part result message to the Output // window such that the user can double-click on it to jump to the // corresponding source code location; otherwise they do nothing. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // We don't call OutputDebugString*() on Windows Mobile, as printing // to stdout is done by OutputDebugString() there already - we don't // want the same message printed twice. ::OutputDebugStringA(result.c_str()); ::OutputDebugStringA("\n"); #endif } // class PrettyUnitTestResultPrinter #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW // Returns the character attribute for the given color. static WORD GetColorAttribute(GTestColor color) { switch (color) { case COLOR_RED: return FOREGROUND_RED; case COLOR_GREEN: return FOREGROUND_GREEN; case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; default: return 0; } } static int GetBitOffset(WORD color_mask) { if (color_mask == 0) return 0; int bitOffset = 0; while ((color_mask & 1) == 0) { color_mask >>= 1; ++bitOffset; } return bitOffset; } static WORD GetNewColor(GTestColor color, WORD old_color_attrs) { // Let's reuse the BG static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY; static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; const WORD existing_bg = old_color_attrs & background_mask; WORD new_color = GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY; static const int bg_bitOffset = GetBitOffset(background_mask); static const int fg_bitOffset = GetBitOffset(foreground_mask); if (((new_color & background_mask) >> bg_bitOffset) == ((new_color & foreground_mask) >> fg_bitOffset)) { new_color ^= FOREGROUND_INTENSITY; // invert intensity } return new_color; } #else // Returns the ANSI color code for the given color. COLOR_DEFAULT is // an invalid input. static const char* GetAnsiColorCode(GTestColor color) { switch (color) { case COLOR_RED: return "1"; case COLOR_GREEN: return "2"; case COLOR_YELLOW: return "3"; default: return nullptr; } } #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // Returns true iff Google Test should use colors in the output. bool ShouldUseColor(bool stdout_is_tty) { const char* const gtest_color = GTEST_FLAG(color).c_str(); if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW // On Windows the TERM variable is usually not set, but the // console there does support colors. return stdout_is_tty; #else // On non-Windows platforms, we rely on the TERM variable. const char* const term = posix::GetEnv("TERM"); const bool term_supports_color = String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-256color") || String::CStringEquals(term, "screen") || String::CStringEquals(term, "screen-256color") || String::CStringEquals(term, "tmux") || String::CStringEquals(term, "tmux-256color") || String::CStringEquals(term, "rxvt-unicode") || String::CStringEquals(term, "rxvt-unicode-256color") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin"); return stdout_is_tty && term_supports_color; #endif // GTEST_OS_WINDOWS } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || String::CaseInsensitiveCStringEquals(gtest_color, "true") || String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CStringEquals(gtest_color, "1"); // We take "yes", "true", "t", and "1" as meaning "yes". If the // value is neither one of these nor "auto", we treat it as "no" to // be conservative. } // Helpers for printing colored strings to stdout. Note that on Windows, we // cannot simply emit special characters and have the terminal change colors. // This routine must actually emit the characters rather than return a string // that would be colored when printed, as can be done on Linux. void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \ GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT const bool use_color = AlwaysFalse(); #else static const bool in_color_mode = ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); const bool use_color = in_color_mode && (color != COLOR_DEFAULT); #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS if (!use_color) { vprintf(fmt, args); va_end(args); return; } #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. CONSOLE_SCREEN_BUFFER_INFO buffer_info; GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); const WORD old_color_attrs = buffer_info.wAttributes; const WORD new_color = GetNewColor(color, old_color_attrs); // We need to flush the stream buffers into the console before each // SetConsoleTextAttribute call lest it affect the text that is already // printed but has not yet reached the console. fflush(stdout); SetConsoleTextAttribute(stdout_handle, new_color); vprintf(fmt, args); fflush(stdout); // Restores the text color. SetConsoleTextAttribute(stdout_handle, old_color_attrs); #else printf("\033[0;3%sm", GetAnsiColorCode(color)); vprintf(fmt, args); printf("\033[m"); // Resets the terminal to default. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE va_end(args); } // Text printed in Google Test's text output and --gtest_list_tests // output to label the type parameter and value parameter for a test. static const char kTypeParamLabel[] = "TypeParam"; static const char kValueParamLabel[] = "GetParam()"; static void PrintFullTestCommentIfPresent(const TestInfo& test_info) { const char* const type_param = test_info.type_param(); const char* const value_param = test_info.value_param(); if (type_param != nullptr || value_param != nullptr) { printf(", where "); if (type_param != nullptr) { printf("%s = %s", kTypeParamLabel, type_param); if (value_param != nullptr) printf(" and "); } if (value_param != nullptr) { printf("%s = %s", kValueParamLabel, value_param); } } } // This class implements the TestEventListener interface. // // Class PrettyUnitTestResultPrinter is copyable. class PrettyUnitTestResultPrinter : public TestEventListener { public: PrettyUnitTestResultPrinter() {} static void PrintTestName(const char* test_suite, const char* test) { printf("%s.%s", test_suite, test); } // The following methods override what's in the TestEventListener class. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {} void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {} void OnTestCaseStart(const TestSuite& test_suite) override; void OnTestStart(const TestInfo& test_info) override; void OnTestPartResult(const TestPartResult& result) override; void OnTestEnd(const TestInfo& test_info) override; void OnTestCaseEnd(const TestSuite& test_suite) override; void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {} void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {} private: static void PrintFailedTests(const UnitTest& unit_test); static void PrintSkippedTests(const UnitTest& unit_test); }; // Fired before each iteration of tests starts. void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { if (GTEST_FLAG(repeat) != 1) printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); const char* const filter = GTEST_FLAG(filter).c_str(); // Prints the filter if it's not *. This reminds the user that some // tests may be skipped. if (!String::CStringEquals(filter, kUniversalFilter)) { ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter); } if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n", static_cast<int>(shard_index) + 1, internal::posix::GetEnv(kTestTotalShards)); } if (GTEST_FLAG(shuffle)) { ColoredPrintf(COLOR_YELLOW, "Note: Randomizing tests' orders with a seed of %d .\n", unit_test.random_seed()); } ColoredPrintf(COLOR_GREEN, "[==========] "); printf("Running %s from %s.\n", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( const UnitTest& /*unit_test*/) { ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment set-up.\n"); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestSuite& test_suite) { const std::string counts = FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s", counts.c_str(), test_suite.name()); if (test_suite.type_param() == nullptr) { printf("\n"); } else { printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param()); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { ColoredPrintf(COLOR_GREEN, "[ RUN ] "); PrintTestName(test_info.test_suite_name(), test_info.name()); printf("\n"); fflush(stdout); } // Called after an assertion failure. void PrettyUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { switch (result.type()) { // If the test part succeeded, or was skipped, // we don't need to do anything. case TestPartResult::kSkip: case TestPartResult::kSuccess: return; default: // Print failure message from the assertion // (e.g. expected this and got that). PrintTestPartResult(result); fflush(stdout); } } void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { if (test_info.result()->Passed()) { ColoredPrintf(COLOR_GREEN, "[ OK ] "); } else if (test_info.result()->Skipped()) { ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); } else { ColoredPrintf(COLOR_RED, "[ FAILED ] "); } PrintTestName(test_info.test_suite_name(), test_info.name()); if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG(print_time)) { printf(" (%s ms)\n", internal::StreamableToString( test_info.result()->elapsed_time()).c_str()); } else { printf("\n"); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestSuite& test_suite) { if (!GTEST_FLAG(print_time)) return; const std::string counts = FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(), internal::StreamableToString(test_suite.elapsed_time()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( const UnitTest& /*unit_test*/) { ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment tear-down\n"); fflush(stdout); } // Internal helper for printing the list of failed tests. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { const int failed_test_count = unit_test.failed_test_count(); if (failed_test_count == 0) { return; } for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { const TestSuite& test_suite = *unit_test.GetTestSuite(i); if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) { continue; } for (int j = 0; j < test_suite.total_test_count(); ++j) { const TestInfo& test_info = *test_suite.GetTestInfo(j); if (!test_info.should_run() || !test_info.result()->Failed()) { continue; } ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s.%s", test_suite.name(), test_info.name()); PrintFullTestCommentIfPresent(test_info); printf("\n"); } } } // Internal helper for printing the list of skipped tests. void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) { const int skipped_test_count = unit_test.skipped_test_count(); if (skipped_test_count == 0) { return; } for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { const TestSuite& test_suite = *unit_test.GetTestSuite(i); if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) { continue; } for (int j = 0; j < test_suite.total_test_count(); ++j) { const TestInfo& test_info = *test_suite.GetTestInfo(j); if (!test_info.should_run() || !test_info.result()->Skipped()) { continue; } ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); printf("%s.%s", test_suite.name(), test_info.name()); printf("\n"); } } } void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { ColoredPrintf(COLOR_GREEN, "[==========] "); printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); if (GTEST_FLAG(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } printf("\n"); ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); const int skipped_test_count = unit_test.skipped_test_count(); if (skipped_test_count > 0) { ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str()); PrintSkippedTests(unit_test); } int num_failures = unit_test.failed_test_count(); if (!unit_test.Passed()) { const int failed_test_count = unit_test.failed_test_count(); ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); PrintFailedTests(unit_test); printf("\n%2d FAILED %s\n", num_failures, num_failures == 1 ? "TEST" : "TESTS"); } int num_disabled = unit_test.reportable_disabled_test_count(); if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { if (!num_failures) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. } ColoredPrintf(COLOR_YELLOW, " YOU HAVE %d DISABLED %s\n\n", num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); } // Ensure that Google Test output is printed before, e.g., heapchecker output. fflush(stdout); } // End PrettyUnitTestResultPrinter // class TestEventRepeater // // This class forwards events to other event listeners. class TestEventRepeater : public TestEventListener { public: TestEventRepeater() : forwarding_enabled_(true) {} ~TestEventRepeater() override; void Append(TestEventListener *listener); TestEventListener* Release(TestEventListener* listener); // Controls whether events will be forwarded to listeners_. Set to false // in death test child processes. bool forwarding_enabled() const { return forwarding_enabled_; } void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } void OnTestProgramStart(const UnitTest& unit_test) override; void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override; // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI void OnTestCaseStart(const TestSuite& parameter) override; #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI void OnTestSuiteStart(const TestSuite& parameter) override; void OnTestStart(const TestInfo& test_info) override; void OnTestPartResult(const TestPartResult& result) override; void OnTestEnd(const TestInfo& test_info) override; // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI void OnTestCaseEnd(const TestSuite& parameter) override; #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI void OnTestSuiteEnd(const TestSuite& parameter) override; void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override; void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; void OnTestProgramEnd(const UnitTest& unit_test) override; private: // Controls whether events will be forwarded to listeners_. Set to false // in death test child processes. bool forwarding_enabled_; // The list of listeners that receive events. std::vector<TestEventListener*> listeners_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); }; TestEventRepeater::~TestEventRepeater() { ForEach(listeners_, Delete<TestEventListener>); } void TestEventRepeater::Append(TestEventListener *listener) { listeners_.push_back(listener); } TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { listeners_.erase(listeners_.begin() + i); return listener; } } return nullptr; } // Since most methods are very similar, use macros to reduce boilerplate. // This defines a member that forwards the call to all listeners. #define GTEST_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (size_t i = 0; i < listeners_.size(); i++) { \ listeners_[i]->Name(parameter); \ } \ } \ } // This defines a member that forwards the call to all listeners in reverse // order. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ listeners_[i]->Name(parameter); \ } \ } \ } GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite) #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite) GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite) #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite) GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) #undef GTEST_REPEATER_METHOD_ #undef GTEST_REVERSE_REPEATER_METHOD_ void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (size_t i = 0; i < listeners_.size(); i++) { listeners_[i]->OnTestIterationStart(unit_test, iteration); } } } void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { listeners_[i]->OnTestIterationEnd(unit_test, iteration); } } } // End TestEventRepeater // This class generates an XML output file. class XmlUnitTestResultPrinter : public EmptyTestEventListener { public: explicit XmlUnitTestResultPrinter(const char* output_file); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites); // Prints an XML summary of all unit tests. static void PrintXmlTestsList(std::ostream* stream, const std::vector<TestSuite*>& test_suites); private: // Is c a whitespace character that is normalized to a space character // when it appears in an XML attribute value? static bool IsNormalizableWhitespace(char c) { return c == 0x9 || c == 0xA || c == 0xD; } // May c appear in a well-formed XML document? static bool IsValidXmlCharacter(char c) { return IsNormalizableWhitespace(c) || c >= 0x20; } // Returns an XML-escaped copy of the input string str. If // is_attribute is true, the text is meant to appear as an attribute // value, and normalizable whitespace is preserved by replacing it // with character references. static std::string EscapeXml(const std::string& str, bool is_attribute); // Returns the given string with all characters invalid in XML removed. static std::string RemoveInvalidXmlCharacters(const std::string& str); // Convenience wrapper around EscapeXml when str is an attribute value. static std::string EscapeXmlAttribute(const std::string& str) { return EscapeXml(str, true); } // Convenience wrapper around EscapeXml when str is not an attribute value. static std::string EscapeXmlText(const char* str) { return EscapeXml(str, false); } // Verifies that the given attribute belongs to the given element and // streams the attribute as XML. static void OutputXmlAttribute(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value); // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. static void OutputXmlCDataSection(::std::ostream* stream, const char* data); // Streams an XML representation of a TestInfo object. static void OutputXmlTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info); // Prints an XML representation of a TestSuite object static void PrintXmlTestSuite(::std::ostream* stream, const TestSuite& test_suite); // Prints an XML summary of unit_test to output stream out. static void PrintXmlUnitTest(::std::ostream* stream, const UnitTest& unit_test); // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. // When the std::string is not empty, it includes a space at the beginning, // to delimit this attribute from prior attributes. static std::string TestPropertiesAsXmlAttributes(const TestResult& result); // Streams an XML representation of the test properties of a TestResult // object. static void OutputXmlTestProperties(std::ostream* stream, const TestResult& result); // The output file. const std::string output_file_; GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); }; // Creates a new XmlUnitTestResultPrinter. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) : output_file_(output_file) { if (output_file_.empty()) { GTEST_LOG_(FATAL) << "XML output file may not be null"; } } // Called after the unit test ends. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { FILE* xmlout = OpenFileForWriting(output_file_); std::stringstream stream; PrintXmlUnitTest(&stream, unit_test); fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); fclose(xmlout); } void XmlUnitTestResultPrinter::ListTestsMatchingFilter( const std::vector<TestSuite*>& test_suites) { FILE* xmlout = OpenFileForWriting(output_file_); std::stringstream stream; PrintXmlTestsList(&stream, test_suites); fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); fclose(xmlout); } // Returns an XML-escaped copy of the input string str. If is_attribute // is true, the text is meant to appear as an attribute value, and // normalizable whitespace is preserved by replacing it with character // references. // // Invalid XML characters in str, if any, are stripped from the output. // It is expected that most, if not all, of the text processed by this // module will consist of ordinary English text. // If this module is ever modified to produce version 1.1 XML output, // most invalid characters can be retained using character references. std::string XmlUnitTestResultPrinter::EscapeXml( const std::string& str, bool is_attribute) { Message m; for (size_t i = 0; i < str.size(); ++i) { const char ch = str[i]; switch (ch) { case '<': m << "&lt;"; break; case '>': m << "&gt;"; break; case '&': m << "&amp;"; break; case '\'': if (is_attribute) m << "&apos;"; else m << '\''; break; case '"': if (is_attribute) m << "&quot;"; else m << '"'; break; default: if (IsValidXmlCharacter(ch)) { if (is_attribute && IsNormalizableWhitespace(ch)) m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch)) << ";"; else m << ch; } break; } } return m.GetString(); } // Returns the given string with all characters invalid in XML removed. // Currently invalid characters are dropped from the string. An // alternative is to replace them with certain characters such as . or ?. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( const std::string& str) { std::string output; output.reserve(str.size()); for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) if (IsValidXmlCharacter(*it)) output.push_back(*it); return output; } // The following routines generate an XML representation of a UnitTest // object. // GOOGLETEST_CM0009 DO NOT DELETE // // This is how Google Test concepts map to the DTD: // // <testsuites name="AllTests"> <-- corresponds to a UnitTest object // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object // <testcase name="test-name"> <-- corresponds to a TestInfo object // <failure message="...">...</failure> // <failure message="...">...</failure> // <failure message="...">...</failure> // <-- individual assertion failures // </testcase> // </testsuite> // </testsuites> // Formats the given time in milliseconds as seconds. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { ::std::stringstream ss; ss << (static_cast<double>(ms) * 1e-3); return ss.str(); } static bool PortableLocaltime(time_t seconds, struct tm* out) { #if defined(_MSC_VER) return localtime_s(out, &seconds) == 0; #elif defined(__MINGW32__) || defined(__MINGW64__) // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses // Windows' localtime(), which has a thread-local tm buffer. struct tm* tm_ptr = localtime(&seconds); // NOLINT if (tm_ptr == nullptr) return false; *out = *tm_ptr; return true; #else return localtime_r(&seconds, out) != nullptr; #endif } // Converts the given epoch time in milliseconds to a date string in the ISO // 8601 format, without the timezone information. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { struct tm time_struct; if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) return ""; // YYYY-MM-DDThh:mm:ss return StreamableToString(time_struct.tm_year + 1900) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_sec); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, const char* data) { const char* segment = data; *stream << "<![CDATA["; for (;;) { const char* const next_segment = strstr(segment, "]]>"); if (next_segment != nullptr) { stream->write( segment, static_cast<std::streamsize>(next_segment - segment)); *stream << "]]>]]&gt;<![CDATA["; segment = next_segment + strlen("]]>"); } else { *stream << segment; break; } } *stream << "]]>"; } void XmlUnitTestResultPrinter::OutputXmlAttribute( std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) << "Attribute " << name << " is not allowed for element <" << element_name << ">."; *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; } // Prints an XML representation of a TestInfo object. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); const std::string kTestsuite = "testcase"; if (test_info.is_in_another_shard()) { return; } *stream << " <testcase"; OutputXmlAttribute(stream, kTestsuite, "name", test_info.name()); if (test_info.value_param() != nullptr) { OutputXmlAttribute(stream, kTestsuite, "value_param", test_info.value_param()); } if (test_info.type_param() != nullptr) { OutputXmlAttribute(stream, kTestsuite, "type_param", test_info.type_param()); } if (GTEST_FLAG(list_tests)) { OutputXmlAttribute(stream, kTestsuite, "file", test_info.file()); OutputXmlAttribute(stream, kTestsuite, "line", StreamableToString(test_info.line())); *stream << " />\n"; return; } OutputXmlAttribute(stream, kTestsuite, "status", test_info.should_run() ? "run" : "notrun"); OutputXmlAttribute(stream, kTestsuite, "result", test_info.should_run() ? (result.Skipped() ? "skipped" : "completed") : "suppressed"); OutputXmlAttribute(stream, kTestsuite, "time", FormatTimeInMillisAsSeconds(result.elapsed_time())); OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name); int failures = 0; for (int i = 0; i < result.total_part_count(); ++i) { const TestPartResult& part = result.GetTestPartResult(i); if (part.failed()) { if (++failures == 1) { *stream << ">\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string summary = location + "\n" + part.summary(); *stream << " <failure message=\"" << EscapeXmlAttribute(summary.c_str()) << "\" type=\"\">"; const std::string detail = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); *stream << "</failure>\n"; } } if (failures == 0 && result.test_property_count() == 0) { *stream << " />\n"; } else { if (failures == 0) { *stream << ">\n"; } OutputXmlTestProperties(stream, result); *stream << " </testcase>\n"; } } // Prints an XML representation of a TestSuite object void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream, const TestSuite& test_suite) { const std::string kTestsuite = "testsuite"; *stream << " <" << kTestsuite; OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name()); OutputXmlAttribute(stream, kTestsuite, "tests", StreamableToString(test_suite.reportable_test_count())); if (!GTEST_FLAG(list_tests)) { OutputXmlAttribute(stream, kTestsuite, "failures", StreamableToString(test_suite.failed_test_count())); OutputXmlAttribute( stream, kTestsuite, "disabled", StreamableToString(test_suite.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuite, "errors", "0"); OutputXmlAttribute(stream, kTestsuite, "time", FormatTimeInMillisAsSeconds(test_suite.elapsed_time())); *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result()); } *stream << ">\n"; for (int i = 0; i < test_suite.total_test_count(); ++i) { if (test_suite.GetTestInfo(i)->is_reportable()) OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); } *stream << " </" << kTestsuite << ">\n"; } // Prints an XML summary of unit_test to output stream out. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, const UnitTest& unit_test) { const std::string kTestsuites = "testsuites"; *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; *stream << "<" << kTestsuites; OutputXmlAttribute(stream, kTestsuites, "tests", StreamableToString(unit_test.reportable_test_count())); OutputXmlAttribute(stream, kTestsuites, "failures", StreamableToString(unit_test.failed_test_count())); OutputXmlAttribute( stream, kTestsuites, "disabled", StreamableToString(unit_test.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuites, "errors", "0"); OutputXmlAttribute( stream, kTestsuites, "timestamp", FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); OutputXmlAttribute(stream, kTestsuites, "time", FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); if (GTEST_FLAG(shuffle)) { OutputXmlAttribute(stream, kTestsuites, "random_seed", StreamableToString(unit_test.random_seed())); } *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); *stream << ">\n"; for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i)); } *stream << "</" << kTestsuites << ">\n"; } void XmlUnitTestResultPrinter::PrintXmlTestsList( std::ostream* stream, const std::vector<TestSuite*>& test_suites) { const std::string kTestsuites = "testsuites"; *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; *stream << "<" << kTestsuites; int total_tests = 0; for (auto test_suite : test_suites) { total_tests += test_suite->total_test_count(); } OutputXmlAttribute(stream, kTestsuites, "tests", StreamableToString(total_tests)); OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); *stream << ">\n"; for (auto test_suite : test_suites) { PrintXmlTestSuite(stream, *test_suite); } *stream << "</" << kTestsuites << ">\n"; } // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( const TestResult& result) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << " " << property.key() << "=" << "\"" << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } void XmlUnitTestResultPrinter::OutputXmlTestProperties( std::ostream* stream, const TestResult& result) { const std::string kProperties = "properties"; const std::string kProperty = "property"; if (result.test_property_count() <= 0) { return; } *stream << "<" << kProperties << ">\n"; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); *stream << "<" << kProperty; *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\""; *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\""; *stream << "/>\n"; } *stream << "</" << kProperties << ">\n"; } // End XmlUnitTestResultPrinter // This class generates an JSON output file. class JsonUnitTestResultPrinter : public EmptyTestEventListener { public: explicit JsonUnitTestResultPrinter(const char* output_file); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; // Prints an JSON summary of all unit tests. static void PrintJsonTestList(::std::ostream* stream, const std::vector<TestSuite*>& test_suites); private: // Returns an JSON-escaped copy of the input string str. static std::string EscapeJson(const std::string& str); //// Verifies that the given attribute belongs to the given element and //// streams the attribute as JSON. static void OutputJsonKey(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value, const std::string& indent, bool comma = true); static void OutputJsonKey(std::ostream* stream, const std::string& element_name, const std::string& name, int value, const std::string& indent, bool comma = true); // Streams a JSON representation of a TestInfo object. static void OutputJsonTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info); // Prints a JSON representation of a TestSuite object static void PrintJsonTestSuite(::std::ostream* stream, const TestSuite& test_suite); // Prints a JSON summary of unit_test to output stream out. static void PrintJsonUnitTest(::std::ostream* stream, const UnitTest& unit_test); // Produces a string representing the test properties in a result as // a JSON dictionary. static std::string TestPropertiesAsJson(const TestResult& result, const std::string& indent); // The output file. const std::string output_file_; GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter); }; // Creates a new JsonUnitTestResultPrinter. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file) : output_file_(output_file) { if (output_file_.empty()) { GTEST_LOG_(FATAL) << "JSON output file may not be null"; } } void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { FILE* jsonout = OpenFileForWriting(output_file_); std::stringstream stream; PrintJsonUnitTest(&stream, unit_test); fprintf(jsonout, "%s", StringStreamToString(&stream).c_str()); fclose(jsonout); } // Returns an JSON-escaped copy of the input string str. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) { Message m; for (size_t i = 0; i < str.size(); ++i) { const char ch = str[i]; switch (ch) { case '\\': case '"': case '/': m << '\\' << ch; break; case '\b': m << "\\b"; break; case '\t': m << "\\t"; break; case '\n': m << "\\n"; break; case '\f': m << "\\f"; break; case '\r': m << "\\r"; break; default: if (ch < ' ') { m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch)); } else { m << ch; } break; } } return m.GetString(); } // The following routines generate an JSON representation of a UnitTest // object. // Formats the given time in milliseconds as seconds. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) { ::std::stringstream ss; ss << (static_cast<double>(ms) * 1e-3) << "s"; return ss.str(); } // Converts the given epoch time in milliseconds to a date string in the // RFC3339 format, without the timezone information. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { struct tm time_struct; if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) return ""; // YYYY-MM-DDThh:mm:ss return StreamableToString(time_struct.tm_year + 1900) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_sec) + "Z"; } static inline std::string Indent(int width) { return std::string(width, ' '); } void JsonUnitTestResultPrinter::OutputJsonKey( std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value, const std::string& indent, bool comma) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) << "Key \"" << name << "\" is not allowed for value \"" << element_name << "\"."; *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\""; if (comma) *stream << ",\n"; } void JsonUnitTestResultPrinter::OutputJsonKey( std::ostream* stream, const std::string& element_name, const std::string& name, int value, const std::string& indent, bool comma) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) << "Key \"" << name << "\" is not allowed for value \"" << element_name << "\"."; *stream << indent << "\"" << name << "\": " << StreamableToString(value); if (comma) *stream << ",\n"; } // Prints a JSON representation of a TestInfo object. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); const std::string kTestsuite = "testcase"; const std::string kIndent = Indent(10); *stream << Indent(8) << "{\n"; OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent); if (test_info.value_param() != nullptr) { OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(), kIndent); } if (test_info.type_param() != nullptr) { OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), kIndent); } if (GTEST_FLAG(list_tests)) { OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); *stream << "\n" << Indent(8) << "}"; return; } OutputJsonKey(stream, kTestsuite, "status", test_info.should_run() ? "RUN" : "NOTRUN", kIndent); OutputJsonKey(stream, kTestsuite, "result", test_info.should_run() ? (result.Skipped() ? "SKIPPED" : "COMPLETED") : "SUPPRESSED", kIndent); OutputJsonKey(stream, kTestsuite, "time", FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent); OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent, false); *stream << TestPropertiesAsJson(result, kIndent); int failures = 0; for (int i = 0; i < result.total_part_count(); ++i) { const TestPartResult& part = result.GetTestPartResult(i); if (part.failed()) { *stream << ",\n"; if (++failures == 1) { *stream << kIndent << "\"" << "failures" << "\": [\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string message = EscapeJson(location + "\n" + part.message()); *stream << kIndent << " {\n" << kIndent << " \"failure\": \"" << message << "\",\n" << kIndent << " \"type\": \"\"\n" << kIndent << " }"; } } if (failures > 0) *stream << "\n" << kIndent << "]"; *stream << "\n" << Indent(8) << "}"; } // Prints an JSON representation of a TestSuite object void JsonUnitTestResultPrinter::PrintJsonTestSuite( std::ostream* stream, const TestSuite& test_suite) { const std::string kTestsuite = "testsuite"; const std::string kIndent = Indent(6); *stream << Indent(4) << "{\n"; OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent); OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(), kIndent); if (!GTEST_FLAG(list_tests)) { OutputJsonKey(stream, kTestsuite, "failures", test_suite.failed_test_count(), kIndent); OutputJsonKey(stream, kTestsuite, "disabled", test_suite.reportable_disabled_test_count(), kIndent); OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent); OutputJsonKey(stream, kTestsuite, "time", FormatTimeInMillisAsDuration(test_suite.elapsed_time()), kIndent, false); *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent) << ",\n"; } *stream << kIndent << "\"" << kTestsuite << "\": [\n"; bool comma = false; for (int i = 0; i < test_suite.total_test_count(); ++i) { if (test_suite.GetTestInfo(i)->is_reportable()) { if (comma) { *stream << ",\n"; } else { comma = true; } OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); } } *stream << "\n" << kIndent << "]\n" << Indent(4) << "}"; } // Prints a JSON summary of unit_test to output stream out. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, const UnitTest& unit_test) { const std::string kTestsuites = "testsuites"; const std::string kIndent = Indent(2); *stream << "{\n"; OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(), kIndent); OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(), kIndent); OutputJsonKey(stream, kTestsuites, "disabled", unit_test.reportable_disabled_test_count(), kIndent); OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent); if (GTEST_FLAG(shuffle)) { OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(), kIndent); } OutputJsonKey(stream, kTestsuites, "timestamp", FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()), kIndent); OutputJsonKey(stream, kTestsuites, "time", FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent, false); *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent) << ",\n"; OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); *stream << kIndent << "\"" << kTestsuites << "\": [\n"; bool comma = false; for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) { if (comma) { *stream << ",\n"; } else { comma = true; } PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i)); } } *stream << "\n" << kIndent << "]\n" << "}\n"; } void JsonUnitTestResultPrinter::PrintJsonTestList( std::ostream* stream, const std::vector<TestSuite*>& test_suites) { const std::string kTestsuites = "testsuites"; const std::string kIndent = Indent(2); *stream << "{\n"; int total_tests = 0; for (auto test_suite : test_suites) { total_tests += test_suite->total_test_count(); } OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent); OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); *stream << kIndent << "\"" << kTestsuites << "\": [\n"; for (size_t i = 0; i < test_suites.size(); ++i) { if (i != 0) { *stream << ",\n"; } PrintJsonTestSuite(stream, *test_suites[i]); } *stream << "\n" << kIndent << "]\n" << "}\n"; } // Produces a string representing the test properties in a result as // a JSON dictionary. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( const TestResult& result, const std::string& indent) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << ",\n" << indent << "\"" << property.key() << "\": " << "\"" << EscapeJson(property.value()) << "\""; } return attributes.GetString(); } // End JsonUnitTestResultPrinter #if GTEST_CAN_STREAM_RESULTS_ // Checks if str contains '=', '&', '%' or '\n' characters. If yes, // replaces them by "%xx" where xx is their hexadecimal value. For // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) // in both time and space -- important as the input str may contain an // arbitrarily long test failure message and stack trace. std::string StreamingListener::UrlEncode(const char* str) { std::string result; result.reserve(strlen(str) + 1); for (char ch = *str; ch != '\0'; ch = *++str) { switch (ch) { case '%': case '=': case '&': case '\n': result.append("%" + String::FormatByte(static_cast<unsigned char>(ch))); break; default: result.push_back(ch); break; } } return result; } void StreamingListener::SocketWriter::MakeConnection() { GTEST_CHECK_(sockfd_ == -1) << "MakeConnection() can't be called when there is already a connection."; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. hints.ai_socktype = SOCK_STREAM; addrinfo* servinfo = nullptr; // Use the getaddrinfo() to get a linked list of IP addresses for // the given host name. const int error_num = getaddrinfo( host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); if (error_num != 0) { GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " << gai_strerror(error_num); } // Loop through all the results and connect to the first we can. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr; cur_addr = cur_addr->ai_next) { sockfd_ = socket( cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); if (sockfd_ != -1) { // Connect the client socket to the server socket. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { close(sockfd_); sockfd_ = -1; } } } freeaddrinfo(servinfo); // all done with this structure if (sockfd_ == -1) { GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " << host_name_ << ":" << port_num_; } } // End of class Streaming Listener #endif // GTEST_CAN_STREAM_RESULTS__ // class OsStackTraceGetter const char* const OsStackTraceGetterInterface::kElidedFramesMarker = "... " GTEST_NAME_ " internal frames ..."; std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) GTEST_LOCK_EXCLUDED_(mutex_) { #if GTEST_HAS_ABSL std::string result; if (max_depth <= 0) { return result; } max_depth = std::min(max_depth, kMaxStackTraceDepth); std::vector<void*> raw_stack(max_depth); // Skips the frames requested by the caller, plus this function. const int raw_stack_size = absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1); void* caller_frame = nullptr; { MutexLock lock(&mutex_); caller_frame = caller_frame_; } for (int i = 0; i < raw_stack_size; ++i) { if (raw_stack[i] == caller_frame && !GTEST_FLAG(show_internal_stack_frames)) { // Add a marker to the trace and stop adding frames. absl::StrAppend(&result, kElidedFramesMarker, "\n"); break; } char tmp[1024]; const char* symbol = "(unknown)"; if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) { symbol = tmp; } char line[1024]; snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol); result += line; } return result; #else // !GTEST_HAS_ABSL static_cast<void>(max_depth); static_cast<void>(skip_count); return ""; #endif // GTEST_HAS_ABSL } void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { #if GTEST_HAS_ABSL void* caller_frame = nullptr; if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) { caller_frame = nullptr; } MutexLock lock(&mutex_); caller_frame_ = caller_frame; #endif // GTEST_HAS_ABSL } // A helper class that creates the premature-exit file in its // constructor and deletes the file in its destructor. class ScopedPrematureExitFile { public: explicit ScopedPrematureExitFile(const char* premature_exit_filepath) : premature_exit_filepath_(premature_exit_filepath ? premature_exit_filepath : "") { // If a path to the premature-exit file is specified... if (!premature_exit_filepath_.empty()) { // create the file with a single "0" character in it. I/O // errors are ignored as there's nothing better we can do and we // don't want to fail the test because of this. FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); fwrite("0", 1, 1, pfile); fclose(pfile); } } ~ScopedPrematureExitFile() { if (!premature_exit_filepath_.empty()) { int retval = remove(premature_exit_filepath_.c_str()); if (retval) { GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \"" << premature_exit_filepath_ << "\" with error " << retval; } } } private: const std::string premature_exit_filepath_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); }; } // namespace internal // class TestEventListeners TestEventListeners::TestEventListeners() : repeater_(new internal::TestEventRepeater()), default_result_printer_(nullptr), default_xml_generator_(nullptr) {} TestEventListeners::~TestEventListeners() { delete repeater_; } // Returns the standard listener responsible for the default console // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the user. void TestEventListeners::Append(TestEventListener* listener) { repeater_->Append(listener); } // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns // NULL if the listener is not found in the list. TestEventListener* TestEventListeners::Release(TestEventListener* listener) { if (listener == default_result_printer_) default_result_printer_ = nullptr; else if (listener == default_xml_generator_) default_xml_generator_ = nullptr; return repeater_->Release(listener); } // Returns repeater that broadcasts the TestEventListener events to all // subscribers. TestEventListener* TestEventListeners::repeater() { return repeater_; } // Sets the default_result_printer attribute to the provided listener. // The listener is also added to the listener list and previous // default_result_printer is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { if (default_result_printer_ != listener) { // It is an error to pass this method a listener that is already in the // list. delete Release(default_result_printer_); default_result_printer_ = listener; if (listener != nullptr) Append(listener); } } // Sets the default_xml_generator attribute to the provided listener. The // listener is also added to the listener list and previous // default_xml_generator is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { if (default_xml_generator_ != listener) { // It is an error to pass this method a listener that is already in the // list. delete Release(default_xml_generator_); default_xml_generator_ = listener; if (listener != nullptr) Append(listener); } } // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool TestEventListeners::EventForwardingEnabled() const { return repeater_->forwarding_enabled(); } void TestEventListeners::SuppressEventForwarding() { repeater_->set_forwarding_enabled(false); } // class UnitTest // Gets the singleton UnitTest object. The first time this method is // called, a UnitTest object is constructed and returned. Consecutive // calls will return the same object. // // We don't protect this under mutex_ as a user is not supposed to // call this before main() starts, from which point on the return // value will never change. UnitTest* UnitTest::GetInstance() { // CodeGear C++Builder insists on a public destructor for the // default implementation. Use this implementation to keep good OO // design with private destructor. #if defined(__BORLANDC__) static UnitTest* const instance = new UnitTest; return instance; #else static UnitTest instance; return &instance; #endif // defined(__BORLANDC__) } // Gets the number of successful test suites. int UnitTest::successful_test_suite_count() const { return impl()->successful_test_suite_count(); } // Gets the number of failed test suites. int UnitTest::failed_test_suite_count() const { return impl()->failed_test_suite_count(); } // Gets the number of all test suites. int UnitTest::total_test_suite_count() const { return impl()->total_test_suite_count(); } // Gets the number of all test suites that contain at least one test // that should run. int UnitTest::test_suite_to_run_count() const { return impl()->test_suite_to_run_count(); } // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ int UnitTest::successful_test_case_count() const { return impl()->successful_test_suite_count(); } int UnitTest::failed_test_case_count() const { return impl()->failed_test_suite_count(); } int UnitTest::total_test_case_count() const { return impl()->total_test_suite_count(); } int UnitTest::test_case_to_run_count() const { return impl()->test_suite_to_run_count(); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Gets the number of successful tests. int UnitTest::successful_test_count() const { return impl()->successful_test_count(); } // Gets the number of skipped tests. int UnitTest::skipped_test_count() const { return impl()->skipped_test_count(); } // Gets the number of failed tests. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } // Gets the number of disabled tests that will be reported in the XML report. int UnitTest::reportable_disabled_test_count() const { return impl()->reportable_disabled_test_count(); } // Gets the number of disabled tests. int UnitTest::disabled_test_count() const { return impl()->disabled_test_count(); } // Gets the number of tests to be printed in the XML report. int UnitTest::reportable_test_count() const { return impl()->reportable_test_count(); } // Gets the number of all tests. int UnitTest::total_test_count() const { return impl()->total_test_count(); } // Gets the number of tests that should run. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } // Gets the time of the test program start, in ms from the start of the // UNIX epoch. internal::TimeInMillis UnitTest::start_timestamp() const { return impl()->start_timestamp(); } // Gets the elapsed time, in milliseconds. internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); } // Returns true iff the unit test passed (i.e. all test suites passed). bool UnitTest::Passed() const { return impl()->Passed(); } // Returns true iff the unit test failed (i.e. some test suite failed // or something outside of all tests failed). bool UnitTest::Failed() const { return impl()->Failed(); } // Gets the i-th test suite among all the test suites. i can range from 0 to // total_test_suite_count() - 1. If i is not in that range, returns NULL. const TestSuite* UnitTest::GetTestSuite(int i) const { return impl()->GetTestSuite(i); } // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* UnitTest::GetTestCase(int i) const { return impl()->GetTestCase(i); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Returns the TestResult containing information on test failures and // properties logged outside of individual test suites. const TestResult& UnitTest::ad_hoc_test_result() const { return *impl()->ad_hoc_test_result(); } // Gets the i-th test suite among all the test suites. i can range from 0 to // total_test_suite_count() - 1. If i is not in that range, returns NULL. TestSuite* UnitTest::GetMutableTestSuite(int i) { return impl()->GetMutableSuiteCase(i); } // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in the // order they were registered. After all tests in the program have // finished, all global test environments will be torn-down in the // *reverse* order they were registered. // // The UnitTest object takes ownership of the given environment. // // We don't protect this under mutex_, as we only support calling it // from the main thread. Environment* UnitTest::AddEnvironment(Environment* env) { if (env == nullptr) { return nullptr; } impl_->environments().push_back(env); return env; } // Adds a TestPartResult to the current TestResult object. All Google Test // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. void UnitTest::AddTestPartResult( TestPartResult::Type result_type, const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { Message msg; msg << message; internal::MutexLock lock(&mutex_); if (impl_->gtest_trace_stack().size() > 0) { msg << "\n" << GTEST_NAME_ << " trace:"; for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); i > 0; --i) { const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) << " " << trace.message; } } if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) { msg << internal::kStackTraceMarker << os_stack_trace; } const TestPartResult result = TestPartResult( result_type, file_name, line_number, msg.GetString().c_str()); impl_->GetTestPartResultReporterForCurrentThread()-> ReportTestPartResult(result); if (result_type != TestPartResult::kSuccess && result_type != TestPartResult::kSkip) { // gtest_break_on_failure takes precedence over // gtest_throw_on_failure. This allows a user to set the latter // in the code (perhaps in order to use Google Test assertions // with another testing framework) and specify the former on the // command line for debugging. if (GTEST_FLAG(break_on_failure)) { #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Using DebugBreak on Windows allows gtest to still break into a debugger // when a failure happens and both the --gtest_break_on_failure and // the --gtest_catch_exceptions flags are specified. DebugBreak(); #elif (!defined(__native_client__)) && \ ((defined(__clang__) || defined(__GNUC__)) && \ (defined(__x86_64__) || defined(__i386__))) // with clang/gcc we can achieve the same effect on x86 by invoking int3 asm("int3"); #else // Dereference nullptr through a volatile pointer to prevent the compiler // from removing. We use this rather than abort() or __builtin_trap() for // portability: some debuggers don't correctly trap abort(). *static_cast<volatile int*>(nullptr) = 1; #endif // GTEST_OS_WINDOWS } else if (GTEST_FLAG(throw_on_failure)) { #if GTEST_HAS_EXCEPTIONS throw internal::GoogleTestFailureException(result); #else // We cannot call abort() as it generates a pop-up in debug mode // that cannot be suppressed in VC 7.1 or below. exit(1); #endif } } } // Adds a TestProperty to the current TestResult object when invoked from // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked // from SetUpTestSuite or TearDownTestSuite, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. void UnitTest::RecordProperty(const std::string& key, const std::string& value) { impl_->RecordProperty(TestProperty(key, value)); } // Runs all tests in this UnitTest object and prints the result. // Returns 0 if successful, or 1 otherwise. // // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { const bool in_death_test_child_process = internal::GTEST_FLAG(internal_run_death_test).length() > 0; // Google Test implements this protocol for catching that a test // program exits before returning control to Google Test: // // 1. Upon start, Google Test creates a file whose absolute path // is specified by the environment variable // TEST_PREMATURE_EXIT_FILE. // 2. When Google Test has finished its work, it deletes the file. // // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before // running a Google-Test-based test program and check the existence // of the file at the end of the test execution to see if it has // exited prematurely. // If we are in the child process of a death test, don't // create/delete the premature exit file, as doing so is unnecessary // and will confuse the parent process. Otherwise, create/delete // the file upon entering/leaving this function. If the program // somehow exits before this function has a chance to return, the // premature-exit file will be left undeleted, causing a test runner // that understands the premature-exit-file protocol to report the // test as having failed. const internal::ScopedPrematureExitFile premature_exit_file( in_death_test_child_process ? nullptr : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); // Captures the value of GTEST_FLAG(catch_exceptions). This value will be // used for the duration of the program. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); #if GTEST_OS_WINDOWS // Either the user wants Google Test to catch exceptions thrown by the // tests or this is executing in the context of death test child // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); # endif // !GTEST_OS_WINDOWS_MOBILE # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE // Death test children can be terminated with _abort(). On Windows, // _abort() can show a dialog with a warning message. This forces the // abort message to go to stderr instead. _set_error_mode(_OUT_TO_STDERR); # endif # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program. We need to suppress // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement // executed. Google Test will notify the user of any unexpected // failure via stderr. if (!GTEST_FLAG(break_on_failure)) _set_abort_behavior( 0x0, // Clear the following flags: _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. # endif } #endif // GTEST_OS_WINDOWS return internal::HandleExceptionsInMethodIfSupported( impl(), &internal::UnitTestImpl::RunAllTests, "auxiliary test code (environments or event listeners)") ? 0 : 1; } // Returns the working directory when the first TEST() or TEST_F() was // executed. const char* UnitTest::original_working_dir() const { return impl_->original_working_dir_.c_str(); } // Returns the TestSuite object for the test that's currently running, // or NULL if no test is running. const TestSuite* UnitTest::current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_suite(); } // Legacy API is still available but deprecated #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* UnitTest::current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_suite(); } #endif // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. const TestInfo* UnitTest::current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_info(); } // Returns the random seed used at the start of the current test run. int UnitTest::random_seed() const { return impl_->random_seed(); } // Returns ParameterizedTestSuiteRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestSuiteRegistry& UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { return impl_->parameterized_test_registry(); } // Creates an empty UnitTest. UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); } // Destructor of UnitTest. UnitTest::~UnitTest() { delete impl_; } // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().push_back(trace); } // Pops a trace from the per-thread Google Test trace stack. void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().pop_back(); } namespace internal { UnitTestImpl::UnitTestImpl(UnitTest* parent) : parent_(parent), GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) default_global_test_part_result_reporter_(this), default_per_thread_test_part_result_reporter_(this), GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_( &default_global_test_part_result_reporter_), per_thread_test_part_result_reporter_( &default_per_thread_test_part_result_reporter_), parameterized_test_registry_(), parameterized_tests_registered_(false), last_death_test_suite_(-1), current_test_suite_(nullptr), current_test_info_(nullptr), ad_hoc_test_result_(), os_stack_trace_getter_(nullptr), post_flag_parse_init_performed_(false), random_seed_(0), // Will be overridden by the flag before first use. random_(0), // Will be reseeded before first use. start_timestamp_(0), elapsed_time_(0), #if GTEST_HAS_DEATH_TEST death_test_factory_(new DefaultDeathTestFactory), #endif // Will be overridden by the flag before first use. catch_exceptions_(false) { listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); } UnitTestImpl::~UnitTestImpl() { // Deletes every TestSuite. ForEach(test_suites_, internal::Delete<TestSuite>); // Deletes every Environment. ForEach(environments_, internal::Delete<Environment>); delete os_stack_trace_getter_; } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test, to current test suite's ad_hoc_test_result when invoke // from SetUpTestSuite/TearDownTestSuite, or to the global property set // otherwise. If the result already contains a property with the same key, // the value will be updated. void UnitTestImpl::RecordProperty(const TestProperty& test_property) { std::string xml_element; TestResult* test_result; // TestResult appropriate for property recording. if (current_test_info_ != nullptr) { xml_element = "testcase"; test_result = &(current_test_info_->result_); } else if (current_test_suite_ != nullptr) { xml_element = "testsuite"; test_result = &(current_test_suite_->ad_hoc_test_result_); } else { xml_element = "testsuites"; test_result = &ad_hoc_test_result_; } test_result->RecordProperty(xml_element, test_property); } #if GTEST_HAS_DEATH_TEST // Disables event forwarding if the control is currently in a death test // subprocess. Must not be called before InitGoogleTest. void UnitTestImpl::SuppressTestEventsIfInSubprocess() { if (internal_run_death_test_flag_.get() != nullptr) listeners()->SuppressEventForwarding(); } #endif // GTEST_HAS_DEATH_TEST // Initializes event listeners performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureXmlOutput() { const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml") { listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); } else if (output_format == "json") { listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); } else if (output_format != "") { GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \"" << output_format << "\" ignored."; } } #if GTEST_CAN_STREAM_RESULTS_ // Initializes event listeners for streaming test results in string form. // Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureStreamingOutput() { const std::string& target = GTEST_FLAG(stream_result_to); if (!target.empty()) { const size_t pos = target.find(':'); if (pos != std::string::npos) { listeners()->Append(new StreamingListener(target.substr(0, pos), target.substr(pos+1))); } else { GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target << "\" ignored."; } } } #endif // GTEST_CAN_STREAM_RESULTS_ // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void UnitTestImpl::PostFlagParsingInit() { // Ensures that this function does not execute more than once. if (!post_flag_parse_init_performed_) { post_flag_parse_init_performed_ = true; #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) // Register to send notifications about key process state changes. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) #if GTEST_HAS_DEATH_TEST InitDeathTestSubprocessControlInfo(); SuppressTestEventsIfInSubprocess(); #endif // GTEST_HAS_DEATH_TEST // Registers parameterized tests. This makes parameterized tests // available to the UnitTest reflection API without running // RUN_ALL_TESTS. RegisterParameterizedTests(); // Configures listeners for XML output. This makes it possible for users // to shut down the default XML output before invoking RUN_ALL_TESTS. ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Configures listeners for streaming test results to the specified server. ConfigureStreamingOutput(); #endif // GTEST_CAN_STREAM_RESULTS_ #if GTEST_HAS_ABSL if (GTEST_FLAG(install_failure_signal_handler)) { absl::FailureSignalHandlerOptions options; absl::InstallFailureSignalHandler(options); } #endif // GTEST_HAS_ABSL } } // A predicate that checks the name of a TestSuite against a known // value. // // This is used for implementation of the UnitTest class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // // TestSuiteNameIs is copyable. class TestSuiteNameIs { public: // Constructor. explicit TestSuiteNameIs(const std::string& name) : name_(name) {} // Returns true iff the name of test_suite matches name_. bool operator()(const TestSuite* test_suite) const { return test_suite != nullptr && strcmp(test_suite->name(), name_.c_str()) == 0; } private: std::string name_; }; // Finds and returns a TestSuite with the given name. If one doesn't // exist, creates one and returns it. It's the CALLER'S // RESPONSIBILITY to ensure that this function is only called WHEN THE // TESTS ARE NOT SHUFFLED. // // Arguments: // // test_suite_name: name of the test suite // type_param: the name of the test suite's type parameter, or NULL if // this is not a typed or a type-parameterized test suite. // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite TestSuite* UnitTestImpl::GetTestSuite( const char* test_suite_name, const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) { // Can we find a TestSuite with the given name? const auto test_suite = std::find_if(test_suites_.rbegin(), test_suites_.rend(), TestSuiteNameIs(test_suite_name)); if (test_suite != test_suites_.rend()) return *test_suite; // No. Let's create one. auto* const new_test_suite = new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc); // Is this a death test suite? if (internal::UnitTestOptions::MatchesFilter(test_suite_name, kDeathTestSuiteFilter)) { // Yes. Inserts the test suite after the last death test suite // defined so far. This only works when the test suites haven't // been shuffled. Otherwise we may end up running a death test // after a non-death test. ++last_death_test_suite_; test_suites_.insert(test_suites_.begin() + last_death_test_suite_, new_test_suite); } else { // No. Appends to the end of the list. test_suites_.push_back(new_test_suite); } test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size())); return new_test_suite; } // Helpers for setting up / tearing down the given environment. They // are for use in the ForEach() function. static void SetUpEnvironment(Environment* env) { env->SetUp(); } static void TearDownEnvironment(Environment* env) { env->TearDown(); } // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, the test is considered to be failed, but the // rest of the tests will still be run. // // When parameterized tests are enabled, it expands and registers // parameterized tests first in RegisterParameterizedTests(). // All other functions called from RunAllTests() may safely assume that // parameterized tests are ready to be counted and run. bool UnitTestImpl::RunAllTests() { // True iff Google Test is initialized before RUN_ALL_TESTS() is called. const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); // Do not run any test if the --help flag was specified. if (g_help_flag) return true; // Repeats the call to the post-flag parsing initialization in case the // user didn't call InitGoogleTest. PostFlagParsingInit(); // Even if sharding is not on, test runners may want to use the // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding // protocol. internal::WriteToShardStatusFileIfNeeded(); // True iff we are in a subprocess for running a thread-safe-style // death test. bool in_subprocess_for_death_test = false; #if GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != nullptr); # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) if (in_subprocess_for_death_test) { GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); } # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #endif // GTEST_HAS_DEATH_TEST const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, in_subprocess_for_death_test); // Compares the full test names with the filter to decide which // tests to run. const bool has_tests_to_run = FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL : IGNORE_SHARDING_PROTOCOL) > 0; // Lists the tests and exits if the --gtest_list_tests flag was specified. if (GTEST_FLAG(list_tests)) { // This must be called *after* FilterTests() has been called. ListTestsMatchingFilter(); return true; } random_seed_ = GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; // True iff at least one test has failed. bool failed = false; TestEventListener* repeater = listeners()->repeater(); start_timestamp_ = GetTimeInMillis(); repeater->OnTestProgramStart(*parent_); // How many times to repeat the tests? We don't want to repeat them // when we are inside the subprocess of a death test. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); // Repeats forever if the repeat count is negative. const bool forever = repeat < 0; for (int i = 0; forever || i != repeat; i++) { // We want to preserve failures generated by ad-hoc test // assertions executed before RUN_ALL_TESTS(). ClearNonAdHocTestResult(); const TimeInMillis start = GetTimeInMillis(); // Shuffles test suites and tests if requested. if (has_tests_to_run && GTEST_FLAG(shuffle)) { random()->Reseed(random_seed_); // This should be done before calling OnTestIterationStart(), // such that a test event listener can see the actual test order // in the event. ShuffleTests(); } // Tells the unit test event listeners that the tests are about to start. repeater->OnTestIterationStart(*parent_, i); // Runs each test suite if there is at least one test to run. if (has_tests_to_run) { // Sets up all environments beforehand. repeater->OnEnvironmentsSetUpStart(*parent_); ForEach(environments_, SetUpEnvironment); repeater->OnEnvironmentsSetUpEnd(*parent_); // Runs the tests only if there was no fatal failure or skip triggered // during global set-up. if (Test::IsSkipped()) { // Emit diagnostics when global set-up calls skip, as it will not be // emitted by default. TestResult& test_result = *internal::GetUnitTestImpl()->current_test_result(); for (int j = 0; j < test_result.total_part_count(); ++j) { const TestPartResult& test_part_result = test_result.GetTestPartResult(j); if (test_part_result.type() == TestPartResult::kSkip) { const std::string& result = test_part_result.message(); printf("%s\n", result.c_str()); } } fflush(stdout); } else if (!Test::HasFatalFailure()) { for (int test_index = 0; test_index < total_test_suite_count(); test_index++) { GetMutableSuiteCase(test_index)->Run(); } } // Tears down all environments in reverse order afterwards. repeater->OnEnvironmentsTearDownStart(*parent_); std::for_each(environments_.rbegin(), environments_.rend(), TearDownEnvironment); repeater->OnEnvironmentsTearDownEnd(*parent_); } elapsed_time_ = GetTimeInMillis() - start; // Tells the unit test event listener that the tests have just finished. repeater->OnTestIterationEnd(*parent_, i); // Gets the result and clears it. if (!Passed()) { failed = true; } // Restores the original test order after the iteration. This // allows the user to quickly repro a failure that happens in the // N-th iteration without repeating the first (N - 1) iterations. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in // case the user somehow changes the value of the flag somewhere // (it's always safe to unshuffle the tests). UnshuffleTests(); if (GTEST_FLAG(shuffle)) { // Picks a new random seed for each iteration. random_seed_ = GetNextRandomSeed(random_seed_); } } repeater->OnTestProgramEnd(*parent_); if (!gtest_is_initialized_before_run_all_tests) { ColoredPrintf( COLOR_RED, "\nIMPORTANT NOTICE - DO NOT IGNORE:\n" "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_ "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_ " will start to enforce the valid usage. " "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT #if GTEST_FOR_GOOGLE_ ColoredPrintf(COLOR_RED, "For more details, see http://wiki/Main/ValidGUnitMain.\n"); #endif // GTEST_FOR_GOOGLE_ } return !failed; } // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded() { const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); if (test_shard_file != nullptr) { FILE* const file = posix::FOpen(test_shard_file, "w"); if (file == nullptr) { ColoredPrintf(COLOR_RED, "Could not write to the test shard status file \"%s\" " "specified by the %s environment variable.\n", test_shard_file, kTestShardStatusFile); fflush(stdout); exit(EXIT_FAILURE); } fclose(file); } } // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (i.e., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { if (in_subprocess_for_death_test) { return false; } const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestShardIndex << " = " << shard_index << ", but have left " << kTestTotalShards << " unset.\n"; ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestTotalShards << " = " << total_shards << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { const Message msg = Message() << "Invalid environment variables: we require 0 <= " << kTestShardIndex << " < " << kTestTotalShards << ", but you have " << kTestShardIndex << "=" << shard_index << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } return total_shards > 1; } // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error // and aborts. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { const char* str_val = posix::GetEnv(var); if (str_val == nullptr) { return default_val; } Int32 result; if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) { exit(EXIT_FAILURE); } return result; } // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { return (test_id % total_shards) == shard_index; } // Compares the name of each test with the user-specified filter to // decide whether the test should be run, then records the result in // each TestSuite and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestTotalShards, -1) : -1; const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestShardIndex, -1) : -1; // num_runnable_tests are the number of tests that will // run across all shards (i.e., match filter and are not disabled). // num_selected_tests are the number of tests to be run on // this shard. int num_runnable_tests = 0; int num_selected_tests = 0; for (auto* test_suite : test_suites_) { const std::string& test_suite_name = test_suite->name(); test_suite->set_should_run(false); for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { TestInfo* const test_info = test_suite->test_info_list()[j]; const std::string test_name(test_info->name()); // A test is disabled if test suite name or test name matches // kDisableTestFilter. const bool is_disabled = internal::UnitTestOptions::MatchesFilter( test_suite_name, kDisableTestFilter) || internal::UnitTestOptions::MatchesFilter( test_name, kDisableTestFilter); test_info->is_disabled_ = is_disabled; const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest( test_suite_name, test_name); test_info->matches_filter_ = matches_filter; const bool is_runnable = (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && matches_filter; const bool is_in_another_shard = shard_tests != IGNORE_SHARDING_PROTOCOL && !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests); test_info->is_in_another_shard_ = is_in_another_shard; const bool is_selected = is_runnable && !is_in_another_shard; num_runnable_tests += is_runnable; num_selected_tests += is_selected; test_info->should_run_ = is_selected; test_suite->set_should_run(test_suite->should_run() || is_selected); } } return num_selected_tests; } // Prints the given C-string on a single line by replacing all '\n' // characters with string "\\n". If the output takes more than // max_length characters, only prints the first max_length characters // and "...". static void PrintOnOneLine(const char* str, int max_length) { if (str != nullptr) { for (int i = 0; *str != '\0'; ++str) { if (i >= max_length) { printf("..."); break; } if (*str == '\n') { printf("\\n"); i += 2; } else { printf("%c", *str); ++i; } } } } // Prints the names of the tests matching the user-specified filter flag. void UnitTestImpl::ListTestsMatchingFilter() { // Print at most this many characters for each type/value parameter. const int kMaxParamLength = 250; for (auto* test_suite : test_suites_) { bool printed_test_suite_name = false; for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { const TestInfo* const test_info = test_suite->test_info_list()[j]; if (test_info->matches_filter_) { if (!printed_test_suite_name) { printed_test_suite_name = true; printf("%s.", test_suite->name()); if (test_suite->type_param() != nullptr) { printf(" # %s = ", kTypeParamLabel); // We print the type parameter on a single line to make // the output easy to parse by a program. PrintOnOneLine(test_suite->type_param(), kMaxParamLength); } printf("\n"); } printf(" %s", test_info->name()); if (test_info->value_param() != nullptr) { printf(" # %s = ", kValueParamLabel); // We print the value parameter on a single line to make the // output easy to parse by a program. PrintOnOneLine(test_info->value_param(), kMaxParamLength); } printf("\n"); } } } fflush(stdout); const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml" || output_format == "json") { FILE* fileout = OpenFileForWriting( UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); std::stringstream stream; if (output_format == "xml") { XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) .PrintXmlTestsList(&stream, test_suites_); } else if (output_format == "json") { JsonUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) .PrintJsonTestList(&stream, test_suites_); } fprintf(fileout, "%s", StringStreamToString(&stream).c_str()); fclose(fileout); } } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter are // the same; otherwise, deletes the old getter and makes the input the // current getter. void UnitTestImpl::set_os_stack_trace_getter( OsStackTraceGetterInterface* getter) { if (os_stack_trace_getter_ != getter) { delete os_stack_trace_getter_; os_stack_trace_getter_ = getter; } } // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { if (os_stack_trace_getter_ == nullptr) { #ifdef GTEST_OS_STACK_TRACE_GETTER_ os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_; #else os_stack_trace_getter_ = new OsStackTraceGetter; #endif // GTEST_OS_STACK_TRACE_GETTER_ } return os_stack_trace_getter_; } // Returns the most specific TestResult currently running. TestResult* UnitTestImpl::current_test_result() { if (current_test_info_ != nullptr) { return &current_test_info_->result_; } if (current_test_suite_ != nullptr) { return &current_test_suite_->ad_hoc_test_result_; } return &ad_hoc_test_result_; } // Shuffles all test suites, and the tests within each test suite, // making sure that death tests are still run first. void UnitTestImpl::ShuffleTests() { // Shuffles the death test suites. ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_); // Shuffles the non-death test suites. ShuffleRange(random(), last_death_test_suite_ + 1, static_cast<int>(test_suites_.size()), &test_suite_indices_); // Shuffles the tests inside each test suite. for (auto& test_suite : test_suites_) { test_suite->ShuffleTests(random()); } } // Restores the test suites and tests to their order before the first shuffle. void UnitTestImpl::UnshuffleTests() { for (size_t i = 0; i < test_suites_.size(); i++) { // Unshuffles the tests in each test suite. test_suites_[i]->UnshuffleTests(); // Resets the index of each test suite. test_suite_indices_[i] = static_cast<int>(i); } } // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { // We pass skip_count + 1 to skip this wrapper function in addition // to what the user really wants to skip. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); } // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to // suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue {}; } bool IsTrue(bool condition) { return condition; } bool AlwaysTrue() { #if GTEST_HAS_EXCEPTIONS // This condition is always false so AlwaysTrue() never actually throws, // but it makes the compiler think that it may throw. if (IsTrue(false)) throw ClassUniqueToAlwaysTrue(); #endif // GTEST_HAS_EXCEPTIONS return true; } // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged // and returns false. None of pstr, *pstr, and prefix can be NULL. bool SkipPrefix(const char* prefix, const char** pstr) { const size_t prefix_len = strlen(prefix); if (strncmp(*pstr, prefix, prefix_len) == 0) { *pstr += prefix_len; return true; } return false; } // Parses a string as a command line flag. The string should have // the format "--flag=value". When def_optional is true, the "=value" // part can be omitted. // // Returns the value of the flag, or NULL if the parsing failed. static const char* ParseFlagValue(const char* str, const char* flag, bool def_optional) { // str and flag must not be NULL. if (str == nullptr || flag == nullptr) return nullptr; // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; const size_t flag_len = flag_str.length(); if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; // Skips the flag name. const char* flag_end = str + flag_len; // When def_optional is true, it's OK to not have a "=value" part. if (def_optional && (flag_end[0] == '\0')) { return flag_end; } // If def_optional is true and there are more characters after the // flag name, or if def_optional is false, there must be a '=' after // the flag name. if (flag_end[0] != '=') return nullptr; // Returns the string after "=". return flag_end + 1; } // Parses a string for a bool flag, in the form of either // "--flag=value" or "--flag". // // In the former case, the value is taken as true as long as it does // not start with '0', 'f', or 'F'. // // In the latter case, the value is taken as true. // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. static bool ParseBoolFlag(const char* str, const char* flag, bool* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, true); // Aborts if the parsing failed. if (value_str == nullptr) return false; // Converts the string value to a bool. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); return true; } // Parses a string for an Int32 flag, in the form of // "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); // Aborts if the parsing failed. if (value_str == nullptr) return false; // Sets *value to the value of the flag. return ParseInt32(Message() << "The value of flag --" << flag, value_str, value); } // Parses a string for a string flag, in the form of // "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. template <typename String> static bool ParseStringFlag(const char* str, const char* flag, String* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); // Aborts if the parsing failed. if (value_str == nullptr) return false; // Sets *value to the value of the flag. *value = value_str; return true; } // Determines whether a string has a prefix that Google Test uses for its // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. // If Google Test detects that a command line flag has its prefix but is not // recognized, it will print its help message. Flags starting with // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // internal flags and do not trigger the help message. static bool HasGoogleTestFlagPrefix(const char* str) { return (SkipPrefix("--", &str) || SkipPrefix("-", &str) || SkipPrefix("/", &str)) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); } // Prints a string containing code-encoded text. The following escape // sequences can be used in the string to control the text color: // // @@ prints a single '@' character. // @R changes the color to red. // @G changes the color to green. // @Y changes the color to yellow. // @D changes to the default terminal text color. // static void PrintColorEncoded(const char* str) { GTestColor color = COLOR_DEFAULT; // The current color. // Conceptually, we split the string into segments divided by escape // sequences. Then we print one segment at a time. At the end of // each iteration, the str pointer advances to the beginning of the // next segment. for (;;) { const char* p = strchr(str, '@'); if (p == nullptr) { ColoredPrintf(color, "%s", str); return; } ColoredPrintf(color, "%s", std::string(str, p).c_str()); const char ch = p[1]; str = p + 2; if (ch == '@') { ColoredPrintf(color, "@"); } else if (ch == 'D') { color = COLOR_DEFAULT; } else if (ch == 'R') { color = COLOR_RED; } else if (ch == 'G') { color = COLOR_GREEN; } else if (ch == 'Y') { color = COLOR_YELLOW; } else { --str; } } } static const char kColorEncodedHelpMessage[] = "This program contains tests written using " GTEST_NAME_ ". You can use the\n" "following command line flags to control its behavior:\n" "\n" "Test Selection:\n" " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" " List the names of all tests instead of running them. The name of\n" " TEST(Foo, Bar) is \"Foo.Bar\".\n" " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" "[@G-@YNEGATIVE_PATTERNS]@D\n" " Run only the tests whose name matches one of the positive patterns but\n" " none of the negative patterns. '?' matches any single character; '*'\n" " matches any substring; ':' separates two patterns.\n" " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" " Run all disabled tests too.\n" "\n" "Test Execution:\n" " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" " Run the tests repeatedly; use a negative count to repeat forever.\n" " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" " Randomize tests' orders on every iteration.\n" " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" " Random number seed to use for shuffling test orders (between 1 and\n" " 99999, or 0 to use a seed based on the current time).\n" "\n" "Test Output:\n" " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" " Enable/disable colored output. The default is @Gauto@D.\n" " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" " Don't print the elapsed time of each test.\n" " @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" " Generate a JSON or XML report in the given directory or with the given\n" " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" # if GTEST_CAN_STREAM_RESULTS_ " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" " Stream test results to the given server.\n" # endif // GTEST_CAN_STREAM_RESULTS_ "\n" "Assertion Behavior:\n" # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" " Set the default death test style.\n" # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" " Turn assertion failures into debugger break-points.\n" " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" " Turn assertion failures into C++ exceptions for use by an external\n" " test framework.\n" " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" " Do not report exceptions as test failures. Instead, allow them\n" " to crash the program or throw a pop-up (on Windows).\n" "\n" "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " "the corresponding\n" "environment variable of a flag (all letters in upper-case). For example, to\n" "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ "color=no@D or set\n" "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" "\n" "For more information, please read the " GTEST_NAME_ " documentation at\n" "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" "(not one in your own code or tests), please report it to\n" "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; static bool ParseGoogleTestFlag(const char* const arg) { return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, &GTEST_FLAG(also_run_disabled_tests)) || ParseBoolFlag(arg, kBreakOnFailureFlag, &GTEST_FLAG(break_on_failure)) || ParseBoolFlag(arg, kCatchExceptionsFlag, &GTEST_FLAG(catch_exceptions)) || ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) || ParseStringFlag(arg, kDeathTestStyleFlag, &GTEST_FLAG(death_test_style)) || ParseBoolFlag(arg, kDeathTestUseFork, &GTEST_FLAG(death_test_use_fork)) || ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) || ParseStringFlag(arg, kInternalRunDeathTestFlag, &GTEST_FLAG(internal_run_death_test)) || ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) || ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) || ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) || ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) || ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) || ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) || ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) || ParseInt32Flag(arg, kStackTraceDepthFlag, &GTEST_FLAG(stack_trace_depth)) || ParseStringFlag(arg, kStreamResultToFlag, &GTEST_FLAG(stream_result_to)) || ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure)); } #if GTEST_USE_OWN_FLAGFILE_FLAG_ static void LoadFlagsFromFile(const std::string& path) { FILE* flagfile = posix::FOpen(path.c_str(), "r"); if (!flagfile) { GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile) << "\""; } std::string contents(ReadEntireFile(flagfile)); posix::FClose(flagfile); std::vector<std::string> lines; SplitString(contents, '\n', &lines); for (size_t i = 0; i < lines.size(); ++i) { if (lines[i].empty()) continue; if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true; } } #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ // Parses the command line for Google Test flags, without initializing // other parts of Google Test. The type parameter CharType can be // instantiated to either char or wchar_t. template <typename CharType> void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { for (int i = 1; i < *argc; i++) { const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); using internal::ParseBoolFlag; using internal::ParseInt32Flag; using internal::ParseStringFlag; bool remove_flag = false; if (ParseGoogleTestFlag(arg)) { remove_flag = true; #if GTEST_USE_OWN_FLAGFILE_FLAG_ } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) { LoadFlagsFromFile(GTEST_FLAG(flagfile)); remove_flag = true; #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ } else if (arg_string == "--help" || arg_string == "-h" || arg_string == "-?" || arg_string == "/?" || HasGoogleTestFlagPrefix(arg)) { // Both help flag and unrecognized Google Test flags (excluding // internal ones) trigger help display. g_help_flag = true; } if (remove_flag) { // Shift the remainder of the argv list left by one. Note // that argv has (*argc + 1) elements, the last one always being // NULL. The following loop moves the trailing NULL element as // well. for (int j = i; j != *argc; j++) { argv[j] = argv[j + 1]; } // Decrements the argument count. (*argc)--; // We also need to decrement the iterator as we just removed // an element. i--; } } if (g_help_flag) { // We print the help here instead of in RUN_ALL_TESTS(), as the // latter may not be called at all if the user is using Google // Test with another testing framework. PrintColorEncoded(kColorEncodedHelpMessage); } } // Parses the command line for Google Test flags, without initializing // other parts of Google Test. void ParseGoogleTestFlagsOnly(int* argc, char** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); // Fix the value of *_NSGetArgc() on macOS, but iff // *_NSGetArgv() == argv // Only applicable to char** version of argv #if GTEST_OS_MAC #ifndef GTEST_OS_IOS if (*_NSGetArgv() == argv) { *_NSGetArgc() = *argc; } #endif #endif } void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } // The internal implementation of InitGoogleTest(). // // The type parameter CharType can be instantiated to either char or // wchar_t. template <typename CharType> void InitGoogleTestImpl(int* argc, CharType** argv) { // We don't want to run the initialization code twice. if (GTestIsInitialized()) return; if (*argc <= 0) return; g_argvs.clear(); for (int i = 0; i != *argc; i++) { g_argvs.push_back(StreamableToString(argv[i])); } #if GTEST_HAS_ABSL absl::InitializeSymbolizer(g_argvs[0].c_str()); #endif // GTEST_HAS_ABSL ParseGoogleTestFlagsOnly(argc, argv); GetUnitTestImpl()->PostFlagParsingInit(); } } // namespace internal // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the // flags that Google Test recognizes. Whenever a Google Test flag is // seen, it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Test flag variables are // updated. // // Calling the function for the second time has no user-visible effect. void InitGoogleTest(int* argc, char** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } // This overloaded version can be used in Windows programs compiled in // UNICODE mode. void InitGoogleTest(int* argc, wchar_t** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } // This overloaded version can be used on Arduino/embedded platforms where // there is no argc/argv. void InitGoogleTest() { // Since Arduino doesn't have a command line, fake out the argc/argv arguments int argc = 1; const auto arg0 = "dummy"; char* argv0 = const_cast<char*>(arg0); char** argv = &argv0; #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv); #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(&argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } std::string TempDir() { #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) return GTEST_CUSTOM_TEMPDIR_FUNCTION_(); #endif #if GTEST_OS_WINDOWS_MOBILE return "\\temp\\"; #elif GTEST_OS_WINDOWS const char* temp_dir = internal::posix::GetEnv("TEMP"); if (temp_dir == nullptr || temp_dir[0] == '\0') return "\\temp\\"; else if (temp_dir[strlen(temp_dir) - 1] == '\\') return temp_dir; else return std::string(temp_dir) + "\\"; #elif GTEST_OS_LINUX_ANDROID return "/sdcard/"; #else return "/tmp/"; #endif // GTEST_OS_WINDOWS_MOBILE } // Class ScopedTrace // Pushes the given source file location and message onto a per-thread // trace stack maintained by Google Test. void ScopedTrace::PushTrace(const char* file, int line, std::string message) { internal::TraceInfo trace; trace.file = file; trace.line = line; trace.message.swap(message); UnitTest::GetInstance()->PushGTestTrace(trace); } // Pops the info pushed by the c'tor. ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { UnitTest::GetInstance()->PopGTestTrace(); } } // namespace testing // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // // This file implements death tests. #include <utility> #if GTEST_HAS_DEATH_TEST # if GTEST_OS_MAC # include <crt_externs.h> # endif // GTEST_OS_MAC # include <errno.h> # include <fcntl.h> # include <limits.h> # if GTEST_OS_LINUX # include <signal.h> # endif // GTEST_OS_LINUX # include <stdarg.h> # if GTEST_OS_WINDOWS # include <windows.h> # else # include <sys/mman.h> # include <sys/wait.h> # endif // GTEST_OS_WINDOWS # if GTEST_OS_QNX # include <spawn.h> # endif // GTEST_OS_QNX # if GTEST_OS_FUCHSIA # include <lib/fdio/fd.h> # include <lib/fdio/io.h> # include <lib/fdio/spawn.h> # include <lib/zx/port.h> # include <lib/zx/process.h> # include <lib/zx/socket.h> # include <zircon/processargs.h> # include <zircon/syscalls.h> # include <zircon/syscalls/policy.h> # include <zircon/syscalls/port.h> # endif // GTEST_OS_FUCHSIA #endif // GTEST_HAS_DEATH_TEST namespace testing { // Constants. // The default death test style. // // This is defined in internal/gtest-port.h as "fast", but can be overridden by // a definition in internal/custom/gtest-port.h. The recommended value, which is // used internally at Google, is "threadsafe". static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE; GTEST_DEFINE_string_( death_test_style, internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), "Indicates how to run a death test in a forked child process: " "\"threadsafe\" (child process re-executes the test binary " "from the beginning, running only the specific death test) or " "\"fast\" (child process runs the death test immediately " "after forking)."); GTEST_DEFINE_bool_( death_test_use_fork, internal::BoolFromGTestEnv("death_test_use_fork", false), "Instructs to use fork()/_exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " "those do not support clone(). Valgrind 3.3.1 will just fail if " "it sees an unsupported combination of clone() flags. " "It is not recommended to use this flag w/o valgrind though it will " "work in 99% of the cases. Once valgrind is fixed, this flag will " "most likely be removed."); namespace internal { GTEST_DEFINE_string_( internal_run_death_test, "", "Indicates the file, line number, temporal index of " "the single death test to run, and a file descriptor to " "which a success code may be sent, all separated by " "the '|' characters. This flag is specified if and only if the current " "process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY."); } // namespace internal #if GTEST_HAS_DEATH_TEST namespace internal { // Valid only for fast death tests. Indicates the code is running in the // child process of a fast style death test. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA static bool g_in_fast_death_test_child = false; # endif // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as // Valgrind heap checkers may need this to modify their behavior in death // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. bool InDeathTestChild() { # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // On Windows and Fuchsia, death tests are thread-safe regardless of the value // of the death_test_style flag. return !GTEST_FLAG(internal_run_death_test).empty(); # else if (GTEST_FLAG(death_test_style) == "threadsafe") return !GTEST_FLAG(internal_run_death_test).empty(); else return g_in_fast_death_test_child; #endif } } // namespace internal // ExitedWithCode constructor. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { } // ExitedWithCode function-call operator. bool ExitedWithCode::operator()(int exit_status) const { # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA return exit_status == exit_code_; # else return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA } # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // KilledBySignal constructor. KilledBySignal::KilledBySignal(int signum) : signum_(signum) { } // KilledBySignal function-call operator. bool KilledBySignal::operator()(int exit_status) const { # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) { bool result; if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { return result; } } # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA namespace internal { // Utilities needed for death tests. // Generates a textual description of a given exit code, in the format // specified by wait(2). static std::string ExitSummary(int exit_code) { Message m; # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA m << "Exited with exit status " << exit_code; # else if (WIFEXITED(exit_code)) { m << "Exited with exit status " << WEXITSTATUS(exit_code); } else if (WIFSIGNALED(exit_code)) { m << "Terminated by signal " << WTERMSIG(exit_code); } # ifdef WCOREDUMP if (WCOREDUMP(exit_code)) { m << " (core dumped)"; } # endif # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA return m.GetString(); } // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. bool ExitedUnsuccessfully(int exit_status) { return !ExitedWithCode(0)(exit_status); } # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Generates a textual failure message when a death test finds more than // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the // caller not to pass a thread_count of 1. static std::string DeathTestThreadWarning(size_t thread_count) { Message msg; msg << "Death tests use fork(), which is unsafe particularly" << " in a threaded context. For this test, " << GTEST_NAME_ << " "; if (thread_count == 0) { msg << "couldn't detect the number of threads."; } else { msg << "detected " << thread_count << " threads."; } msg << " See " "https://github.com/google/googletest/blob/master/googletest/docs/" "advanced.md#death-tests-and-threads" << " for more explanation and suggested solutions, especially if" << " this is the last message you see before your test times out."; return msg.GetString(); } # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; static const char kDeathTestReturned = 'R'; static const char kDeathTestThrew = 'T'; static const char kDeathTestInternalError = 'I'; #if GTEST_OS_FUCHSIA // File descriptor used for the pipe in the child process. static const int kFuchsiaReadPipeFd = 3; #endif // An enumeration describing all of the possible ways that a death test can // conclude. DIED means that the process died while executing the test // code; LIVED means that process lived beyond the end of the test code; // RETURNED means that the test statement attempted to execute a return // statement, which is not allowed; THREW means that the test statement // returned control by throwing an exception. IN_PROGRESS means the test // has not yet concluded. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; // Routine for aborting the program which is safe to call from an // exec-style death test child process, in which case the error // message is propagated back to the parent process. Otherwise, the // message is simply printed to stderr. In either case, the program // then exits with status 1. static void DeathTestAbort(const std::string& message) { // On a POSIX system, this function may be called from a threadsafe-style // death test child process, which operates on a very small stack. Use // the heap for any additional non-minuscule memory requirements. const InternalRunDeathTestFlag* const flag = GetUnitTestImpl()->internal_run_death_test_flag(); if (flag != nullptr) { FILE* parent = posix::FDOpen(flag->write_fd(), "w"); fputc(kDeathTestInternalError, parent); fprintf(parent, "%s", message.c_str()); fflush(parent); _exit(1); } else { fprintf(stderr, "%s", message.c_str()); fflush(stderr); posix::Abort(); } } // A replacement for CHECK that calls DeathTestAbort if the assertion // fails. # define GTEST_DEATH_TEST_CHECK_(expression) \ do { \ if (!::testing::internal::IsTrue(expression)) { \ DeathTestAbort( \ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + ::testing::internal::StreamableToString(__LINE__) + ": " \ + #expression); \ } \ } while (::testing::internal::AlwaysFalse()) // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for // evaluating any system call that fulfills two conditions: it must return // -1 on failure, and set errno to EINTR when it is interrupted and // should be tried again. The macro expands to a loop that repeatedly // evaluates the expression as long as it evaluates to -1 and sets // errno to EINTR. If the expression evaluates to -1 but errno is // something other than EINTR, DeathTestAbort is called. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ do { \ int gtest_retval; \ do { \ gtest_retval = (expression); \ } while (gtest_retval == -1 && errno == EINTR); \ if (gtest_retval == -1) { \ DeathTestAbort( \ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + ::testing::internal::StreamableToString(__LINE__) + ": " \ + #expression + " != -1"); \ } \ } while (::testing::internal::AlwaysFalse()) // Returns the message describing the last system error in errno. std::string GetLastErrnoDescription() { return errno == 0 ? "" : posix::StrError(errno); } // This is called from a death test parent process to read a failure // message from the death test child process and log it with the FATAL // severity. On Windows, the message is read from a pipe handle. On other // platforms, it is read from a file descriptor. static void FailFromInternalError(int fd) { Message error; char buffer[256]; int num_read; do { while ((num_read = posix::Read(fd, buffer, 255)) > 0) { buffer[num_read] = '\0'; error << buffer; } } while (num_read == -1 && errno == EINTR); if (num_read == 0) { GTEST_LOG_(FATAL) << error.GetString(); } else { const int last_error = errno; GTEST_LOG_(FATAL) << "Error while reading death test internal: " << GetLastErrnoDescription() << " [" << last_error << "]"; } } // Death test constructor. Increments the running death test count // for the current test. DeathTest::DeathTest() { TestInfo* const info = GetUnitTestImpl()->current_test_info(); if (info == nullptr) { DeathTestAbort("Cannot run a death test outside of a TEST or " "TEST_F construct"); } } // Creates and returns a death test by dispatching to the current // death test factory. bool DeathTest::Create(const char* statement, Matcher<const std::string&> matcher, const char* file, int line, DeathTest** test) { return GetUnitTestImpl()->death_test_factory()->Create( statement, std::move(matcher), file, line, test); } const char* DeathTest::LastMessage() { return last_death_test_message_.c_str(); } void DeathTest::set_last_death_test_message(const std::string& message) { last_death_test_message_ = message; } std::string DeathTest::last_death_test_message_; // Provides cross platform implementation for some death functionality. class DeathTestImpl : public DeathTest { protected: DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher) : statement_(a_statement), matcher_(std::move(matcher)), spawned_(false), status_(-1), outcome_(IN_PROGRESS), read_fd_(-1), write_fd_(-1) {} // read_fd_ is expected to be closed and cleared by a derived class. ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } void Abort(AbortReason reason) override; bool Passed(bool status_ok) override; const char* statement() const { return statement_; } bool spawned() const { return spawned_; } void set_spawned(bool is_spawned) { spawned_ = is_spawned; } int status() const { return status_; } void set_status(int a_status) { status_ = a_status; } DeathTestOutcome outcome() const { return outcome_; } void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } int read_fd() const { return read_fd_; } void set_read_fd(int fd) { read_fd_ = fd; } int write_fd() const { return write_fd_; } void set_write_fd(int fd) { write_fd_ = fd; } // Called in the parent process only. Reads the result code of the death // test child process via a pipe, interprets it to set the outcome_ // member, and closes read_fd_. Outputs diagnostics and terminates in // case of unexpected codes. void ReadAndInterpretStatusByte(); // Returns stderr output from the child process. virtual std::string GetErrorLogs(); private: // The textual content of the code this object is testing. This class // doesn't own this string and should not attempt to delete it. const char* const statement_; // A matcher that's expected to match the stderr output by the child process. Matcher<const std::string&> matcher_; // True if the death test child process has been successfully spawned. bool spawned_; // The exit status of the child process. int status_; // How the death test concluded. DeathTestOutcome outcome_; // Descriptor to the read end of the pipe to the child process. It is // always -1 in the child process. The child keeps its write end of the // pipe in write_fd_. int read_fd_; // Descriptor to the child's write end of the pipe to the parent process. // It is always -1 in the parent process. The parent keeps its end of the // pipe in read_fd_. int write_fd_; }; // Called in the parent process only. Reads the result code of the death // test child process via a pipe, interprets it to set the outcome_ // member, and closes read_fd_. Outputs diagnostics and terminates in // case of unexpected codes. void DeathTestImpl::ReadAndInterpretStatusByte() { char flag; int bytes_read; // The read() here blocks until data is available (signifying the // failure of the death test) or until the pipe is closed (signifying // its success), so it's okay to call this in the parent before // the child process has exited. do { bytes_read = posix::Read(read_fd(), &flag, 1); } while (bytes_read == -1 && errno == EINTR); if (bytes_read == 0) { set_outcome(DIED); } else if (bytes_read == 1) { switch (flag) { case kDeathTestReturned: set_outcome(RETURNED); break; case kDeathTestThrew: set_outcome(THREW); break; case kDeathTestLived: set_outcome(LIVED); break; case kDeathTestInternalError: FailFromInternalError(read_fd()); // Does not return. break; default: GTEST_LOG_(FATAL) << "Death test child process reported " << "unexpected status byte (" << static_cast<unsigned int>(flag) << ")"; } } else { GTEST_LOG_(FATAL) << "Read from death test child process failed: " << GetLastErrnoDescription(); } GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); set_read_fd(-1); } std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); } // Signals that the death test code which should have exited, didn't. // Should be called only in a death test child process. // Writes a status byte to the child's status file descriptor, then // calls _exit(1). void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte // to the pipe, then exit. const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., // when built as Windows DLL), destructors of global objects will still // run after calling _exit(). On such systems, write_fd_ will be // indirectly closed from the destructor of UnitTestImpl, causing double // close if it is also closed here. On debug configurations, double close // may assert. As there are no in-process buffers to flush here, we are // relying on the OS to close the descriptor after the process terminates // when the destructors are not run. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) } // Returns an indented copy of stderr output for a death test. // This makes distinguishing death test output lines from regular log lines // much easier. static ::std::string FormatDeathTestOutput(const ::std::string& output) { ::std::string ret; for (size_t at = 0; ; ) { const size_t line_end = output.find('\n', at); ret += "[ DEATH ] "; if (line_end == ::std::string::npos) { ret += output.substr(at); break; } ret += output.substr(at, line_end + 1 - at); at = line_end + 1; } return ret; } // Assesses the success or failure of a death test, using both private // members which have previously been set, and one argument: // // Private data members: // outcome: An enumeration describing how the death test // concluded: DIED, LIVED, THREW, or RETURNED. The death test // fails in the latter three cases. // status: The exit status of the child process. On *nix, it is in the // in the format specified by wait(2). On Windows, this is the // value supplied to the ExitProcess() API or a numeric code // of the exception that terminated the program. // matcher_: A matcher that's expected to match the stderr output by the child // process. // // Argument: // status_ok: true if exit_status is acceptable in the context of // this particular death test, which fails if it is false // // Returns true iff all of the above conditions are met. Otherwise, the // first failing condition, in the order given above, is the one that is // reported. Also sets the last death test message string. bool DeathTestImpl::Passed(bool status_ok) { if (!spawned()) return false; const std::string error_message = GetErrorLogs(); bool success = false; Message buffer; buffer << "Death test: " << statement() << "\n"; switch (outcome()) { case LIVED: buffer << " Result: failed to die.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case THREW: buffer << " Result: threw an exception.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case RETURNED: buffer << " Result: illegal return in test statement.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case DIED: if (status_ok) { if (matcher_.Matches(error_message)) { success = true; } else { std::ostringstream stream; matcher_.DescribeTo(&stream); buffer << " Result: died but not with expected error.\n" << " Expected: " << stream.str() << "\n" << "Actual msg:\n" << FormatDeathTestOutput(error_message); } } else { buffer << " Result: died but not with expected exit code:\n" << " " << ExitSummary(status()) << "\n" << "Actual msg:\n" << FormatDeathTestOutput(error_message); } break; case IN_PROGRESS: default: GTEST_LOG_(FATAL) << "DeathTest::Passed somehow called before conclusion of test"; } DeathTest::set_last_death_test_message(buffer.GetString()); return success; } # if GTEST_OS_WINDOWS // WindowsDeathTest implements death tests on Windows. Due to the // specifics of starting new processes on Windows, death tests there are // always threadsafe, and Google Test considers the // --gtest_death_test_style=fast setting to be equivalent to // --gtest_death_test_style=threadsafe there. // // A few implementation notes: Like the Linux version, the Windows // implementation uses pipes for child-to-parent communication. But due to // the specifics of pipes on Windows, some extra steps are required: // // 1. The parent creates a communication pipe and stores handles to both // ends of it. // 2. The parent starts the child and provides it with the information // necessary to acquire the handle to the write end of the pipe. // 3. The child acquires the write end of the pipe and signals the parent // using a Windows event. // 4. Now the parent can release the write end of the pipe on its side. If // this is done before step 3, the object's reference count goes down to // 0 and it is destroyed, preventing the child from acquiring it. The // parent now has to release it, or read operations on the read end of // the pipe will not return when the child terminates. // 5. The parent reads child's output through the pipe (outcome code and // any possible error messages) from the pipe, and its stderr and then // determines whether to fail the test. // // Note: to distinguish Win32 API calls from the local method and function // calls, the former are explicitly resolved in the global namespace. // class WindowsDeathTest : public DeathTestImpl { public: WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher, const char* file, int line) : DeathTestImpl(a_statement, std::move(matcher)), file_(file), line_(line) {} // All of these virtual functions are inherited from DeathTest. virtual int Wait(); virtual TestRole AssumeRole(); private: // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; // Handle to the write end of the pipe to the child process. AutoHandle write_handle_; // Child process handle. AutoHandle child_handle_; // Event the child process uses to signal the parent that it has // acquired the handle to the write end of the pipe. After seeing this // event the parent can release its own handles to make sure its // ReadFile() calls return when the child terminates. AutoHandle event_handle_; }; // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int WindowsDeathTest::Wait() { if (!spawned()) return 0; // Wait until the child either signals that it has acquired the write end // of the pipe or it dies. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; switch (::WaitForMultipleObjects(2, wait_handles, FALSE, // Waits for any of the handles. INFINITE)) { case WAIT_OBJECT_0: case WAIT_OBJECT_0 + 1: break; default: GTEST_DEATH_TEST_CHECK_(false); // Should not get here. } // The child has acquired the write end of the pipe or exited. // We release the handle on our side and continue. write_handle_.Reset(); event_handle_.Reset(); ReadAndInterpretStatusByte(); // Waits for the child process to exit if it haven't already. This // returns immediately if the child has already exited, regardless of // whether previous calls to WaitForMultipleObjects synchronized on this // handle or not. GTEST_DEATH_TEST_CHECK_( WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), INFINITE)); DWORD status_code; GTEST_DEATH_TEST_CHECK_( ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); child_handle_.Reset(); set_status(static_cast<int>(status_code)); return status(); } // The AssumeRole process for a Windows death test. It creates a child // process with the same executable as the current process to run the // death test. The child process is given the --gtest_filter and // --gtest_internal_run_death_test flags such that it knows to run the // current death test only. DeathTest::TestRole WindowsDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != nullptr) { // ParseInternalRunDeathTestFlag() has performed all the necessary // processing. set_write_fd(flag->write_fd()); return EXECUTE_TEST; } // WindowsDeathTest uses an anonymous pipe to communicate results of // a death test. SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; HANDLE read_handle, write_handle; GTEST_DEATH_TEST_CHECK_( ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, 0) // Default buffer size. != FALSE); set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY)); write_handle_.Reset(write_handle); event_handle_.Reset(::CreateEvent( &handles_are_inheritable, TRUE, // The event will automatically reset to non-signaled state. FALSE, // The initial state is non-signalled. nullptr)); // The even is unnamed. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr); const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_suite_name() + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) + // size_t has the same width as pointers on both 32-bit and 64-bit // Windows platforms. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get())); char executable_path[_MAX_PATH + 1]; // NOLINT GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr, executable_path, _MAX_PATH)); std::string command_line = std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + internal_flag + "\""; DeathTest::set_last_death_test_message(""); CaptureStderr(); // Flush the log buffers since the log streams are shared with the child. FlushInfoLog(); // The child process will share the standard handles with the parent. STARTUPINFOA startup_info; memset(&startup_info, 0, sizeof(STARTUPINFO)); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); PROCESS_INFORMATION process_info; GTEST_DEATH_TEST_CHECK_( ::CreateProcessA( executable_path, const_cast<char*>(command_line.c_str()), nullptr, // Retuned process handle is not inheritable. nullptr, // Retuned thread handle is not inheritable. TRUE, // Child inherits all inheritable handles (for write_handle_). 0x0, // Default creation flags. nullptr, // Inherit the parent's environment. UnitTest::GetInstance()->original_working_dir(), &startup_info, &process_info) != FALSE); child_handle_.Reset(process_info.hProcess); ::CloseHandle(process_info.hThread); set_spawned(true); return OVERSEE_TEST; } # elif GTEST_OS_FUCHSIA class FuchsiaDeathTest : public DeathTestImpl { public: FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher, const char* file, int line) : DeathTestImpl(a_statement, std::move(matcher)), file_(file), line_(line) {} // All of these virtual functions are inherited from DeathTest. int Wait() override; TestRole AssumeRole() override; std::string GetErrorLogs() override; private: // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; // The stderr data captured by the child process. std::string captured_stderr_; zx::process child_process_; zx::port port_; zx::socket stderr_socket_; }; // Utility class for accumulating command-line arguments. class Arguments { public: Arguments() { args_.push_back(nullptr); } ~Arguments() { for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); ++i) { free(*i); } } void AddArgument(const char* argument) { args_.insert(args_.end() - 1, posix::StrDup(argument)); } template <typename Str> void AddArguments(const ::std::vector<Str>& arguments) { for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } char* const* Argv() { return &args_[0]; } int size() { return args_.size() - 1; } private: std::vector<char*> args_; }; // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int FuchsiaDeathTest::Wait() { const int kProcessKey = 0; const int kSocketKey = 1; if (!spawned()) return 0; // Register to wait for the child process to terminate. zx_status_t status_zx; status_zx = child_process_.wait_async( port_, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); // Register to wait for the socket to be readable or closed. status_zx = stderr_socket_.wait_async( port_, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, ZX_WAIT_ASYNC_REPEATING); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); bool process_terminated = false; bool socket_closed = false; do { zx_port_packet_t packet = {}; status_zx = port_.wait(zx::time::infinite(), &packet); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); if (packet.key == kProcessKey) { if (ZX_PKT_IS_EXCEPTION(packet.type)) { // Process encountered an exception. Kill it directly rather than // letting other handlers process the event. We will get a second // kProcessKey event when the process actually terminates. status_zx = child_process_.kill(); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); } else { // Process terminated. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type)); GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED); process_terminated = true; } } else if (packet.key == kSocketKey) { GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_REP(packet.type)); if (packet.signal.observed & ZX_SOCKET_READABLE) { // Read data from the socket. constexpr size_t kBufferSize = 1024; do { size_t old_length = captured_stderr_.length(); size_t bytes_read = 0; captured_stderr_.resize(old_length + kBufferSize); status_zx = stderr_socket_.read( 0, &captured_stderr_.front() + old_length, kBufferSize, &bytes_read); captured_stderr_.resize(old_length + bytes_read); } while (status_zx == ZX_OK); if (status_zx == ZX_ERR_PEER_CLOSED) { socket_closed = true; } else { GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT); } } else { GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED); socket_closed = true; } } } while (!process_terminated && !socket_closed); ReadAndInterpretStatusByte(); zx_info_process_t buffer; status_zx = child_process_.get_info( ZX_INFO_PROCESS, &buffer, sizeof(buffer), nullptr, nullptr); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); GTEST_DEATH_TEST_CHECK_(buffer.exited); set_status(buffer.return_code); return status(); } // The AssumeRole process for a Fuchsia death test. It creates a child // process with the same executable as the current process to run the // death test. The child process is given the --gtest_filter and // --gtest_internal_run_death_test flags such that it knows to run the // current death test only. DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != nullptr) { // ParseInternalRunDeathTestFlag() has performed all the necessary // processing. set_write_fd(kFuchsiaReadPipeFd); return EXECUTE_TEST; } // Flush the log buffers since the log streams are shared with the child. FlushInfoLog(); // Build the child process command line. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_suite_name() + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index); Arguments args; args.AddArguments(GetInjectableArgvs()); args.AddArgument(filter_flag.c_str()); args.AddArgument(internal_flag.c_str()); // Build the pipe for communication with the child. zx_status_t status; zx_handle_t child_pipe_handle; int child_pipe_fd; status = fdio_pipe_half2(&child_pipe_fd, &child_pipe_handle); GTEST_DEATH_TEST_CHECK_(status != ZX_OK); set_read_fd(child_pipe_fd); // Set the pipe handle for the child. fdio_spawn_action_t spawn_actions[2] = {}; fdio_spawn_action_t* add_handle_action = &spawn_actions[0]; add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE; add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd); add_handle_action->h.handle = child_pipe_handle; // Create a socket pair will be used to receive the child process' stderr. zx::socket stderr_producer_socket; status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_); GTEST_DEATH_TEST_CHECK_(status >= 0); int stderr_producer_fd = -1; status = fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd); GTEST_DEATH_TEST_CHECK_(status >= 0); // Make the stderr socket nonblocking. GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0); fdio_spawn_action_t* add_stderr_action = &spawn_actions[1]; add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD; add_stderr_action->fd.local_fd = stderr_producer_fd; add_stderr_action->fd.target_fd = STDERR_FILENO; // Create a child job. zx_handle_t child_job = ZX_HANDLE_INVALID; status = zx_job_create(zx_job_default(), 0, & child_job); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); zx_policy_basic_t policy; policy.condition = ZX_POL_NEW_ANY; policy.policy = ZX_POL_ACTION_ALLOW; status = zx_job_set_policy( child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); // Create an exception port and attach it to the |child_job|, to allow // us to suppress the system default exception handler from firing. status = zx::port::create(0, &port_); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); status = zx_task_bind_exception_port( child_job, port_.get(), 0 /* key */, 0 /*options */); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); // Spawn the child process. status = fdio_spawn_etc( child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr, 2, spawn_actions, child_process_.reset_and_get_address(), nullptr); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); set_spawned(true); return OVERSEE_TEST; } std::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; } #else // We are neither on Windows, nor on Fuchsia. // ForkingDeathTest provides implementations for most of the abstract // methods of the DeathTest interface. Only the AssumeRole method is // left undefined. class ForkingDeathTest : public DeathTestImpl { public: ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher); // All of these virtual functions are inherited from DeathTest. int Wait() override; protected: void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } private: // PID of child process during death test; 0 in the child process itself. pid_t child_pid_; }; // Constructs a ForkingDeathTest. ForkingDeathTest::ForkingDeathTest(const char* a_statement, Matcher<const std::string&> matcher) : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {} // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int ForkingDeathTest::Wait() { if (!spawned()) return 0; ReadAndInterpretStatusByte(); int status_value; GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); set_status(status_value); return status_value; } // A concrete death test class that forks, then immediately runs the test // in the child process. class NoExecDeathTest : public ForkingDeathTest { public: NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher) : ForkingDeathTest(a_statement, std::move(matcher)) {} TestRole AssumeRole() override; }; // The AssumeRole process for a fork-and-run death test. It implements a // straightforward fork, with a simple pipe to transmit the status byte. DeathTest::TestRole NoExecDeathTest::AssumeRole() { const size_t thread_count = GetThreadCount(); if (thread_count != 1) { GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); } int pipe_fd[2]; GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); DeathTest::set_last_death_test_message(""); CaptureStderr(); // When we fork the process below, the log file buffers are copied, but the // file descriptors are shared. We flush all log files here so that closing // the file descriptors in the child process doesn't throw off the // synchronization between descriptors and buffers in the parent process. // This is as close to the fork as possible to avoid a race condition in case // there are multiple threads running before the death test, and another // thread writes to the log file. FlushInfoLog(); const pid_t child_pid = fork(); GTEST_DEATH_TEST_CHECK_(child_pid != -1); set_child_pid(child_pid); if (child_pid == 0) { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); set_write_fd(pipe_fd[1]); // Redirects all logging to stderr in the child process to prevent // concurrent writes to the log files. We capture stderr in the parent // process and append the child process' output to a log. LogToStderr(); // Event forwarding to the listeners of event listener API mush be shut // down in death test subprocesses. GetUnitTestImpl()->listeners()->SuppressEventForwarding(); g_in_fast_death_test_child = true; return EXECUTE_TEST; } else { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_read_fd(pipe_fd[0]); set_spawned(true); return OVERSEE_TEST; } } // A concrete death test class that forks and re-executes the main // program from the beginning, with command-line flags set that cause // only this specific death test to be run. class ExecDeathTest : public ForkingDeathTest { public: ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher, const char* file, int line) : ForkingDeathTest(a_statement, std::move(matcher)), file_(file), line_(line) {} TestRole AssumeRole() override; private: static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() { ::std::vector<std::string> args = GetInjectableArgvs(); # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) ::std::vector<std::string> extra_args = GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); args.insert(args.end(), extra_args.begin(), extra_args.end()); # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) return args; } // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; }; // Utility class for accumulating command-line arguments. class Arguments { public: Arguments() { args_.push_back(nullptr); } ~Arguments() { for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); ++i) { free(*i); } } void AddArgument(const char* argument) { args_.insert(args_.end() - 1, posix::StrDup(argument)); } template <typename Str> void AddArguments(const ::std::vector<Str>& arguments) { for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } char* const* Argv() { return &args_[0]; } private: std::vector<char*> args_; }; // A struct that encompasses the arguments to the child process of a // threadsafe-style death test process. struct ExecDeathTestArgs { char* const* argv; // Command-line arguments for the child's call to exec int close_fd; // File descriptor to close; the read end of a pipe }; # if GTEST_OS_MAC inline char** GetEnviron() { // When Google Test is built as a framework on MacOS X, the environ variable // is unavailable. Apple's documentation (man environ) recommends using // _NSGetEnviron() instead. return *_NSGetEnviron(); } # else // Some POSIX platforms expect you to declare environ. extern "C" makes // it reside in the global namespace. extern "C" char** environ; inline char** GetEnviron() { return environ; } # endif // GTEST_OS_MAC # if !GTEST_OS_QNX // The main function for a threadsafe-style death test child process. // This function is called in a clone()-ed process and thus must avoid // any potentially unsafe operations like malloc or libc functions. static int ExecDeathTestChildMain(void* child_arg) { ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } // We can safely call execve() as it's a direct system call. We // cannot use execvp() as it's a libc function and thus potentially // unsafe. Since execve() doesn't search the PATH, the user must // invoke the test program via a valid path that contains at least // one path separator. execve(args->argv[0], args->argv, GetEnviron()); DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + original_dir + " failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } # endif // !GTEST_OS_QNX # if GTEST_HAS_CLONE // Two utility routines that together determine the direction the stack // grows. // This could be accomplished more elegantly by a single recursive // function, but we want to guard against the unlikely possibility of // a smart compiler optimizing the recursion away. // // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining // StackLowerThanAddress into StackGrowsDown, which then doesn't give // correct answer. static void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_; // HWAddressSanitizer add a random tag to the MSB of the local variable address, // making comparison result unpredictable. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ static void StackLowerThanAddress(const void* ptr, bool* result) { int dummy; *result = (&dummy < ptr); } // Make sure AddressSanitizer does not tamper with the stack here. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ static bool StackGrowsDown() { int dummy; bool result; StackLowerThanAddress(&dummy, &result); return result; } # endif // GTEST_HAS_CLONE // Spawns a child process with the same executable as the current process in // a thread-safe manner and instructs it to run the death test. The // implementation uses fork(2) + exec. On systems where clone(2) is // available, it is used instead, being slightly more thread-safe. On QNX, // fork supports only single-threaded environments, so this function uses // spawn(2) there instead. The function dies with an error message if // anything goes wrong. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ExecDeathTestArgs args = { argv, close_fd }; pid_t child_pid = -1; # if GTEST_OS_QNX // Obtains the current directory and sets it to be closed in the child // process. const int cwd_fd = open(".", O_RDONLY); GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } int fd_flags; // Set close_fd to be closed after spawn. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC)); struct inheritance inherit = {0}; // spawn is a system call. child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron()); // Restores the current working directory. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); # else // GTEST_OS_QNX # if GTEST_OS_LINUX // When a SIGPROF signal is received while fork() or clone() are executing, // the process may hang. To avoid this, we ignore SIGPROF here and re-enable // it after the call to fork()/clone() is complete. struct sigaction saved_sigprof_action; struct sigaction ignore_sigprof_action; memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); sigemptyset(&ignore_sigprof_action.sa_mask); ignore_sigprof_action.sa_handler = SIG_IGN; GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); # endif // GTEST_OS_LINUX # if GTEST_HAS_CLONE const bool use_fork = GTEST_FLAG(death_test_use_fork); if (!use_fork) { static const bool stack_grows_down = StackGrowsDown(); const size_t stack_size = getpagesize(); // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); // Maximum stack alignment in bytes: For a downward-growing stack, this // amount is subtracted from size of the stack space to get an address // that is within the stack space and is aligned on all systems we care // about. As far as I know there is no ABI with stack alignment greater // than 64. We assume stack and stack_size already have alignment of // kMaxStackAlignment. const size_t kMaxStackAlignment = 64; void* const stack_top = static_cast<char*>(stack) + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0); child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); } # else const bool use_fork = true; # endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { ExecDeathTestChildMain(&args); _exit(0); } # endif // GTEST_OS_QNX # if GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_SYSCALL_( sigaction(SIGPROF, &saved_sigprof_action, nullptr)); # endif // GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_(child_pid != -1); return child_pid; } // The AssumeRole process for a fork-and-exec death test. It re-executes the // main program from the beginning, setting the --gtest_filter // and --gtest_internal_run_death_test flags to cause only the current // death test to be re-run. DeathTest::TestRole ExecDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != nullptr) { set_write_fd(flag->write_fd()); return EXECUTE_TEST; } int pipe_fd[2]; GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); // Clear the close-on-exec flag on the write end of the pipe, lest // it be closed when the child process does an exec: GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_suite_name() + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + StreamableToString(pipe_fd[1]); Arguments args; args.AddArguments(GetArgvsForDeathTestChildProcess()); args.AddArgument(filter_flag.c_str()); args.AddArgument(internal_flag.c_str()); DeathTest::set_last_death_test_message(""); CaptureStderr(); // See the comment in NoExecDeathTest::AssumeRole for why the next line // is necessary. FlushInfoLog(); const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_child_pid(child_pid); set_read_fd(pipe_fd[0]); set_spawned(true); return OVERSEE_TEST; } # endif // !GTEST_OS_WINDOWS // Creates a concrete DeathTest-derived class that depends on the // --gtest_death_test_style flag, and sets the pointer pointed to // by the "test" argument to its address. If the test should be // skipped, sets that pointer to NULL. Returns true, unless the // flag is set to an invalid value. bool DefaultDeathTestFactory::Create(const char* statement, Matcher<const std::string&> matcher, const char* file, int line, DeathTest** test) { UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const int death_test_index = impl->current_test_info() ->increment_death_test_count(); if (flag != nullptr) { if (death_test_index > flag->index()) { DeathTest::set_last_death_test_message( "Death test count (" + StreamableToString(death_test_index) + ") somehow exceeded expected maximum (" + StreamableToString(flag->index()) + ")"); return false; } if (!(flag->file() == file && flag->line() == line && flag->index() == death_test_index)) { *test = nullptr; return true; } } # if GTEST_OS_WINDOWS if (GTEST_FLAG(death_test_style) == "threadsafe" || GTEST_FLAG(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, std::move(matcher), file, line); } # elif GTEST_OS_FUCHSIA if (GTEST_FLAG(death_test_style) == "threadsafe" || GTEST_FLAG(death_test_style) == "fast") { *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line); } # else if (GTEST_FLAG(death_test_style) == "threadsafe") { *test = new ExecDeathTest(statement, std::move(matcher), file, line); } else if (GTEST_FLAG(death_test_style) == "fast") { *test = new NoExecDeathTest(statement, std::move(matcher)); } # endif // GTEST_OS_WINDOWS else { // NOLINT - this is more readable than unbalanced brackets inside #if. DeathTest::set_last_death_test_message( "Unknown death test style \"" + GTEST_FLAG(death_test_style) + "\" encountered"); return false; } return true; } # if GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe // handle. This function is called in the child process only. static int GetStatusFileDescriptor(unsigned int parent_process_id, size_t write_handle_as_size_t, size_t event_handle_as_size_t) { AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, FALSE, // Non-inheritable. parent_process_id)); if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { DeathTestAbort("Unable to open parent process " + StreamableToString(parent_process_id)); } GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t); HANDLE dup_write_handle; // The newly initialized handle is accessible only in the parent // process. To obtain one accessible within the child, we need to use // DuplicateHandle. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, ::GetCurrentProcess(), &dup_write_handle, 0x0, // Requested privileges ignored since // DUPLICATE_SAME_ACCESS is used. FALSE, // Request non-inheritable handler. DUPLICATE_SAME_ACCESS)) { DeathTestAbort("Unable to duplicate the pipe handle " + StreamableToString(write_handle_as_size_t) + " from the parent process " + StreamableToString(parent_process_id)); } const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); HANDLE dup_event_handle; if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE, DUPLICATE_SAME_ACCESS)) { DeathTestAbort("Unable to duplicate the event handle " + StreamableToString(event_handle_as_size_t) + " from the parent process " + StreamableToString(parent_process_id)); } const int write_fd = ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); if (write_fd == -1) { DeathTestAbort("Unable to convert pipe handle " + StreamableToString(write_handle_as_size_t) + " to a file descriptor"); } // Signals the parent that the write end of the pipe has been acquired // so the parent can release its own write end. ::SetEvent(dup_event_handle); return write_fd; } # endif // GTEST_OS_WINDOWS // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { if (GTEST_FLAG(internal_run_death_test) == "") return nullptr; // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we // can use it here. int line = -1; int index = -1; ::std::vector< ::std::string> fields; SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); int write_fd = -1; # if GTEST_OS_WINDOWS unsigned int parent_process_id = 0; size_t write_handle_as_size_t = 0; size_t event_handle_as_size_t = 0; if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &parent_process_id) || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, event_handle_as_size_t); # elif GTEST_OS_FUCHSIA if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } # else if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &write_fd)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } # endif // GTEST_OS_WINDOWS return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); } } // namespace internal #endif // GTEST_HAS_DEATH_TEST } // namespace testing // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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 <stdlib.h> #if GTEST_OS_WINDOWS_MOBILE # include <windows.h> #elif GTEST_OS_WINDOWS # include <direct.h> # include <io.h> #else # include <limits.h> # include <climits> // Some Linux distributions define PATH_MAX here. #endif // GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS # define GTEST_PATH_MAX_ _MAX_PATH #elif defined(PATH_MAX) # define GTEST_PATH_MAX_ PATH_MAX #elif defined(_XOPEN_PATH_MAX) # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX #else # define GTEST_PATH_MAX_ _POSIX_PATH_MAX #endif // GTEST_OS_WINDOWS namespace testing { namespace internal { #if GTEST_OS_WINDOWS // On Windows, '\\' is the standard path separator, but many tools and the // Windows API also accept '/' as an alternate path separator. Unless otherwise // noted, a file path can contain either kind of path separators, or a mixture // of them. const char kPathSeparator = '\\'; const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparatorString[] = "/"; # if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory. You should not use // the current directory in tests on Windows CE, but this at least // provides a reasonable fallback. const char kCurrentDirectoryString[] = "\\"; // Windows CE doesn't define INVALID_FILE_ATTRIBUTES const DWORD kInvalidFileAttributes = 0xffffffff; # else const char kCurrentDirectoryString[] = ".\\"; # endif // GTEST_OS_WINDOWS_MOBILE #else const char kPathSeparator = '/'; const char kCurrentDirectoryString[] = "./"; #endif // GTEST_OS_WINDOWS // Returns whether the given character is a valid path separator. static bool IsPathSeparator(char c) { #if GTEST_HAS_ALT_PATH_SEP_ return (c == kPathSeparator) || (c == kAlternatePathSeparator); #else return c == kPathSeparator; #endif } // Returns the current working directory, or "" if unsuccessful. FilePath FilePath::GetCurrentDir() { #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ GTEST_OS_WINDOWS_RT || ARDUINO // Windows CE and Arduino don't have a current directory, so we just return // something reasonable. return FilePath(kCurrentDirectoryString); #elif GTEST_OS_WINDOWS char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd); #else char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; char* result = getcwd(cwd, sizeof(cwd)); # if GTEST_OS_NACL // getcwd will likely fail in NaCl due to the sandbox, so return something // reasonable. The user may have provided a shim implementation for getcwd, // however, so fallback only when failure is detected. return FilePath(result == nullptr ? kCurrentDirectoryString : cwd); # endif // GTEST_OS_NACL return FilePath(result == nullptr ? "" : cwd); #endif // GTEST_OS_WINDOWS_MOBILE } // Returns a copy of the FilePath with the case-insensitive extension removed. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns // FilePath("dir/file"). If a case-insensitive extension is not // found, returns a copy of the original FilePath. FilePath FilePath::RemoveExtension(const char* extension) const { const std::string dot_extension = std::string(".") + extension; if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { return FilePath(pathname_.substr( 0, pathname_.length() - dot_extension.length())); } return *this; } // Returns a pointer to the last occurrence of a valid path separator in // the FilePath. On Windows, for example, both '/' and '\' are valid path // separators. Returns NULL if no path separator was found. const char* FilePath::FindLastPathSeparator() const { const char* const last_sep = strrchr(c_str(), kPathSeparator); #if GTEST_HAS_ALT_PATH_SEP_ const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); // Comparing two pointers of which only one is NULL is undefined. if (last_alt_sep != nullptr && (last_sep == nullptr || last_alt_sep > last_sep)) { return last_alt_sep; } #endif return last_sep; } // Returns a copy of the FilePath with the directory part removed. // Example: FilePath("path/to/file").RemoveDirectoryName() returns // FilePath("file"). If there is no directory part ("just_a_file"), it returns // the FilePath unmodified. If there is no file part ("just_a_dir/") it // returns an empty FilePath (""). // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveDirectoryName() const { const char* const last_sep = FindLastPathSeparator(); return last_sep ? FilePath(last_sep + 1) : *this; } // RemoveFileName returns the directory path with the filename removed. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". // If the FilePath is "a_file" or "/a_file", RemoveFileName returns // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does // not have a file, like "just/a/dir/", it returns the FilePath unmodified. // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveFileName() const { const char* const last_sep = FindLastPathSeparator(); std::string dir; if (last_sep) { dir = std::string(c_str(), last_sep + 1 - c_str()); } else { dir = kCurrentDirectoryString; } return FilePath(dir); } // Helper functions for naming files in a directory for xml output. // Given directory = "dir", base_name = "test", number = 0, // extension = "xml", returns "dir/test.xml". If number is greater // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. FilePath FilePath::MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension) { std::string file; if (number == 0) { file = base_name.string() + "." + extension; } else { file = base_name.string() + "_" + StreamableToString(number) + "." + extension; } return ConcatPaths(directory, FilePath(file)); } // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". // On Windows, uses \ as the separator rather than /. FilePath FilePath::ConcatPaths(const FilePath& directory, const FilePath& relative_path) { if (directory.IsEmpty()) return relative_path; const FilePath dir(directory.RemoveTrailingPathSeparator()); return FilePath(dir.string() + kPathSeparator + relative_path.string()); } // Returns true if pathname describes something findable in the file-system, // either a file, directory, or whatever. bool FilePath::FileOrDirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); const DWORD attributes = GetFileAttributes(unicode); delete [] unicode; return attributes != kInvalidFileAttributes; #else posix::StatStruct file_stat; return posix::Stat(pathname_.c_str(), &file_stat) == 0; #endif // GTEST_OS_WINDOWS_MOBILE } // Returns true if pathname describes a directory in the file-system // that exists. bool FilePath::DirectoryExists() const { bool result = false; #if GTEST_OS_WINDOWS // Don't strip off trailing separator if path is a root directory on // Windows (like "C:\\"). const FilePath& path(IsRootDirectory() ? *this : RemoveTrailingPathSeparator()); #else const FilePath& path(*this); #endif #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); const DWORD attributes = GetFileAttributes(unicode); delete [] unicode; if ((attributes != kInvalidFileAttributes) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) { result = true; } #else posix::StatStruct file_stat; result = posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat); #endif // GTEST_OS_WINDOWS_MOBILE return result; } // Returns true if pathname describes a root directory. (Windows has one // root directory per disk drive.) bool FilePath::IsRootDirectory() const { #if GTEST_OS_WINDOWS return pathname_.length() == 3 && IsAbsolutePath(); #else return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); #endif } // Returns true if pathname describes an absolute path. bool FilePath::IsAbsolutePath() const { const char* const name = pathname_.c_str(); #if GTEST_OS_WINDOWS return pathname_.length() >= 3 && ((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z')) && name[1] == ':' && IsPathSeparator(name[2]); #else return IsPathSeparator(name[0]); #endif } // Returns a pathname for a file that does not currently exist. The pathname // will be directory/base_name.extension or // directory/base_name_<number>.extension if directory/base_name.extension // already exists. The number will be incremented until a pathname is found // that does not already exist. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. // There could be a race condition if two or more processes are calling this // function at the same time -- they could both pick the same filename. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, const FilePath& base_name, const char* extension) { FilePath full_pathname; int number = 0; do { full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); } while (full_pathname.FileOrDirectoryExists()); return full_pathname; } // Returns true if FilePath ends with a path separator, which indicates that // it is intended to represent a directory. Returns false otherwise. // This does NOT check that a directory (or file) actually exists. bool FilePath::IsDirectory() const { return !pathname_.empty() && IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); } // Create directories so that path exists. Returns true if successful or if // the directories already exist; returns false if unable to create directories // for any reason. bool FilePath::CreateDirectoriesRecursively() const { if (!this->IsDirectory()) { return false; } if (pathname_.length() == 0 || this->DirectoryExists()) { return true; } const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); return parent.CreateDirectoriesRecursively() && this->CreateFolder(); } // Create the directory so that path exists. Returns true if successful or // if the directory already exists; returns false if unable to create the // directory for any reason, including if the parent directory does not // exist. Not named "CreateDirectory" because that's a macro on Windows. bool FilePath::CreateFolder() const { #if GTEST_OS_WINDOWS_MOBILE FilePath removed_sep(this->RemoveTrailingPathSeparator()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); int result = CreateDirectory(unicode, nullptr) ? 0 : -1; delete [] unicode; #elif GTEST_OS_WINDOWS int result = _mkdir(pathname_.c_str()); #else int result = mkdir(pathname_.c_str(), 0777); #endif // GTEST_OS_WINDOWS_MOBILE if (result == -1) { return this->DirectoryExists(); // An error is OK if the directory exists. } return true; // No error. } // If input name has a trailing separator character, remove it and return the // name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath FilePath::RemoveTrailingPathSeparator() const { return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1)) : *this; } // Removes any redundant separators that might be in the pathname. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". void FilePath::Normalize() { if (pathname_.c_str() == nullptr) { pathname_ = ""; return; } const char* src = pathname_.c_str(); char* const dest = new char[pathname_.length() + 1]; char* dest_ptr = dest; memset(dest_ptr, 0, pathname_.length() + 1); while (*src != '\0') { *dest_ptr = *src; if (!IsPathSeparator(*src)) { src++; } else { #if GTEST_HAS_ALT_PATH_SEP_ if (*dest_ptr == kAlternatePathSeparator) { *dest_ptr = kPathSeparator; } #endif while (IsPathSeparator(*src)) src++; } dest_ptr++; } *dest_ptr = '\0'; pathname_ = dest; delete[] dest; } } // namespace internal } // namespace testing // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // The Google C++ Testing and Mocking Framework (Google Test) // // This file implements just enough of the matcher interface to allow // EXPECT_DEATH and friends to accept a matcher argument. #include <string> namespace testing { // Constructs a matcher that matches a const std::string& whose value is // equal to s. Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); } // Constructs a matcher that matches a const std::string& whose value is // equal to s. Matcher<const std::string&>::Matcher(const char* s) { *this = Eq(std::string(s)); } // Constructs a matcher that matches a std::string whose value is equal to // s. Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); } // Constructs a matcher that matches a std::string whose value is equal to // s. Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); } #if GTEST_HAS_ABSL // Constructs a matcher that matches a const absl::string_view& whose value is // equal to s. Matcher<const absl::string_view&>::Matcher(const std::string& s) { *this = Eq(s); } // Constructs a matcher that matches a const absl::string_view& whose value is // equal to s. Matcher<const absl::string_view&>::Matcher(const char* s) { *this = Eq(std::string(s)); } // Constructs a matcher that matches a const absl::string_view& whose value is // equal to s. Matcher<const absl::string_view&>::Matcher(absl::string_view s) { *this = Eq(std::string(s)); } // Constructs a matcher that matches a absl::string_view whose value is equal to // s. Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); } // Constructs a matcher that matches a absl::string_view whose value is equal to // s. Matcher<absl::string_view>::Matcher(const char* s) { *this = Eq(std::string(s)); } // Constructs a matcher that matches a absl::string_view whose value is equal to // s. Matcher<absl::string_view>::Matcher(absl::string_view s) { *this = Eq(std::string(s)); } #endif // GTEST_HAS_ABSL } // namespace testing // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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 <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fstream> #include <memory> #if GTEST_OS_WINDOWS # include <windows.h> # include <io.h> # include <sys/stat.h> # include <map> // Used in ThreadLocal. # ifdef _MSC_VER # include <crtdbg.h> # endif // _MSC_VER #else # include <unistd.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC # include <mach/mach_init.h> # include <mach/task.h> # include <mach/vm_map.h> #endif // GTEST_OS_MAC #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ GTEST_OS_NETBSD || GTEST_OS_OPENBSD # include <sys/sysctl.h> # if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD # include <sys/user.h> # endif #endif #if GTEST_OS_QNX # include <devctl.h> # include <fcntl.h> # include <sys/procfs.h> #endif // GTEST_OS_QNX #if GTEST_OS_AIX # include <procinfo.h> # include <sys/types.h> #endif // GTEST_OS_AIX #if GTEST_OS_FUCHSIA # include <zircon/process.h> # include <zircon/syscalls.h> #endif // GTEST_OS_FUCHSIA namespace testing { namespace internal { #if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC and C++Builder do not provide a definition of STDERR_FILENO. const int kStdOutFileno = 1; const int kStdErrFileno = 2; #else const int kStdOutFileno = STDOUT_FILENO; const int kStdErrFileno = STDERR_FILENO; #endif // _MSC_VER #if GTEST_OS_LINUX namespace { template <typename T> T ReadProcFileField(const std::string& filename, int field) { std::string dummy; std::ifstream file(filename.c_str()); while (field-- > 0) { file >> dummy; } T output = 0; file >> output; return output; } } // namespace // Returns the number of active threads, or 0 when there is an error. size_t GetThreadCount() { const std::string filename = (Message() << "/proc/" << getpid() << "/stat").GetString(); return ReadProcFileField<int>(filename, 19); } #elif GTEST_OS_MAC size_t GetThreadCount() { const task_t task = mach_task_self(); mach_msg_type_number_t thread_count; thread_act_array_t thread_list; const kern_return_t status = task_threads(task, &thread_list, &thread_count); if (status == KERN_SUCCESS) { // task_threads allocates resources in thread_list and we need to free them // to avoid leaks. vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list), sizeof(thread_t) * thread_count); return static_cast<size_t>(thread_count); } else { return 0; } } #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ GTEST_OS_NETBSD #if GTEST_OS_NETBSD #undef KERN_PROC #define KERN_PROC KERN_PROC2 #define kinfo_proc kinfo_proc2 #endif #if GTEST_OS_DRAGONFLY #define KP_NLWP(kp) (kp.kp_nthreads) #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD #define KP_NLWP(kp) (kp.ki_numthreads) #elif GTEST_OS_NETBSD #define KP_NLWP(kp) (kp.p_nlwps) #endif // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. size_t GetThreadCount() { int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid(), #if GTEST_OS_NETBSD sizeof(struct kinfo_proc), 1, #endif }; u_int miblen = sizeof(mib) / sizeof(mib[0]); struct kinfo_proc info; size_t size = sizeof(info); if (sysctl(mib, miblen, &info, &size, NULL, 0)) { return 0; } return KP_NLWP(info); } #elif GTEST_OS_OPENBSD // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. size_t GetThreadCount() { int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_SHOW_THREADS, getpid(), sizeof(struct kinfo_proc), 0, }; u_int miblen = sizeof(mib) / sizeof(mib[0]); // get number of structs size_t size; if (sysctl(mib, miblen, NULL, &size, NULL, 0)) { return 0; } mib[5] = size / mib[4]; // populate array of structs struct kinfo_proc info[mib[5]]; if (sysctl(mib, miblen, &info, &size, NULL, 0)) { return 0; } // exclude empty members int nthreads = 0; for (int i = 0; i < size / mib[4]; i++) { if (info[i].p_tid != -1) nthreads++; } return nthreads; } #elif GTEST_OS_QNX // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. size_t GetThreadCount() { const int fd = open("/proc/self/as", O_RDONLY); if (fd < 0) { return 0; } procfs_info process_info; const int status = devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr); close(fd); if (status == EOK) { return static_cast<size_t>(process_info.num_threads); } else { return 0; } } #elif GTEST_OS_AIX size_t GetThreadCount() { struct procentry64 entry; pid_t pid = getpid(); int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1); if (status == 1) { return entry.pi_thcount; } else { return 0; } } #elif GTEST_OS_FUCHSIA size_t GetThreadCount() { int dummy_buffer; size_t avail; zx_status_t status = zx_object_get_info( zx_process_self(), ZX_INFO_PROCESS_THREADS, &dummy_buffer, 0, nullptr, &avail); if (status == ZX_OK) { return avail; } else { return 0; } } #else size_t GetThreadCount() { // There's no portable way to detect the number of threads, so we just // return 0 to indicate that we cannot detect it. return 0; } #endif // GTEST_OS_LINUX #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS void SleepMilliseconds(int n) { ::Sleep(n); } AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} AutoHandle::AutoHandle(Handle handle) : handle_(handle) {} AutoHandle::~AutoHandle() { Reset(); } AutoHandle::Handle AutoHandle::Get() const { return handle_; } void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); } void AutoHandle::Reset(HANDLE handle) { // Resetting with the same handle we already own is invalid. if (handle_ != handle) { if (IsCloseable()) { ::CloseHandle(handle_); } handle_ = handle; } else { GTEST_CHECK_(!IsCloseable()) << "Resetting a valid handle to itself is likely a programmer error " "and thus not allowed."; } } bool AutoHandle::IsCloseable() const { // Different Windows APIs may use either of these values to represent an // invalid handle. return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE; } Notification::Notification() : event_(::CreateEvent(nullptr, // Default security attributes. TRUE, // Do not reset automatically. FALSE, // Initially unset. nullptr)) { // Anonymous event. GTEST_CHECK_(event_.Get() != nullptr); } void Notification::Notify() { GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); } void Notification::WaitForNotification() { GTEST_CHECK_( ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); } Mutex::Mutex() : owner_thread_id_(0), type_(kDynamic), critical_section_init_phase_(0), critical_section_(new CRITICAL_SECTION) { ::InitializeCriticalSection(critical_section_); } Mutex::~Mutex() { // Static mutexes are leaked intentionally. It is not thread-safe to try // to clean them up. if (type_ == kDynamic) { ::DeleteCriticalSection(critical_section_); delete critical_section_; critical_section_ = nullptr; } } void Mutex::Lock() { ThreadSafeLazyInit(); ::EnterCriticalSection(critical_section_); owner_thread_id_ = ::GetCurrentThreadId(); } void Mutex::Unlock() { ThreadSafeLazyInit(); // We don't protect writing to owner_thread_id_ here, as it's the // caller's responsibility to ensure that the current thread holds the // mutex when this is called. owner_thread_id_ = 0; ::LeaveCriticalSection(critical_section_); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void Mutex::AssertHeld() { ThreadSafeLazyInit(); GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) << "The current thread is not holding the mutex @" << this; } namespace { #ifdef _MSC_VER // Use the RAII idiom to flag mem allocs that are intentionally never // deallocated. The motivation is to silence the false positive mem leaks // that are reported by the debug version of MS's CRT which can only detect // if an alloc is missing a matching deallocation. // Example: // MemoryIsNotDeallocated memory_is_not_deallocated; // critical_section_ = new CRITICAL_SECTION; // class MemoryIsNotDeallocated { public: MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT // doesn't report mem leak if there's no matching deallocation. _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF); } ~MemoryIsNotDeallocated() { // Restore the original _CRTDBG_ALLOC_MEM_DF flag _CrtSetDbgFlag(old_crtdbg_flag_); } private: int old_crtdbg_flag_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated); }; #endif // _MSC_VER } // namespace // Initializes owner_thread_id_ and critical_section_ in static mutexes. void Mutex::ThreadSafeLazyInit() { // Dynamic mutexes are initialized in the constructor. if (type_ == kStatic) { switch ( ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { case 0: // If critical_section_init_phase_ was 0 before the exchange, we // are the first to test it and need to perform the initialization. owner_thread_id_ = 0; { // Use RAII to flag that following mem alloc is never deallocated. #ifdef _MSC_VER MemoryIsNotDeallocated memory_is_not_deallocated; #endif // _MSC_VER critical_section_ = new CRITICAL_SECTION; } ::InitializeCriticalSection(critical_section_); // Updates the critical_section_init_phase_ to 2 to signal // initialization complete. GTEST_CHECK_(::InterlockedCompareExchange( &critical_section_init_phase_, 2L, 1L) == 1L); break; case 1: // Somebody else is already initializing the mutex; spin until they // are done. while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L, 2L) != 2L) { // Possibly yields the rest of the thread's time slice to other // threads. ::Sleep(0); } break; case 2: break; // The mutex is already initialized and ready for use. default: GTEST_CHECK_(false) << "Unexpected value of critical_section_init_phase_ " << "while initializing a static mutex."; } } } namespace { class ThreadWithParamSupport : public ThreadWithParamBase { public: static HANDLE CreateThread(Runnable* runnable, Notification* thread_can_start) { ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); DWORD thread_id; HANDLE thread_handle = ::CreateThread( nullptr, // Default security. 0, // Default stack size. &ThreadWithParamSupport::ThreadMain, param, // Parameter to ThreadMainStatic 0x0, // Default creation flags. &thread_id); // Need a valid pointer for the call to work under Win98. GTEST_CHECK_(thread_handle != nullptr) << "CreateThread failed with error " << ::GetLastError() << "."; if (thread_handle == nullptr) { delete param; } return thread_handle; } private: struct ThreadMainParam { ThreadMainParam(Runnable* runnable, Notification* thread_can_start) : runnable_(runnable), thread_can_start_(thread_can_start) { } std::unique_ptr<Runnable> runnable_; // Does not own. Notification* thread_can_start_; }; static DWORD WINAPI ThreadMain(void* ptr) { // Transfers ownership. std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr)); if (param->thread_can_start_ != nullptr) param->thread_can_start_->WaitForNotification(); param->runnable_->Run(); return 0; } // Prohibit instantiation. ThreadWithParamSupport(); GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport); }; } // namespace ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start) : thread_(ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) { } ThreadWithParamBase::~ThreadWithParamBase() { Join(); } void ThreadWithParamBase::Join() { GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) << "Failed to join the thread with error " << ::GetLastError() << "."; } // Maps a thread to a set of ThreadIdToThreadLocals that have values // instantiated on that thread and notifies them when the thread exits. A // ThreadLocal instance is expected to persist until all threads it has // values on have terminated. class ThreadLocalRegistryImpl { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { DWORD current_thread = ::GetCurrentThreadId(); MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(current_thread); if (thread_local_pos == thread_to_thread_locals->end()) { thread_local_pos = thread_to_thread_locals->insert( std::make_pair(current_thread, ThreadLocalValues())).first; StartWatcherThreadFor(current_thread); } ThreadLocalValues& thread_local_values = thread_local_pos->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos == thread_local_values.end()) { value_pos = thread_local_values .insert(std::make_pair( thread_local_instance, std::shared_ptr<ThreadLocalValueHolderBase>( thread_local_instance->NewValueForCurrentThread()))) .first; } return value_pos->second.get(); } static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance) { std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders; // Clean up the ThreadLocalValues data structure while holding the lock, but // defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); for (ThreadIdToThreadLocals::iterator it = thread_to_thread_locals->begin(); it != thread_to_thread_locals->end(); ++it) { ThreadLocalValues& thread_local_values = it->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos != thread_local_values.end()) { value_holders.push_back(value_pos->second); thread_local_values.erase(value_pos); // This 'if' can only be successful at most once, so theoretically we // could break out of the loop here, but we don't bother doing so. } } } // Outside the lock, let the destructor for 'value_holders' deallocate the // ThreadLocalValueHolderBases. } static void OnThreadExit(DWORD thread_id) { GTEST_CHECK_(thread_id != 0) << ::GetLastError(); std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders; // Clean up the ThreadIdToThreadLocals data structure while holding the // lock, but defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(thread_id); if (thread_local_pos != thread_to_thread_locals->end()) { ThreadLocalValues& thread_local_values = thread_local_pos->second; for (ThreadLocalValues::iterator value_pos = thread_local_values.begin(); value_pos != thread_local_values.end(); ++value_pos) { value_holders.push_back(value_pos->second); } thread_to_thread_locals->erase(thread_local_pos); } } // Outside the lock, let the destructor for 'value_holders' deallocate the // ThreadLocalValueHolderBases. } private: // In a particular thread, maps a ThreadLocal object to its value. typedef std::map<const ThreadLocalBase*, std::shared_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues; // Stores all ThreadIdToThreadLocals having values in a thread, indexed by // thread's ID. typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals; // Holds the thread id and thread handle that we pass from // StartWatcherThreadFor to WatcherThreadFunc. typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle; static void StartWatcherThreadFor(DWORD thread_id) { // The returned handle will be kept in thread_map and closed by // watcher_thread in WatcherThreadFunc. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id); GTEST_CHECK_(thread != nullptr); // We need to pass a valid thread ID pointer into CreateThread for it // to work correctly under Win98. DWORD watcher_thread_id; HANDLE watcher_thread = ::CreateThread( nullptr, // Default security. 0, // Default stack size &ThreadLocalRegistryImpl::WatcherThreadFunc, reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)), CREATE_SUSPENDED, &watcher_thread_id); GTEST_CHECK_(watcher_thread != nullptr); // Give the watcher thread the same priority as ours to avoid being // blocked by it. ::SetThreadPriority(watcher_thread, ::GetThreadPriority(::GetCurrentThread())); ::ResumeThread(watcher_thread); ::CloseHandle(watcher_thread); } // Monitors exit from a given thread and notifies those // ThreadIdToThreadLocals about thread termination. static DWORD WINAPI WatcherThreadFunc(LPVOID param) { const ThreadIdAndHandle* tah = reinterpret_cast<const ThreadIdAndHandle*>(param); GTEST_CHECK_( ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); OnThreadExit(tah->first); ::CloseHandle(tah->second); delete tah; return 0; } // Returns map of thread local instances. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { mutex_.AssertHeld(); #ifdef _MSC_VER MemoryIsNotDeallocated memory_is_not_deallocated; #endif // _MSC_VER static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals(); return map; } // Protects access to GetThreadLocalsMapLocked() and its return value. static Mutex mutex_; // Protects access to GetThreadMapLocked() and its return value. static Mutex thread_map_mutex_; }; Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { return ThreadLocalRegistryImpl::GetValueOnCurrentThread( thread_local_instance); } void ThreadLocalRegistry::OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance) { ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); } #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS #if GTEST_USES_POSIX_RE // Implements RE. Currently only needed for death tests. RE::~RE() { if (is_valid_) { // regfree'ing an invalid regex might crash because the content // of the regex is undefined. Since the regex's are essentially // the same, one cannot be valid (or invalid) without the other // being so too. regfree(&partial_regex_); regfree(&full_regex_); } free(const_cast<char*>(pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.full_regex_, str, 1, &match, 0) == 0; } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = posix::StrDup(regex); // Reserves enough bytes to hold the regular expression used for a // full match. const size_t full_regex_len = strlen(regex) + 10; char* const full_pattern = new char[full_regex_len]; snprintf(full_pattern, full_regex_len, "^(%s)$", regex); is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; // We want to call regcomp(&partial_regex_, ...) even if the // previous expression returns false. Otherwise partial_regex_ may // not be properly initialized can may cause trouble when it's // freed. // // Some implementation of POSIX regex (e.g. on at least some // versions of Cygwin) doesn't accept the empty string as a valid // regex. We change it to an equivalent form "()" to be safe. if (is_valid_) { const char* const partial_regex = (*regex == '\0') ? "()" : regex; is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; } EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex << "\" is not a valid POSIX Extended regular expression."; delete[] full_pattern; } #elif GTEST_USES_SIMPLE_RE // Returns true iff ch appears anywhere in str (excluding the // terminating '\0' character). bool IsInSet(char ch, const char* str) { return ch != '\0' && strchr(str, ch) != nullptr; } // Returns true iff ch belongs to the given classification. Unlike // similar functions in <ctype.h>, these aren't affected by the // current locale. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } bool IsAsciiPunct(char ch) { return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); } bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } bool IsAsciiWordChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; } // Returns true iff "\\c" is a supported escape sequence. bool IsValidEscape(char c) { return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); } // Returns true iff the given atom (specified by escaped and pattern) // matches ch. The result is undefined if the atom is invalid. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { case 'd': return IsAsciiDigit(ch); case 'D': return !IsAsciiDigit(ch); case 'f': return ch == '\f'; case 'n': return ch == '\n'; case 'r': return ch == '\r'; case 's': return IsAsciiWhiteSpace(ch); case 'S': return !IsAsciiWhiteSpace(ch); case 't': return ch == '\t'; case 'v': return ch == '\v'; case 'w': return IsAsciiWordChar(ch); case 'W': return !IsAsciiWordChar(ch); } return IsAsciiPunct(pattern_char) && pattern_char == ch; } return (pattern_char == '.' && ch != '\n') || pattern_char == ch; } // Helper function used by ValidateRegex() to format error messages. static std::string FormatRegexSyntaxError(const char* regex, int index) { return (Message() << "Syntax error at index " << index << " in simple regular expression \"" << regex << "\": ").GetString(); } // Generates non-fatal failures and returns false if regex is invalid; // otherwise returns true. bool ValidateRegex(const char* regex) { if (regex == nullptr) { ADD_FAILURE() << "NULL is not a valid simple regular expression."; return false; } bool is_valid = true; // True iff ?, *, or + can follow the previous atom. bool prev_repeatable = false; for (int i = 0; regex[i]; i++) { if (regex[i] == '\\') { // An escape sequence i++; if (regex[i] == '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "'\\' cannot appear at the end."; return false; } if (!IsValidEscape(regex[i])) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "invalid escape sequence \"\\" << regex[i] << "\"."; is_valid = false; } prev_repeatable = true; } else { // Not an escape sequence. const char ch = regex[i]; if (ch == '^' && i > 0) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'^' can only appear at the beginning."; is_valid = false; } else if (ch == '$' && regex[i + 1] != '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'$' can only appear at the end."; is_valid = false; } else if (IsInSet(ch, "()[]{}|")) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' is unsupported."; is_valid = false; } else if (IsRepeat(ch) && !prev_repeatable) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' can only follow a repeatable token."; is_valid = false; } prev_repeatable = !IsInSet(ch, "^$?*+"); } } return is_valid; } // Matches a repeated regex atom followed by a valid simple regular // expression. The regex atom is defined as c if escaped is false, // or \c otherwise. repeat is the repetition meta character (?, *, // or +). The behavior is undefined if str contains too many // characters to be indexable by size_t, in which case the test will // probably time out anyway. We are fine with this limitation as // std::string has it too. bool MatchRepetitionAndRegexAtHead( bool escaped, char c, char repeat, const char* regex, const char* str) { const size_t min_count = (repeat == '+') ? 1 : 0; const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1; // We cannot call numeric_limits::max() as it conflicts with the // max() macro on Windows. for (size_t i = 0; i <= max_count; ++i) { // We know that the atom matches each of the first i characters in str. if (i >= min_count && MatchRegexAtHead(regex, str + i)) { // We have enough matches at the head, and the tail matches too. // Since we only care about *whether* the pattern matches str // (as opposed to *how* it matches), there is no need to find a // greedy match. return true; } if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false; } return false; } // Returns true iff regex matches a prefix of str. regex must be a // valid simple regular expression and not start with "^", or the // result is undefined. bool MatchRegexAtHead(const char* regex, const char* str) { if (*regex == '\0') // An empty regex matches a prefix of anything. return true; // "$" only matches the end of a string. Note that regex being // valid guarantees that there's nothing after "$" in it. if (*regex == '$') return *str == '\0'; // Is the first thing in regex an escape sequence? const bool escaped = *regex == '\\'; if (escaped) ++regex; if (IsRepeat(regex[1])) { // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // here's an indirect recursion. It terminates as the regex gets // shorter in each recursion. return MatchRepetitionAndRegexAtHead( escaped, regex[0], regex[1], regex + 2, str); } else { // regex isn't empty, isn't "$", and doesn't start with a // repetition. We match the first atom of regex with the first // character of str and recurse. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && MatchRegexAtHead(regex + 1, str + 1); } } // Returns true iff regex matches any substring of str. regex must be // a valid simple regular expression, or the result is undefined. // // The algorithm is recursive, but the recursion depth doesn't exceed // the regex length, so we won't need to worry about running out of // stack space normally. In rare cases the time complexity can be // exponential with respect to the regex length + the string length, // but usually it's must faster (often close to linear). bool MatchRegexAnywhere(const char* regex, const char* str) { if (regex == nullptr || str == nullptr) return false; if (*regex == '^') return MatchRegexAtHead(regex + 1, str); // A successful match can be anywhere in str. do { if (MatchRegexAtHead(regex, str)) return true; } while (*str++ != '\0'); return false; } // Implements the RE class. RE::~RE() { free(const_cast<char*>(pattern_)); free(const_cast<char*>(full_pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = full_pattern_ = nullptr; if (regex != nullptr) { pattern_ = posix::StrDup(regex); } is_valid_ = ValidateRegex(regex); if (!is_valid_) { // No need to calculate the full pattern when the regex is invalid. return; } const size_t len = strlen(regex); // Reserves enough bytes to hold the regular expression used for a // full match: we need space to prepend a '^', append a '$', and // terminate the string with '\0'. char* buffer = static_cast<char*>(malloc(len + 3)); full_pattern_ = buffer; if (*regex != '^') *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. // We don't use snprintf or strncpy, as they trigger a warning when // compiled with VC++ 8.0. memcpy(buffer, regex, len); buffer += len; if (len == 0 || regex[len - 1] != '$') *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. *buffer = '\0'; } #endif // GTEST_USES_POSIX_RE const char kUnknownFile[] = "unknown file"; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { const std::string file_name(file == nullptr ? kUnknownFile : file); if (line < 0) { return file_name + ":"; } #ifdef _MSC_VER return file_name + "(" + StreamableToString(line) + "):"; #else return file_name + ":" + StreamableToString(line) + ":"; #endif // _MSC_VER } // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. // Note that FormatCompilerIndependentFileLocation() does NOT append colon // to the file location it produces, unlike FormatFileLocation(). GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( const char* file, int line) { const std::string file_name(file == nullptr ? kUnknownFile : file); if (line < 0) return file_name; else return file_name + ":" + StreamableToString(line); } GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) : severity_(severity) { const char* const marker = severity == GTEST_INFO ? "[ INFO ]" : severity == GTEST_WARNING ? "[WARNING]" : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; GetStream() << ::std::endl << marker << " " << FormatFileLocation(file, line).c_str() << ": "; } // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. GTestLog::~GTestLog() { GetStream() << ::std::endl; if (severity_ == GTEST_FATAL) { fflush(stderr); posix::Abort(); } } // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) GTEST_DISABLE_MSC_DEPRECATED_PUSH_() #if GTEST_HAS_STREAM_REDIRECTION // Object that captures an output stream (stdout/stderr). class CapturedStream { public: // The ctor redirects the stream to a temporary file. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { # if GTEST_OS_WINDOWS char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, // Generate unique file name. temp_file_path); GTEST_CHECK_(success != 0) << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; # else // There's no guarantee that a test has write access to the current // directory, so we create the temporary file in the /tmp directory // instead. We use /tmp on most systems, and /sdcard on Android. // That's because Android doesn't have /tmp. # if GTEST_OS_LINUX_ANDROID // Note: Android applications are expected to call the framework's // Context.getExternalStorageDirectory() method through JNI to get // the location of the world-writable SD Card directory. However, // this requires a Context handle, which cannot be retrieved // globally from native code. Doing so also precludes running the // code as part of a regular standalone executable, which doesn't // run in a Dalvik process (e.g. when running it through 'adb shell'). // // The location /sdcard is directly accessible from native code // and is the only location (unofficially) supported by the Android // team. It's generally a symlink to the real SD Card mount point // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or // other OEM-customized locations. Never rely on these, and always // use /sdcard. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; # else char name_template[] = "/tmp/captured_stream.XXXXXX"; # endif // GTEST_OS_LINUX_ANDROID const int captured_fd = mkstemp(name_template); filename_ = name_template; # endif // GTEST_OS_WINDOWS fflush(nullptr); dup2(captured_fd, fd_); close(captured_fd); } ~CapturedStream() { remove(filename_.c_str()); } std::string GetCapturedString() { if (uncaptured_fd_ != -1) { // Restores the original stream. fflush(nullptr); dup2(uncaptured_fd_, fd_); close(uncaptured_fd_); uncaptured_fd_ = -1; } FILE* const file = posix::FOpen(filename_.c_str(), "r"); const std::string content = ReadEntireFile(file); posix::FClose(file); return content; } private: const int fd_; // A stream to capture. int uncaptured_fd_; // Name of the temporary file holding the stderr output. ::std::string filename_; GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); }; GTEST_DISABLE_MSC_DEPRECATED_POP_() static CapturedStream* g_captured_stderr = nullptr; static CapturedStream* g_captured_stdout = nullptr; // Starts capturing an output stream (stdout/stderr). static void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { if (*stream != nullptr) { GTEST_LOG_(FATAL) << "Only one " << stream_name << " capturer can exist at a time."; } *stream = new CapturedStream(fd); } // Stops capturing the output stream and returns the captured string. static std::string GetCapturedStream(CapturedStream** captured_stream) { const std::string content = (*captured_stream)->GetCapturedString(); delete *captured_stream; *captured_stream = nullptr; return content; } // Starts capturing stdout. void CaptureStdout() { CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); } // Starts capturing stderr. void CaptureStderr() { CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); } // Stops capturing stdout and returns the captured string. std::string GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } // Stops capturing stderr and returns the captured string. std::string GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } #endif // GTEST_HAS_STREAM_REDIRECTION size_t GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast<size_t>(ftell(file)); } std::string ReadEntireFile(FILE* file) { const size_t file_size = GetFileSize(file); char* const buffer = new char[file_size]; size_t bytes_last_read = 0; // # of bytes read in the last fread() size_t bytes_read = 0; // # of bytes read so far fseek(file, 0, SEEK_SET); // Keeps reading the file until we cannot read further or the // pre-determined file size is reached. do { bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); const std::string content(buffer, bytes_read); delete[] buffer; return content; } #if GTEST_HAS_DEATH_TEST static const std::vector<std::string>* g_injected_test_argvs = nullptr; // Owned. std::vector<std::string> GetInjectableArgvs() { if (g_injected_test_argvs != nullptr) { return *g_injected_test_argvs; } return GetArgvs(); } void SetInjectableArgvs(const std::vector<std::string>* new_argvs) { if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs; g_injected_test_argvs = new_argvs; } void SetInjectableArgvs(const std::vector<std::string>& new_argvs) { SetInjectableArgvs( new std::vector<std::string>(new_argvs.begin(), new_argvs.end())); } void ClearInjectableArgvs() { delete g_injected_test_argvs; g_injected_test_argvs = nullptr; } #endif // GTEST_HAS_DEATH_TEST #if GTEST_OS_WINDOWS_MOBILE namespace posix { void Abort() { DebugBreak(); TerminateProcess(GetCurrentProcess(), 1); } } // namespace posix #endif // GTEST_OS_WINDOWS_MOBILE // Returns the name of the environment variable corresponding to the // given flag. For example, FlagToEnvVar("foo") will return // "GTEST_FOO" in the open-source version. static std::string FlagToEnvVar(const char* flag) { const std::string full_flag = (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); Message env_var; for (size_t i = 0; i != full_flag.length(); i++) { env_var << ToUpper(full_flag.c_str()[i]); } return env_var.GetString(); } // Parses 'str' for a 32-bit signed integer. If successful, writes // the result to *value and returns true; otherwise leaves *value // unchanged and returns false. bool ParseInt32(const Message& src_text, const char* str, Int32* value) { // Parses the environment variable as a decimal integer. char* end = nullptr; const long long_value = strtol(str, &end, 10); // NOLINT // Has strtol() consumed all characters in the string? if (*end != '\0') { // No - an invalid character was encountered. Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value \"" << str << "\".\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } // Is the parsed value in the range of an Int32? const Int32 result = static_cast<Int32>(long_value); if (long_value == LONG_MAX || long_value == LONG_MIN || // The parsed value overflows as a long. (strtol() returns // LONG_MAX or LONG_MIN when the input overflows.) result != long_value // The parsed value overflows as an Int32. ) { Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value " << str << ", which overflows.\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } *value = result; return true; } // Reads and returns the Boolean environment variable corresponding to // the given flag; if it's not set, returns default_value. // // The value is considered true iff it's not "0". bool BoolFromGTestEnv(const char* flag, bool default_value) { #if defined(GTEST_GET_BOOL_FROM_ENV_) return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); #else const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); return string_value == nullptr ? default_value : strcmp(string_value, "0") != 0; #endif // defined(GTEST_GET_BOOL_FROM_ENV_) } // Reads and returns a 32-bit integer stored in the environment // variable corresponding to the given flag; if it isn't set or // doesn't represent a valid 32-bit integer, returns default_value. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { #if defined(GTEST_GET_INT32_FROM_ENV_) return GTEST_GET_INT32_FROM_ENV_(flag, default_value); #else const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); if (string_value == nullptr) { // The environment variable is not set. return default_value; } Int32 result = default_value; if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, &result)) { printf("The default value %s is used.\n", (Message() << default_value).GetString().c_str()); fflush(stdout); return default_value; } return result; #endif // defined(GTEST_GET_INT32_FROM_ENV_) } // As a special case for the 'output' flag, if GTEST_OUTPUT is not // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build // system. The value of XML_OUTPUT_FILE is a filename without the // "xml:" prefix of GTEST_OUTPUT. // Note that this is meant to be called at the call site so it does // not check that the flag is 'output' // In essence this checks an env variable called XML_OUTPUT_FILE // and if it is set we prepend "xml:" to its value, if it not set we return "" std::string OutputFlagAlsoCheckEnvVar(){ std::string default_value_for_output_flag = ""; const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE"); if (nullptr != xml_output_file_env) { default_value_for_output_flag = std::string("xml:") + xml_output_file_env; } return default_value_for_output_flag; } // Reads and returns the string environment variable corresponding to // the given flag; if it's not set, returns default_value. const char* StringFromGTestEnv(const char* flag, const char* default_value) { #if defined(GTEST_GET_STRING_FROM_ENV_) return GTEST_GET_STRING_FROM_ENV_(flag, default_value); #else const std::string env_var = FlagToEnvVar(flag); const char* const value = posix::GetEnv(env_var.c_str()); return value == nullptr ? default_value : value; #endif // defined(GTEST_GET_STRING_FROM_ENV_) } } // namespace internal } // namespace testing // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // Google Test - The Google C++ Testing and Mocking Framework // // This file implements a universal value printer that can print a // value of any type T: // // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr); // // It uses the << operator when possible, and prints the bytes in the // object otherwise. A user can override its behavior for a class // type Foo by defining either operator<<(::std::ostream&, const Foo&) // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that // defines Foo. #include <stdio.h> #include <cctype> #include <cwchar> #include <ostream> // NOLINT #include <string> namespace testing { namespace { using ::std::ostream; // Prints a segment of bytes in the given object. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, size_t count, ostream* os) { char text[5] = ""; for (size_t i = 0; i != count; i++) { const size_t j = start + i; if (i != 0) { // Organizes the bytes into groups of 2 for easy parsing by // human. if ((j % 2) == 0) *os << ' '; else *os << '-'; } GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); *os << text; } } // Prints the bytes in the given value to the given ostream. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, ostream* os) { // Tells the user how big the object is. *os << count << "-byte object <"; const size_t kThreshold = 132; const size_t kChunkSize = 64; // If the object size is bigger than kThreshold, we'll have to omit // some details by printing only the first and the last kChunkSize // bytes. if (count < kThreshold) { PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); } else { PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); *os << " ... "; // Rounds up to 2-byte boundary. const size_t resume_pos = (count - kChunkSize + 1)/2*2; PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); } *os << ">"; } } // namespace namespace internal2 { // Delegates to PrintBytesInObjectToImpl() to print the bytes in the // given object. The delegation simplifies the implementation, which // uses the << operator and thus is easier done outside of the // ::testing::internal namespace, which contains a << operator that // sometimes conflicts with the one in STL. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ostream* os) { PrintBytesInObjectToImpl(obj_bytes, count, os); } } // namespace internal2 namespace internal { // Depending on the value of a char (or wchar_t), we print it in one // of three formats: // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as a hexadecimal escape sequence (e.g. '\x7F'), or // - as a special escape sequence (e.g. '\r', '\n'). enum CharFormat { kAsIs, kHexEscape, kSpecialEscape }; // Returns true if c is a printable ASCII character. We test the // value of c directly instead of calling isprint(), which is buggy on // Windows Mobile. inline bool IsPrintableAscii(wchar_t c) { return 0x20 <= c && c <= 0x7E; } // Prints a wide or narrow char c as a character literal without the // quotes, escaping it when necessary; returns how c was formatted. // The template argument UnsignedChar is the unsigned version of Char, // which is the type of c. template <typename UnsignedChar, typename Char> static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { switch (static_cast<wchar_t>(c)) { case L'\0': *os << "\\0"; break; case L'\'': *os << "\\'"; break; case L'\\': *os << "\\\\"; break; case L'\a': *os << "\\a"; break; case L'\b': *os << "\\b"; break; case L'\f': *os << "\\f"; break; case L'\n': *os << "\\n"; break; case L'\r': *os << "\\r"; break; case L'\t': *os << "\\t"; break; case L'\v': *os << "\\v"; break; default: if (IsPrintableAscii(c)) { *os << static_cast<char>(c); return kAsIs; } else { ostream::fmtflags flags = os->flags(); *os << "\\x" << std::hex << std::uppercase << static_cast<int>(static_cast<UnsignedChar>(c)); os->flags(flags); return kHexEscape; } } return kSpecialEscape; } // Prints a wchar_t c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { switch (c) { case L'\'': *os << "'"; return kAsIs; case L'"': *os << "\\\""; return kSpecialEscape; default: return PrintAsCharLiteralTo<wchar_t>(c, os); } } // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { return PrintAsStringLiteralTo( static_cast<wchar_t>(static_cast<unsigned char>(c)), os); } // Prints a wide or narrow character c and its code. '\0' is printed // as "'\\0'", other unprintable characters are also properly escaped // using the standard C++ escape sequence. The template argument // UnsignedChar is the unsigned version of Char, which is the type of c. template <typename UnsignedChar, typename Char> void PrintCharAndCodeTo(Char c, ostream* os) { // First, print c as a literal in the most readable form we can find. *os << ((sizeof(c) > 1) ? "L'" : "'"); const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os); *os << "'"; // To aid user debugging, we also print c's code in decimal, unless // it's 0 (in which case c was printed as '\\0', making the code // obvious). if (c == 0) return; *os << " (" << static_cast<int>(c); // For more convenience, we print c's code again in hexadecimal, // unless c was already printed in the form '\x##' or the code is in // [1, 9]. if (format == kHexEscape || (1 <= c && c <= 9)) { // Do nothing. } else { *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c)); } *os << ")"; } void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo<unsigned char>(c, os); } void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo<unsigned char>(c, os); } // Prints a wchar_t as a symbol if it is printable or as its internal // code otherwise and also as its code. L'\0' is printed as "L'\\0'". void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo<wchar_t>(wc, os); } // Prints the given array of characters to the ostream. CharType must be either // char or wchar_t. // The array starts at begin, the length is len, it may include '\0' characters // and may not be NUL-terminated. template <typename CharType> GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat PrintCharsAsStringTo( const CharType* begin, size_t len, ostream* os) { const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; *os << kQuoteBegin; bool is_previous_hex = false; CharFormat print_format = kAsIs; for (size_t index = 0; index < len; ++index) { const CharType cur = begin[index]; if (is_previous_hex && IsXDigit(cur)) { // Previous character is of '\x..' form and this character can be // interpreted as another hexadecimal digit in its number. Break string to // disambiguate. *os << "\" " << kQuoteBegin; } is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; // Remember if any characters required hex escaping. if (is_previous_hex) { print_format = kHexEscape; } } *os << "\""; return print_format; } // Prints a (const) char/wchar_t array of 'len' elements, starting at address // 'begin'. CharType must be either char or wchar_t. template <typename CharType> GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void UniversalPrintCharArray( const CharType* begin, size_t len, ostream* os) { // The code // const char kFoo[] = "foo"; // generates an array of 4, not 3, elements, with the last one being '\0'. // // Therefore when printing a char array, we don't print the last element if // it's '\0', such that the output matches the string literal as it's // written in the source code. if (len > 0 && begin[len - 1] == '\0') { PrintCharsAsStringTo(begin, len - 1, os); return; } // If, however, the last element in the array is not '\0', e.g. // const char kFoo[] = { 'f', 'o', 'o' }; // we must print the entire array. We also print a message to indicate // that the array is not NUL-terminated. PrintCharsAsStringTo(begin, len, os); *os << " (no terminating NUL)"; } // Prints a (const) char array of 'len' elements, starting at address 'begin'. void UniversalPrintArray(const char* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } // Prints a (const) wchar_t array of 'len' elements, starting at address // 'begin'. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } // Prints the given C string to the ostream. void PrintTo(const char* s, ostream* os) { if (s == nullptr) { *os << "NULL"; } else { *os << ImplicitCast_<const void*>(s) << " pointing to "; PrintCharsAsStringTo(s, strlen(s), os); } } // MSVC compiler can be configured to define whar_t as a typedef // of unsigned short. Defining an overload for const wchar_t* in that case // would cause pointers to unsigned shorts be printed as wide strings, // possibly accessing more memory than intended and causing invalid // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when // wchar_t is implemented as a native type. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) // Prints the given wide C string to the ostream. void PrintTo(const wchar_t* s, ostream* os) { if (s == nullptr) { *os << "NULL"; } else { *os << ImplicitCast_<const void*>(s) << " pointing to "; PrintCharsAsStringTo(s, wcslen(s), os); } } #endif // wchar_t is native namespace { bool ContainsUnprintableControlCodes(const char* str, size_t length) { const unsigned char *s = reinterpret_cast<const unsigned char *>(str); for (size_t i = 0; i < length; i++) { unsigned char ch = *s++; if (std::iscntrl(ch)) { switch (ch) { case '\t': case '\n': case '\r': break; default: return true; } } } return false; } bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; } bool IsValidUTF8(const char* str, size_t length) { const unsigned char *s = reinterpret_cast<const unsigned char *>(str); for (size_t i = 0; i < length;) { unsigned char lead = s[i++]; if (lead <= 0x7f) { continue; // single-byte character (ASCII) 0..7F } if (lead < 0xc2) { return false; // trail byte or non-shortest form } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) { ++i; // 2-byte character } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length && IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) && // check for non-shortest form and surrogate (lead != 0xe0 || s[i] >= 0xa0) && (lead != 0xed || s[i] < 0xa0)) { i += 2; // 3-byte character } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length && IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) && IsUTF8TrailByte(s[i + 2]) && // check for non-shortest form (lead != 0xf0 || s[i] >= 0x90) && (lead != 0xf4 || s[i] < 0x90)) { i += 3; // 4-byte character } else { return false; } } return true; } void ConditionalPrintAsText(const char* str, size_t length, ostream* os) { if (!ContainsUnprintableControlCodes(str, length) && IsValidUTF8(str, length)) { *os << "\n As Text: \"" << str << "\""; } } } // anonymous namespace void PrintStringTo(const ::std::string& s, ostream* os) { if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) { if (GTEST_FLAG(print_utf8)) { ConditionalPrintAsText(s.data(), s.size(), os); } } } #if GTEST_HAS_STD_WSTRING void PrintWideStringTo(const ::std::wstring& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_STD_WSTRING } // namespace internal } // namespace testing // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // // The Google C++ Testing and Mocking Framework (Google Test) namespace testing { using internal::GetUnitTestImpl; // Gets the summary of the failure message by omitting the stack trace // in it. std::string TestPartResult::ExtractSummary(const char* message) { const char* const stack_trace = strstr(message, internal::kStackTraceMarker); return stack_trace == nullptr ? message : std::string(message, stack_trace); } // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { return os << result.file_name() << ":" << result.line_number() << ": " << (result.type() == TestPartResult::kSuccess ? "Success" : result.type() == TestPartResult::kSkip ? "Skipped" : result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : "Non-fatal failure") << ":\n" << result.message() << std::endl; } // Appends a TestPartResult to the array. void TestPartResultArray::Append(const TestPartResult& result) { array_.push_back(result); } // Returns the TestPartResult at the given index (0-based). const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { if (index < 0 || index >= size()) { printf("\nInvalid index (%d) into TestPartResultArray.\n", index); internal::posix::Abort(); } return array_[index]; } // Returns the number of TestPartResult objects in the array. int TestPartResultArray::size() const { return static_cast<int>(array_.size()); } namespace internal { HasNewFatalFailureHelper::HasNewFatalFailureHelper() : has_new_fatal_failure_(false), original_reporter_(GetUnitTestImpl()-> GetTestPartResultReporterForCurrentThread()) { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); } HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( original_reporter_); } void HasNewFatalFailureHelper::ReportTestPartResult( const TestPartResult& result) { if (result.fatally_failed()) has_new_fatal_failure_ = true; original_reporter_->ReportTestPartResult(result); } } // namespace internal } // namespace testing // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. namespace testing { namespace internal { #if GTEST_HAS_TYPED_TEST_P // Skips to the first non-space char in str. Returns an empty string if str // contains only whitespace characters. static const char* SkipSpaces(const char* str) { while (IsSpace(*str)) str++; return str; } static std::vector<std::string> SplitIntoTestNames(const char* src) { std::vector<std::string> name_vec; src = SkipSpaces(src); for (; src != nullptr; src = SkipComma(src)) { name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); } return name_vec; } // Verifies that registered_tests match the test names in // registered_tests_; returns registered_tests if successful, or // aborts the program otherwise. const char* TypedTestSuitePState::VerifyRegisteredTestNames( const char* file, int line, const char* registered_tests) { typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests); Message errors; std::set<std::string> tests; for (std::vector<std::string>::const_iterator name_it = name_vec.begin(); name_it != name_vec.end(); ++name_it) { const std::string& name = *name_it; if (tests.count(name) != 0) { errors << "Test " << name << " is listed more than once.\n"; continue; } bool found = false; for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (name == it->first) { found = true; break; } } if (found) { tests.insert(name); } else { errors << "No test named " << name << " can be found in this test suite.\n"; } } for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (tests.count(it->first) == 0) { errors << "You forgot to list test " << it->first << ".\n"; } } const std::string& errors_str = errors.GetString(); if (errors_str != "") { fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); fflush(stderr); posix::Abort(); } return registered_tests; } #endif // GTEST_HAS_TYPED_TEST_P } // namespace internal } // namespace testing
; A123865: a(n) = n^4 - 1. ; 0,15,80,255,624,1295,2400,4095,6560,9999,14640,20735,28560,38415,50624,65535,83520,104975,130320,159999,194480,234255,279840,331775,390624,456975,531440,614655,707280,809999,923520,1048575,1185920,1336335,1500624,1679615,1874160,2085135,2313440,2559999,2825760,3111695,3418800,3748095,4100624,4477455,4879680,5308415,5764800,6249999,6765200,7311615,7890480,8503055,9150624,9834495,10556000,11316495,12117360,12959999,13845840,14776335,15752960,16777215,17850624,18974735,20151120,21381375,22667120 add $0,1 pow $0,4 sub $0,1
.code mul64u proc mov rax,rcx imul rax,rdx ret mul64u endp end
; void *zx_pxy2saddr(uchar x, uchar y) SECTION code_clib SECTION code_arch PUBLIC zx_pxy2saddr EXTERN l0_zx_pxy2saddr_callee zx_pxy2saddr: pop af pop de pop hl push hl push de push af jp l0_zx_pxy2saddr_callee
; A153784: 4 times heptagonal numbers: 2n(5n-3). ; 0,4,28,72,136,220,324,448,592,756,940,1144,1368,1612,1876,2160,2464,2788,3132,3496,3880,4284,4708,5152,5616,6100,6604,7128,7672,8236,8820,9424,10048,10692,11356,12040,12744,13468,14212,14976,15760,16564,17388,18232,19096,19980,20884,21808,22752,23716,24700,25704,26728,27772,28836,29920,31024,32148,33292,34456,35640,36844,38068,39312,40576,41860,43164,44488,45832,47196,48580,49984,51408,52852,54316,55800,57304,58828,60372,61936,63520,65124,66748,68392,70056,71740,73444,75168,76912,78676,80460,82264,84088,85932,87796,89680,91584,93508,95452,97416,99400,101404,103428,105472,107536,109620,111724,113848,115992,118156,120340,122544,124768,127012,129276,131560,133864,136188,138532,140896,143280,145684,148108,150552,153016,155500,158004,160528,163072,165636,168220,170824,173448,176092,178756,181440,184144,186868,189612,192376,195160,197964,200788,203632,206496,209380,212284,215208,218152,221116,224100,227104,230128,233172,236236,239320,242424,245548,248692,251856,255040,258244,261468,264712,267976,271260,274564,277888,281232,284596,287980,291384,294808,298252,301716,305200,308704,312228,315772,319336,322920,326524,330148,333792,337456,341140,344844,348568,352312,356076,359860,363664,367488,371332,375196,379080,382984,386908,390852,394816,398800,402804,406828,410872,414936,419020,423124,427248,431392,435556,439740,443944,448168,452412,456676,460960,465264,469588,473932,478296,482680,487084,491508,495952,500416,504900,509404,513928,518472,523036,527620,532224,536848,541492,546156,550840,555544,560268,565012,569776,574560,579364,584188,589032,593896,598780,603684,608608,613552,618516 mov $1,10 mul $1,$0 sub $1,6 mul $1,$0
; A220946: Expansion of (1+2*x+2*x^2-x^3)/((1-x)*(1+x)*(1-3x^2)). ; 1,2,6,7,21,22,66,67,201,202,606,607,1821,1822,5466,5467,16401,16402,49206,49207,147621,147622,442866,442867,1328601,1328602,3985806,3985807,11957421,11957422,35872266,35872267,107616801,107616802,322850406,322850407 lpb $0 sub $0,2 mul $1,3 add $1,5 lpe add $1,$0 add $1,1
; A002866: a(0) = 1; for n > 0, a(n) = 2^(n-1)*n!. ; 1,1,4,24,192,1920,23040,322560,5160960,92897280,1857945600,40874803200,980995276800,25505877196800,714164561510400,21424936845312000,685597979049984000,23310331287699456000,839171926357180416000,31888533201572855808000,1275541328062914232320000,53572735778642397757440000,2357200374260265501327360000,108431217215972213061058560000,5204698426366666226930810880000,260234921318333311346540544000000,13532215908553332190020108288000000,730739659061879938261085847552000000 mov $2,$0 mov $0,2 mul $2,2 lpb $2 mul $0,$2 sub $2,2 lpe sub $0,4 div $0,4 add $0,1
INCBIN "gfx/footprints/bulbasaur.1bpp" INCBIN "gfx/footprints/ivysaur.1bpp" INCBIN "gfx/footprints/venusaur.1bpp" INCBIN "gfx/footprints/charmander.1bpp" INCBIN "gfx/footprints/charmeleon.1bpp" INCBIN "gfx/footprints/charizard.1bpp" INCBIN "gfx/footprints/squirtle.1bpp" INCBIN "gfx/footprints/wartortle.1bpp" INCBIN "gfx/footprints/blastoise.1bpp" INCBIN "gfx/footprints/caterpie.1bpp" INCBIN "gfx/footprints/metapod.1bpp" INCBIN "gfx/footprints/butterfree.1bpp" INCBIN "gfx/footprints/weedle.1bpp" INCBIN "gfx/footprints/kakuna.1bpp" INCBIN "gfx/footprints/beedrill.1bpp" INCBIN "gfx/footprints/pidgey.1bpp" INCBIN "gfx/footprints/pidgeotto.1bpp" INCBIN "gfx/footprints/pidgeot.1bpp" INCBIN "gfx/footprints/rattata.1bpp" INCBIN "gfx/footprints/raticate.1bpp" INCBIN "gfx/footprints/spearow.1bpp" INCBIN "gfx/footprints/fearow.1bpp" INCBIN "gfx/footprints/ekans.1bpp" INCBIN "gfx/footprints/arbok.1bpp" INCBIN "gfx/footprints/pikachu.1bpp" INCBIN "gfx/footprints/raichu.1bpp" INCBIN "gfx/footprints/sandshrew.1bpp" INCBIN "gfx/footprints/sandslash.1bpp" INCBIN "gfx/footprints/nidoran_f.1bpp" INCBIN "gfx/footprints/nidorina.1bpp" INCBIN "gfx/footprints/nidoqueen.1bpp" INCBIN "gfx/footprints/nidoran_m.1bpp" INCBIN "gfx/footprints/nidorino.1bpp" INCBIN "gfx/footprints/nidoking.1bpp" INCBIN "gfx/footprints/clefairy.1bpp" INCBIN "gfx/footprints/clefable.1bpp" INCBIN "gfx/footprints/vulpix.1bpp" INCBIN "gfx/footprints/ninetales.1bpp" INCBIN "gfx/footprints/jigglypuff.1bpp" INCBIN "gfx/footprints/wigglytuff.1bpp" INCBIN "gfx/footprints/zubat.1bpp" INCBIN "gfx/footprints/golbat.1bpp" INCBIN "gfx/footprints/oddish.1bpp" INCBIN "gfx/footprints/gloom.1bpp" INCBIN "gfx/footprints/vileplume.1bpp" INCBIN "gfx/footprints/paras.1bpp" INCBIN "gfx/footprints/parasect.1bpp" INCBIN "gfx/footprints/venonat.1bpp" INCBIN "gfx/footprints/venomoth.1bpp" INCBIN "gfx/footprints/diglett.1bpp" INCBIN "gfx/footprints/dugtrio.1bpp" INCBIN "gfx/footprints/meowth.1bpp" INCBIN "gfx/footprints/persian.1bpp" INCBIN "gfx/footprints/psyduck.1bpp" INCBIN "gfx/footprints/golduck.1bpp" INCBIN "gfx/footprints/mankey.1bpp" INCBIN "gfx/footprints/primeape.1bpp" INCBIN "gfx/footprints/growlithe.1bpp" INCBIN "gfx/footprints/arcanine.1bpp" INCBIN "gfx/footprints/poliwag.1bpp" INCBIN "gfx/footprints/poliwhirl.1bpp" INCBIN "gfx/footprints/poliwrath.1bpp" INCBIN "gfx/footprints/abra.1bpp" INCBIN "gfx/footprints/kadabra.1bpp" INCBIN "gfx/footprints/alakazam.1bpp" INCBIN "gfx/footprints/machop.1bpp" INCBIN "gfx/footprints/machoke.1bpp" INCBIN "gfx/footprints/machamp.1bpp" INCBIN "gfx/footprints/bellsprout.1bpp" INCBIN "gfx/footprints/weepinbell.1bpp" INCBIN "gfx/footprints/victreebel.1bpp" INCBIN "gfx/footprints/tentacool.1bpp" INCBIN "gfx/footprints/tentacruel.1bpp" INCBIN "gfx/footprints/geodude.1bpp" INCBIN "gfx/footprints/graveler.1bpp" INCBIN "gfx/footprints/golem.1bpp" INCBIN "gfx/footprints/ponyta.1bpp" INCBIN "gfx/footprints/rapidash.1bpp" INCBIN "gfx/footprints/slowpoke.1bpp" INCBIN "gfx/footprints/slowbro.1bpp" INCBIN "gfx/footprints/magnemite.1bpp" INCBIN "gfx/footprints/magneton.1bpp" INCBIN "gfx/footprints/farfetch_d.1bpp" INCBIN "gfx/footprints/doduo.1bpp" INCBIN "gfx/footprints/dodrio.1bpp" INCBIN "gfx/footprints/seel.1bpp" INCBIN "gfx/footprints/dewgong.1bpp" INCBIN "gfx/footprints/grimer.1bpp" INCBIN "gfx/footprints/muk.1bpp" INCBIN "gfx/footprints/shellder.1bpp" INCBIN "gfx/footprints/cloyster.1bpp" INCBIN "gfx/footprints/gastly.1bpp" INCBIN "gfx/footprints/haunter.1bpp" INCBIN "gfx/footprints/gengar.1bpp" INCBIN "gfx/footprints/onix.1bpp" INCBIN "gfx/footprints/drowzee.1bpp" INCBIN "gfx/footprints/hypno.1bpp" INCBIN "gfx/footprints/krabby.1bpp" INCBIN "gfx/footprints/kingler.1bpp" INCBIN "gfx/footprints/voltorb.1bpp" INCBIN "gfx/footprints/electrode.1bpp" INCBIN "gfx/footprints/exeggcute.1bpp" INCBIN "gfx/footprints/exeggutor.1bpp" INCBIN "gfx/footprints/cubone.1bpp" INCBIN "gfx/footprints/marowak.1bpp" INCBIN "gfx/footprints/hitmonlee.1bpp" INCBIN "gfx/footprints/hitmonchan.1bpp" INCBIN "gfx/footprints/lickitung.1bpp" INCBIN "gfx/footprints/koffing.1bpp" INCBIN "gfx/footprints/weezing.1bpp" INCBIN "gfx/footprints/rhyhorn.1bpp" INCBIN "gfx/footprints/rhydon.1bpp" INCBIN "gfx/footprints/chansey.1bpp" INCBIN "gfx/footprints/tangela.1bpp" INCBIN "gfx/footprints/kangaskhan.1bpp" INCBIN "gfx/footprints/horsea.1bpp" INCBIN "gfx/footprints/seadra.1bpp" INCBIN "gfx/footprints/goldeen.1bpp" INCBIN "gfx/footprints/seaking.1bpp" INCBIN "gfx/footprints/staryu.1bpp" INCBIN "gfx/footprints/starmie.1bpp" INCBIN "gfx/footprints/mr__mime.1bpp" INCBIN "gfx/footprints/scyther.1bpp" INCBIN "gfx/footprints/jynx.1bpp" INCBIN "gfx/footprints/electabuzz.1bpp" INCBIN "gfx/footprints/magmar.1bpp" INCBIN "gfx/footprints/pinsir.1bpp" INCBIN "gfx/footprints/tauros.1bpp" INCBIN "gfx/footprints/magikarp.1bpp" INCBIN "gfx/footprints/gyarados.1bpp" INCBIN "gfx/footprints/lapras.1bpp" INCBIN "gfx/footprints/ditto.1bpp" INCBIN "gfx/footprints/eevee.1bpp" INCBIN "gfx/footprints/vaporeon.1bpp" INCBIN "gfx/footprints/jolteon.1bpp" INCBIN "gfx/footprints/flareon.1bpp" INCBIN "gfx/footprints/porygon.1bpp" INCBIN "gfx/footprints/omanyte.1bpp" INCBIN "gfx/footprints/omastar.1bpp" INCBIN "gfx/footprints/kabuto.1bpp" INCBIN "gfx/footprints/kabutops.1bpp" INCBIN "gfx/footprints/aerodactyl.1bpp" INCBIN "gfx/footprints/snorlax.1bpp" INCBIN "gfx/footprints/articuno.1bpp" INCBIN "gfx/footprints/zapdos.1bpp" INCBIN "gfx/footprints/moltres.1bpp" INCBIN "gfx/footprints/dratini.1bpp" INCBIN "gfx/footprints/dragonair.1bpp" INCBIN "gfx/footprints/dragonite.1bpp" INCBIN "gfx/footprints/mewtwo.1bpp" INCBIN "gfx/footprints/mew.1bpp" INCBIN "gfx/footprints/chikorita.1bpp" INCBIN "gfx/footprints/bayleef.1bpp" INCBIN "gfx/footprints/meganium.1bpp" INCBIN "gfx/footprints/cyndaquil.1bpp" INCBIN "gfx/footprints/quilava.1bpp" INCBIN "gfx/footprints/typhlosion.1bpp" INCBIN "gfx/footprints/totodile.1bpp" INCBIN "gfx/footprints/croconaw.1bpp" INCBIN "gfx/footprints/feraligatr.1bpp" INCBIN "gfx/footprints/sentret.1bpp" INCBIN "gfx/footprints/furret.1bpp" INCBIN "gfx/footprints/hoothoot.1bpp" INCBIN "gfx/footprints/noctowl.1bpp" INCBIN "gfx/footprints/ledyba.1bpp" INCBIN "gfx/footprints/ledian.1bpp" INCBIN "gfx/footprints/spinarak.1bpp" INCBIN "gfx/footprints/ariados.1bpp" INCBIN "gfx/footprints/crobat.1bpp" INCBIN "gfx/footprints/chinchou.1bpp" INCBIN "gfx/footprints/lanturn.1bpp" INCBIN "gfx/footprints/pichu.1bpp" INCBIN "gfx/footprints/cleffa.1bpp" INCBIN "gfx/footprints/igglybuff.1bpp" INCBIN "gfx/footprints/togepi.1bpp" INCBIN "gfx/footprints/togetic.1bpp" INCBIN "gfx/footprints/natu.1bpp" INCBIN "gfx/footprints/xatu.1bpp" INCBIN "gfx/footprints/mareep.1bpp" INCBIN "gfx/footprints/flaaffy.1bpp" INCBIN "gfx/footprints/ampharos.1bpp" INCBIN "gfx/footprints/bellossom.1bpp" INCBIN "gfx/footprints/marill.1bpp" INCBIN "gfx/footprints/azumarill.1bpp" INCBIN "gfx/footprints/sudowoodo.1bpp" INCBIN "gfx/footprints/politoed.1bpp" INCBIN "gfx/footprints/hoppip.1bpp" INCBIN "gfx/footprints/skiploom.1bpp" INCBIN "gfx/footprints/jumpluff.1bpp" INCBIN "gfx/footprints/aipom.1bpp" INCBIN "gfx/footprints/sunkern.1bpp" INCBIN "gfx/footprints/sunflora.1bpp" INCBIN "gfx/footprints/yanma.1bpp" INCBIN "gfx/footprints/wooper.1bpp" INCBIN "gfx/footprints/quagsire.1bpp" INCBIN "gfx/footprints/espeon.1bpp" INCBIN "gfx/footprints/umbreon.1bpp" INCBIN "gfx/footprints/murkrow.1bpp" INCBIN "gfx/footprints/slowking.1bpp" INCBIN "gfx/footprints/misdreavus.1bpp" INCBIN "gfx/footprints/unown.1bpp" INCBIN "gfx/footprints/wobbuffet.1bpp" INCBIN "gfx/footprints/girafarig.1bpp" INCBIN "gfx/footprints/pineco.1bpp" INCBIN "gfx/footprints/forretress.1bpp" INCBIN "gfx/footprints/dunsparce.1bpp" INCBIN "gfx/footprints/gligar.1bpp" INCBIN "gfx/footprints/steelix.1bpp" INCBIN "gfx/footprints/snubbull.1bpp" INCBIN "gfx/footprints/granbull.1bpp" INCBIN "gfx/footprints/qwilfish.1bpp" INCBIN "gfx/footprints/scizor.1bpp" INCBIN "gfx/footprints/shuckle.1bpp" INCBIN "gfx/footprints/heracross.1bpp" INCBIN "gfx/footprints/sneasel.1bpp" INCBIN "gfx/footprints/teddiursa.1bpp" INCBIN "gfx/footprints/ursaring.1bpp" INCBIN "gfx/footprints/slugma.1bpp" INCBIN "gfx/footprints/magcargo.1bpp" INCBIN "gfx/footprints/swinub.1bpp" INCBIN "gfx/footprints/piloswine.1bpp" INCBIN "gfx/footprints/corsola.1bpp" INCBIN "gfx/footprints/remoraid.1bpp" INCBIN "gfx/footprints/octillery.1bpp" INCBIN "gfx/footprints/delibird.1bpp" INCBIN "gfx/footprints/mantine.1bpp" INCBIN "gfx/footprints/skarmory.1bpp" INCBIN "gfx/footprints/houndour.1bpp" INCBIN "gfx/footprints/houndoom.1bpp" INCBIN "gfx/footprints/kingdra.1bpp" INCBIN "gfx/footprints/phanpy.1bpp" INCBIN "gfx/footprints/donphan.1bpp" INCBIN "gfx/footprints/porygon2.1bpp" INCBIN "gfx/footprints/stantler.1bpp" INCBIN "gfx/footprints/smeargle.1bpp" INCBIN "gfx/footprints/tyrogue.1bpp" INCBIN "gfx/footprints/hitmontop.1bpp" INCBIN "gfx/footprints/smoochum.1bpp" INCBIN "gfx/footprints/elekid.1bpp" INCBIN "gfx/footprints/magby.1bpp" INCBIN "gfx/footprints/miltank.1bpp" INCBIN "gfx/footprints/blissey.1bpp" INCBIN "gfx/footprints/raikou.1bpp" INCBIN "gfx/footprints/entei.1bpp" INCBIN "gfx/footprints/suicune.1bpp" INCBIN "gfx/footprints/larvitar.1bpp" INCBIN "gfx/footprints/pupitar.1bpp" INCBIN "gfx/footprints/tyranitar.1bpp" INCBIN "gfx/footprints/lugia.1bpp" INCBIN "gfx/footprints/ho_oh.1bpp" INCBIN "gfx/footprints/celebi.1bpp" INCBIN "gfx/footprints/252.1bpp" INCBIN "gfx/footprints/253.1bpp" INCBIN "gfx/footprints/254.1bpp" INCBIN "gfx/footprints/255.1bpp" INCBIN "gfx/footprints/256.1bpp"
#if VERBOSE = 1 LASTINIT SET . #endif ; Subroutines ; ---------------------------------------------------------------------- ; Clear screen -- easy clearScreen SUBROUTINE ldx #$ff .loop: lda #$00 sta $400,x sta $500,x sta $600,x sta $700,x lda #$05 sta $d800,x sta $d900,x sta $da00,x sta $db00,x dex cpx #$ff bne .loop ; Do some math to calculate tile address in video memory ; using x,y coordinates ; Formula: addr = $400 + y * SCREEN_W + x calcTileMem SUBROUTINE ; Save registers pha txa pha tya pha ; Set tileMem to $400 lda #$00 sta tileMem lda #$04 sta tileMem + 1 ldy calcTileY ; Get head Y coordinate calcTileMult: tya beq calcTileEnd ; if Y is equal to zero, nothing to do, just skip moltiplication, else... dey ; decrement Y clc lda #SCREEN_W ; A = screen width = 40 adc tileMem ; A = screen width + tileMem (low) sta tileMem ; update tileMem (low) lda #0 ; do the same with higher byte: A = 0 adc tileMem + 1 ; add (eventual) carry sta tileMem + 1 ; update tileMem (high) jmp calcTileMult ; do again until Y == 0 calcTileEnd: ; now multiplication is ended, so add X lda calcTileX adc tileMem sta tileMem lda #0 adc tileMem + 1 sta tileMem + 1 ; Restore old registers pla tay pla tax pla rts ; Print a byte in hexadecimal ; A input register for byte to print ; Y input register for printing colum (on first line) printByte SUBROUTINE ; Copy parameter also in X tax lsr ; Take most significant nibble lsr lsr lsr ora #$40 ; add 64 (see font) sta $400,y ; print msb char txa ; Take least significant nibble (use previous copy) and #$0f ora #$40 ; add 64 (see font) sta $401,y ; print lsb char rts printString SUBROUTINE ; Print string ; Input parameters: ; srcStringPointer pointer to string to be printed (source) ; dstScreenPointer pointer to text video memory on screen where to print (dest) ; Output results: ; Y leaves string length in reg Y ldy #0 .loop: lda (srcStringPointer),y ; get char from string beq .end ; if zero, then end (string must be null-terminated) cmp #$20 ; is space? bne .checkP1 lda #$0 jmp .print .checkP1: cmp #$28 ; is char '(' ? bne .checkP2 lda #$1b jmp .print .checkP2: cmp #$29 ; is char ')' ? bne .checkP3 lda #$1c jmp .print .checkP3 cmp #$2e ; is char '.' ? bne .checkNumber lda #$1d jmp .print .checkNumber: ; is char a number? cmp #$2f bcc .nextCheck cmp #$3a bcs .nextCheck sec sbc #$30 clc adc #$40 jmp .print .nextCheck: .isLetter: ; defaults to an uppercase letter of ASCII set sec sbc #$40 .print: sta (dstScreenPointer),y ; put screen code to screen iny ; next char in string jmp .loop .end: rts ; Increment a pointer in the zeropage ; Input parameters: ; nextPointerPointer pointer to the pointer in zeropage ; regX value to increment nextPointer: lda #0 sta nextPointerPointer + 1 txa clc ldy #0 adc (nextPointerPointer),y sta (nextPointerPointer),y ldy #1 lda (nextPointerPointer),y adc #0 sta (nextPointerPointer),y rts #if VERBOSE = 1 ECHO "subroutines.asm @ ",LASTINIT,"len:",(. - LASTINIT) #endif
; A204512: Square roots of [A055872/8]: Their square written in base 8, with some digit appended, is again a square. ; Submitted by Christian Krause ; 0,0,0,1,2,6,12,35,70,204,408,1189,2378,6930,13860,40391,80782,235416,470832,1372105,2744210,7997214,15994428,46611179,93222358,271669860,543339720,1583407981,3166815962,9228778026,18457556052,53789260175,107578520350 mov $2,$0 mov $4,$0 lpb $2 mov $0,$4 sub $0,1 div $0,2 sub $2,3 mod $2,2 mov $3,$0 seq $3,1109 ; a(n)^2 is a triangular number: a(n) = 6*a(n-1) - a(n-2) with a(0)=0, a(1)=1. add $1,$3 lpe mov $0,$1
/* This file is part of CosmoLattice, available at www.cosmolattice.net . Copyright Daniel G. Figueroa, Adrien Florio, Francisco Torrenti and Wessel Valkenburg. Released under the MIT license, see LICENSE.md. */ // File info: Main contributor(s): Wessel Valkenburg, Year: 2019 #include "TempLat/util/random/randomuniform.h" namespace { TempLat::TDDContainer<TempLat::RandomUniformTester> test; }
; A157956: a(n) = 200*n + 1. ; 201,401,601,801,1001,1201,1401,1601,1801,2001,2201,2401,2601,2801,3001,3201,3401,3601,3801,4001,4201,4401,4601,4801,5001,5201,5401,5601,5801,6001,6201,6401,6601,6801,7001,7201,7401,7601,7801,8001,8201,8401,8601,8801,9001,9201,9401,9601,9801,10001,10201,10401,10601,10801,11001,11201,11401,11601,11801,12001,12201,12401,12601,12801,13001,13201,13401,13601,13801,14001,14201,14401,14601,14801,15001,15201,15401,15601,15801,16001,16201,16401,16601,16801,17001,17201,17401,17601,17801,18001,18201,18401,18601,18801,19001,19201,19401,19601,19801,20001 mul $0,200 add $0,201
; A086092: 4^n+3n5^(n-1). ; Submitted by Christian Krause ; 1,7,46,289,1756,10399,60346,344509,1940536,10809019,59642326,326459929,1774589716,9588593239,51537966706,275731944949,1469138717296,7799162291059,41267449945486,217712622047569,1145508691315276 mov $1,5 pow $1,$0 mul $1,$0 mov $2,4 pow $2,$0 mov $0,$1 mul $0,3 mul $2,5 add $0,$2 div $0,5
dnl PowerPC-32 mpn_submul_1 -- Multiply a limb vector with a limb and subtract dnl the result from a second limb vector. dnl Copyright 1995, 1997, 1998, 2000, 2002, 2005 Free Software Foundation, dnl Inc. dnl This file is part of the GNU MP Library. dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of the GNU Lesser General Public License as published dnl by the Free Software Foundation; either version 2.1 of the License, or (at dnl your option) any later version. dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public dnl License for more details. dnl You should have received a copy of the GNU Lesser General Public License dnl along with the GNU MP Library; see the file COPYING.LIB. If not, write dnl to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, dnl Boston, MA 02110-1301, USA. include(`../config.m4') C cycles/limb C 603e: ? C 604e: 7.5 C 75x (G3): 9.3-15 C 7400,7410 (G4): 9.3-15 C 744x,745x (G4+): 10.5 C power4/ppc970: 6.75 C power5: 6.5 C INPUT PARAMETERS C rp r3 C up r4 C n r5 C vl r6 C This is optimized for the PPC604. See addmul_1.asm for additional comments. ASM_START() PROLOGUE(mpn_submul_1) cmpwi cr0,r5,9 C more than 9 limbs? bgt cr0,L(big) C branch if more than 9 limbs mtctr r5 lwz r0,0(r4) mullw r7,r0,r6 mulhwu r10,r0,r6 lwz r9,0(r3) subfc r8,r7,r9 addc r7,r7,r8 C invert cy (r7 is junk) addi r3,r3,-4 bdz L(end) L(loop): lwzu r0,4(r4) stwu r8,4(r3) mullw r8,r0,r6 adde r7,r8,r10 mulhwu r10,r0,r6 lwz r9,4(r3) addze r10,r10 subfc r8,r7,r9 addc r7,r7,r8 C invert cy (r7 is junk) bdnz L(loop) L(end): stw r8,4(r3) addze r3,r10 blr L(big): stmw r30,-32(r1) addi r5,r5,-1 srwi r0,r5,2 mtctr r0 lwz r7,0(r4) mullw r8,r7,r6 mulhwu r0,r7,r6 lwz r7,0(r3) subfc r7,r8,r7 addc r8,r8,r7 stw r7,0(r3) L(loopU): lwz r7,4(r4) lwz r12,8(r4) lwz r30,12(r4) lwzu r31,16(r4) mullw r8,r7,r6 mullw r9,r12,r6 mullw r10,r30,r6 mullw r11,r31,r6 adde r8,r8,r0 C add cy_limb mulhwu r0,r7,r6 lwz r7,4(r3) adde r9,r9,r0 mulhwu r0,r12,r6 lwz r12,8(r3) adde r10,r10,r0 mulhwu r0,r30,r6 lwz r30,12(r3) adde r11,r11,r0 mulhwu r0,r31,r6 lwz r31,16(r3) addze r0,r0 C new cy_limb subfc r7,r8,r7 stw r7,4(r3) subfe r12,r9,r12 stw r12,8(r3) subfe r30,r10,r30 stw r30,12(r3) subfe r31,r11,r31 stwu r31,16(r3) subfe r11,r11,r11 C invert ... addic r11,r11,1 C ... carry bdnz L(loopU) andi. r31,r5,3 mtctr r31 beq cr0,L(endx) L(loopE): lwzu r7,4(r4) mullw r8,r7,r6 adde r8,r8,r0 C add cy_limb mulhwu r0,r7,r6 lwz r7,4(r3) addze r0,r0 C new cy_limb subfc r7,r8,r7 addc r8,r8,r7 stwu r7,4(r3) bdnz L(loopE) L(endx): addze r3,r0 lmw r30,-32(r1) blr EPILOGUE(mpn_submul_1)
/******************************************************************* * * DESCRIPTION: consbtch.cpp * * AUTHOR: David Malcolm * * HISTORY: Created 8/4/98 * *******************************************************************/ /* Includes ********************************************************/ #include "3dc.h" #include "console_batch.hpp" #include "reflist.hpp" #define UseLocalAssert TRUE #include "ourasert.h" /* Version settings ************************************************/ /* Constants *******************************************************/ enum { MaxBatchFileLineLength=300, MaxBatchFileLineSize=(MaxBatchFileLineLength+1) }; /* Macros **********************************************************/ /* Imported function prototypes ************************************/ /* Imported data ***************************************************/ /* Exported globals ************************************************/ /* Internal type definitions ***************************************/ /* Internal function prototypes ************************************/ /* Internal globals ************************************************/ /* Exported function definitions ***********************************/ // class BatchFileProcessing // public: // static bool BatchFileProcessing :: Run(char* Filename) { // Tries to find the file, if it finds it it reads it, // adds the non-comment lines to the pending list, and returns TRUE // If it can't find the file, it returns FALSE // LOCALISEME // This code makes several uses of the assumption that char is type-equal // to ProjChar RefList<SCString> PendingList; { FILE *pFile = avp_open_userfile(Filename, "r"); if (NULL==pFile) { return FALSE; } // Read the file, line by line. { // We impose a maximum length on lines that will be valid: char LineBuffer[MaxBatchFileLineSize]; int CharsReadInLine = 0; while (1) { int Char = fgetc(pFile); if (Char==EOF) { break; } else { if ( Char=='\n' ) { // Flush the buffer into the pending queue: GLOBALASSERT(CharsReadInLine<=MaxBatchFileLineLength); LineBuffer[CharsReadInLine] = '\0'; SCString* pSCString_Line = new SCString(&LineBuffer[0]); PendingList . AddToEnd ( *pSCString_Line ); pSCString_Line -> R_Release(); CharsReadInLine = 0; } else { // Add to buffer; silently reject characters beyond the length limit if ( CharsReadInLine < MaxBatchFileLineLength ) { LineBuffer[CharsReadInLine++]=toupper((char)Char); } } } } // Flush anything still in the buffer into the pending queue: { GLOBALASSERT(CharsReadInLine<=MaxBatchFileLineLength); LineBuffer[CharsReadInLine] = '\0'; SCString* pSCString_Line = new SCString(&LineBuffer[0]); PendingList . AddToEnd ( *pSCString_Line ); pSCString_Line -> R_Release(); } } fclose(pFile); } // Feedback: { SCString* pSCString_1 = new SCString("EXECUTING BATCH FILE "); // LOCALISEME SCString* pSCString_2 = new SCString(Filename); SCString* pSCString_Feedback = new SCString ( pSCString_1, pSCString_2 ); pSCString_Feedback -> SendToScreen(); pSCString_Feedback -> R_Release(); pSCString_2 -> R_Release(); pSCString_1 -> R_Release(); } // Now process the pending queue: { // Iterate through the pending list, destructively reading the // "references" from the front: { SCString* pSCString; // The assignment in this boolean expression is deliberate: while ( NULL != (pSCString = PendingList . GetYourFirst()) ) { if (pSCString->pProjCh()[0] != '#') { // lines beginning with hash are comments if (bEcho) { pSCString -> SendToScreen(); } pSCString -> ProcessAnyCheatCodes(); } pSCString -> R_Release(); } } } return TRUE; } // public: // static int BatchFileProcessing :: bEcho = FALSE; /* Internal function definitions ***********************************/
; ; feilipu, 2020 May ; ; This Source Code Form is subject to the terms of the Mozilla Public ; License, v. 2.0. If a copy of the MPL was not distributed with this ; file, You can obtain one at http://mozilla.org/MPL/2.0/. ; ;------------------------------------------------------------------------- ; asm_f16_mul - z80 half floating point multiply 16-bit mantissa ;------------------------------------------------------------------------- ; ; since the z180, and z80n only have support for 8x8bit multiply, ; the multiplication of the mantissas needs to be broken ; into stages and accumulated at the end. ; ; ab * cd ; ; = (a*c)*2^16 + ; (a*d + b*c)*2^8 + ; (b*d)*2^0 ; ; assume worst overflow case: ab=cd=0xffff ; assume worst underflow case: ab=cd=0x8000 ; ; 0xFFFF * 0xFFFF = 0x FF FE 00 01 ; ; 0x8000 * 0x8000 = 0x 40 00 00 00 ; ; for underflow, maximum left shift is 1 place ; so we should report 32 bits of accuracy ; = 16 bits significant ; ; calculation for the z80 is done using unrolled shift+add. ; with zero operand and zero bit elimination for fast multiply option. ; ; unpacked format: exponent in d, sign in e[7], mantissa in hl ; ;------------------------------------------------------------------------- SECTION code_fp_math16 EXTERN asm_f24_f16 EXTERN asm_f16_f24 EXTERN asm_f24_zero EXTERN asm_f24_inf EXTERN l_mulu_32_16x16 PUBLIC asm_f16_mul_callee PUBLIC asm_f24_mul_callee PUBLIC asm_f24_mul_f24 ; enter here for floating asm_f16_mul_callee, x+y, x on stack, y in hl, result in hl .asm_f16_mul_callee call asm_f24_f16 ; expand to dehl exx ; y d' = eeeeeeee e = s------- ; hl' = 1mmmmmmm mmmmmmmm pop hl ; pop return address ex (sp),hl ; get second operand off of the stack, ; return address on stack call asm_f24_f16 ; expand to dehl ; x d = eeeeeeee e = s------- ; hl = 1mmmmmmm mmmmmmmm call asm_f24_mul_f24 jp asm_f16_f24 ; enter here for floating asm_f24_mul_callee, x+y, x on stack, y in dehl, result in dehl .asm_f24_mul_callee exx ; y d = eeeeeeee e = s------- ; hl = 1mmmmmmm mmmmmmmm pop bc ; pop return address pop hl ; x d = eeeeeeee e = s------- hl = 1mmmmmmm mmmmmmmm pop de push bc ; return address on stack .asm_f24_mul_f24 ld a,e ; place op1.s in a[7] exx ; x d' = eeeeeeee e' = s------- hl' = 1mmmmmmm mmmmmmmm xor a,e ; xor sign flags ex af,af ; save sign flag in a[7]' and f' reg ld a,d ; calculate the exponent or a ; second exponent zero then result is zero jr Z,mulzero sub a,07fh ; subtract out bias, so when exponents are added only one bias present jr C,fmchkuf exx add a,d jr C,mulovl jr fmnouf .fmchkuf exx add a,d ; add the exponents jr NC,mulzero .fmnouf ld b,a or a jr Z,mulzero ; check sum of exponents for zero ex af,af ld a,b push af ; stack: sum of exponents a, and xor sign of exponents in f ; first d = eeeeeeee e = s------- hl = 1mmmmmmm mmmmmmmm ; second d' = eeeeeeee e' = s------- hl' = 1mmmmmmm mmmmmmmm ; sum of exponents in a', xor of exponents in sign f' push hl exx pop de ; multiplication of two 16-bit numbers into a 32-bit product call l_mulu_32_16x16 ; exit : de * hl = dehl = 32-bit product pop bc ; retrieve exponent and sign from stack = b,c[7] bit 7,d ; need to shift result left if msb!=1 jr NZ,fm2 add hl,hl rl e rl d jr fm3 .fm2 inc b jr Z,mulovl .fm3 ex de,hl ; put 16 bit mantissa in place, de into hl ld a,d ; capture 8 rounding bits and a,0F0h ; check for 4 lost bits rounding jr Z,fm4 set 0,l .fm4 ld d,b ; put exponent in d ld e,c ; put sign into e[7] ret ; return half float f24 .mulovl ex af,af ; get sign ld e,a jp asm_f24_inf ; done overflow .mulzero ex af,af ; get sign ld e,a jp asm_f24_zero ; done underflow
//# This file is a part of toml++ and is subject to the the terms of the MIT license. //# Copyright (c) 2019-2020 Mark Gillard <mark.gillard@outlook.com.au> //# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text. // SPDX-License-Identifier: MIT #pragma once //# {{ #include "toml_preprocessor.h" #if !TOML_IMPLEMENTATION #error This is an implementation-only header. #endif #if !TOML_PARSER #error This header cannot not be included when TOML_PARSER is disabled. #endif //# }} #include "toml_parser.h" TOML_PUSH_WARNINGS TOML_DISABLE_ALL_WARNINGS #include <cmath> #if TOML_INT_CHARCONV || TOML_FLOAT_CHARCONV #include <charconv> #endif #if !TOML_INT_CHARCONV || !TOML_FLOAT_CHARCONV #include <sstream> #endif #if !TOML_HEADER_ONLY using namespace std::string_view_literals; #endif TOML_POP_WARNINGS TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS TOML_DISABLE_PADDING_WARNINGS #if TOML_EXCEPTIONS && !defined(__INTELLISENSE__) #define TOML_RETURNS_BY_THROWING [[noreturn]] #else #define TOML_RETURNS_BY_THROWING #endif TOML_ANON_NAMESPACE_START { template <uint64_t> struct parse_integer_traits; template <> struct parse_integer_traits<2> final { static constexpr auto scope_qualifier = "binary integer"sv; static constexpr auto is_digit = ::toml::impl::is_binary_digit; static constexpr auto is_signed = false; static constexpr auto buffer_length = 63; static constexpr auto prefix_codepoint = U'b'; static constexpr auto prefix = "b"sv; }; template <> struct parse_integer_traits<8> final { static constexpr auto scope_qualifier = "octal integer"sv; static constexpr auto is_digit = ::toml::impl::is_octal_digit; static constexpr auto is_signed = false; static constexpr auto buffer_length = 21; // strlen("777777777777777777777") static constexpr auto prefix_codepoint = U'o'; static constexpr auto prefix = "o"sv; }; template <> struct parse_integer_traits<10> final { static constexpr auto scope_qualifier = "decimal integer"sv; static constexpr auto is_digit = ::toml::impl::is_decimal_digit; static constexpr auto is_signed = true; static constexpr auto buffer_length = 19; //strlen("9223372036854775807") }; template <> struct parse_integer_traits<16> final { static constexpr auto scope_qualifier = "hexadecimal integer"sv; static constexpr auto is_digit = ::toml::impl::is_hexadecimal_digit; static constexpr auto is_signed = false; static constexpr auto buffer_length = 16; //strlen("7FFFFFFFFFFFFFFF") static constexpr auto prefix_codepoint = U'x'; static constexpr auto prefix = "x"sv; }; [[nodiscard]] TOML_INTERNAL_LINKAGE std::string_view to_sv(::toml::node_type val) noexcept { using namespace ::toml::impl; return node_type_friendly_names[unbox_enum(val)]; } [[nodiscard]] TOML_INTERNAL_LINKAGE std::string_view to_sv(const std::string& str) noexcept { return std::string_view{ str }; } [[nodiscard]] TOML_ATTR(const) TOML_INTERNAL_LINKAGE std::string_view to_sv(bool val) noexcept { using namespace std::string_view_literals; return val ? "true"sv : "false"sv; } [[nodiscard]] TOML_INTERNAL_LINKAGE std::string_view to_sv(const ::toml::impl::utf8_codepoint& cp) noexcept { using namespace ::toml; using namespace ::toml::impl; if TOML_UNLIKELY(cp.value <= U'\x1F') return low_character_escape_table[cp.value]; else if TOML_UNLIKELY(cp.value == U'\x7F') return "\\u007F"sv; else return cp.as_view(); } template <typename T> TOML_ATTR(nonnull) TOML_INTERNAL_LINKAGE TOML_NEVER_INLINE void concatenate(char*& write_pos, char *const buf_end, const T& arg) noexcept { using namespace ::toml; using namespace ::toml::impl; static_assert( is_one_of<remove_cvref_t<T>, std::string_view, int64_t, uint64_t, double>, "concatenate inputs are limited to std::string_view, int64_t, uint64_t and double to keep " "instantiations to a minimum as an anti-bloat measure (hint: to_sv will probably help)" ); if (write_pos >= buf_end) return; using arg_t = remove_cvref_t<T>; if constexpr (std::is_same_v<arg_t, std::string_view>) { const auto max_chars = static_cast<size_t>(buf_end - write_pos); const auto len = max_chars < arg.length() ? max_chars : arg.length(); std::memcpy(write_pos, arg.data(), len); write_pos += len; } else if constexpr (std::is_floating_point_v<arg_t>) { #if TOML_FLOAT_CHARCONV { const auto result = std::to_chars(write_pos, buf_end, arg); write_pos = result.ptr; } #else { std::ostringstream ss; ss.imbue(std::locale::classic()); ss.precision(std::numeric_limits<arg_t>::digits10 + 1); ss << arg; concatenate(write_pos, buf_end, to_sv(std::move(ss).str())); } #endif } else if constexpr (std::is_integral_v<arg_t>) { #if TOML_INT_CHARCONV { const auto result = std::to_chars(write_pos, buf_end, arg); write_pos = result.ptr; } #else { std::ostringstream ss; ss.imbue(std::locale::classic()); using cast_type = std::conditional_t<std::is_signed_v<arg_t>, int64_t, uint64_t>; ss << static_cast<cast_type>(arg); concatenate(write_pos, buf_end, to_sv(std::move(ss).str())); } #endif } } struct error_builder final { static constexpr std::size_t buf_size = 512; char buf[buf_size]; char* write_pos = buf; char* const max_write_pos = buf + (buf_size - std::size_t{ 1 }); //allow for null terminator error_builder(std::string_view scope) noexcept { concatenate(write_pos, max_write_pos, "Error while parsing "sv); concatenate(write_pos, max_write_pos, scope); concatenate(write_pos, max_write_pos, ": "sv); } template <typename T> void append(const T& arg) noexcept { concatenate(write_pos, max_write_pos, arg); } TOML_RETURNS_BY_THROWING auto finish(const ::toml::source_position& pos, const ::toml::source_path_ptr& source_path) const TOML_MAY_THROW { using namespace ::toml; *write_pos = '\0'; #if TOML_EXCEPTIONS throw parse_error{ buf, pos, source_path }; #else return parse_error{ std::string(buf, static_cast<size_t>(write_pos - buf)), pos, source_path }; #endif } }; struct parse_scope final { std::string_view& storage_; std::string_view parent_; TOML_NODISCARD_CTOR explicit parse_scope(std::string_view& current_scope, std::string_view new_scope) noexcept : storage_{ current_scope }, parent_{ current_scope } { storage_ = new_scope; } ~parse_scope() noexcept { storage_ = parent_; } }; #define push_parse_scope_2(scope, line) parse_scope ps_##line{ current_scope, scope } #define push_parse_scope_1(scope, line) push_parse_scope_2(scope, line) #define push_parse_scope(scope) push_parse_scope_1(scope, __LINE__) struct parsed_key final { std::vector<std::string> segments; }; struct parsed_key_value_pair final { parsed_key key; toml::node* value; }; } TOML_ANON_NAMESPACE_END TOML_IMPL_NAMESPACE_START { // Q: "what the fuck is this? MACROS????" // A: The parser needs to work in exceptionless mode (returning error objects directly) // and exception mode (reporting parse failures by throwing). Two totally different control flows. // These macros encapsulate the differences between the two modes so I can write code code // as though I was only targeting one mode and not want yeet myself into the sun. // They're all #undef'd at the bottom of the parser's implementation so they should be harmless outside // of toml++. #if defined(NDEBUG) || !defined(_DEBUG) #define assert_or_assume(cond) TOML_ASSUME(cond) #else #define assert_or_assume(cond) TOML_ASSERT(cond) #endif #define is_eof() !cp #define assert_not_eof() assert_or_assume(cp != nullptr) #define return_if_eof(...) do { if (is_eof()) return __VA_ARGS__; } while(false) #if TOML_EXCEPTIONS #define is_error() false #define return_after_error(...) TOML_UNREACHABLE #define assert_not_error() (void)0 #define return_if_error(...) (void)0 #define return_if_error_or_eof(...) return_if_eof(__VA_ARGS__) #else #define is_error() !!err #define return_after_error(...) return __VA_ARGS__ #define assert_not_error() TOML_ASSERT(!is_error()) #define return_if_error(...) do { if (is_error()) return __VA_ARGS__; } while(false) #define return_if_error_or_eof(...) do { if (is_eof() || is_error()) return __VA_ARGS__; } while(false) #endif #define set_error_and_return(ret, ...) \ do { if (!is_error()) set_error(__VA_ARGS__); return_after_error(ret); } while(false) #define set_error_and_return_default(...) set_error_and_return({}, __VA_ARGS__) #define set_error_and_return_if_eof(...) \ do { if (is_eof()) set_error_and_return(__VA_ARGS__, "encountered end-of-file"sv); } while(false) #define advance_and_return_if_error(...) \ do { assert_not_eof(); advance(); return_if_error(__VA_ARGS__); } while (false) #define advance_and_return_if_error_or_eof(...) \ do { \ assert_not_eof(); \ advance(); \ return_if_error(__VA_ARGS__); \ set_error_and_return_if_eof(__VA_ARGS__); \ } while (false) TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) class parser final { private: utf8_buffered_reader reader; table root; source_position prev_pos = { 1, 1 }; const utf8_codepoint* cp = {}; std::vector<table*> implicit_tables; std::vector<table*> dotted_key_tables; std::vector<array*> table_arrays; std::string recording_buffer; //for diagnostics bool recording = false, recording_whitespace = true; std::string_view current_scope; #if !TOML_EXCEPTIONS mutable optional<toml::parse_error> err; #endif [[nodiscard]] source_position current_position(source_index fallback_offset = 0) const noexcept { if (!is_eof()) return cp->position; return { prev_pos.line, static_cast<source_index>(prev_pos.column + fallback_offset) }; } template <typename... T> TOML_RETURNS_BY_THROWING TOML_NEVER_INLINE void set_error_at(source_position pos, const T&... reason) const TOML_MAY_THROW { static_assert(sizeof...(T) > 0_sz); #if !TOML_EXCEPTIONS if (err) return; #endif error_builder builder{ current_scope }; (builder.append(reason), ...); #if TOML_EXCEPTIONS builder.finish(pos, reader.source_path()); #else err.emplace(builder.finish(pos, reader.source_path())); #endif } template <typename... T> TOML_RETURNS_BY_THROWING void set_error(const T&... reason) const TOML_MAY_THROW { set_error_at(current_position(1), reason...); } void go_back(size_t count = 1_sz) noexcept { return_if_error(); assert_or_assume(count); cp = reader.step_back(count); prev_pos = cp->position; } void advance() TOML_MAY_THROW { return_if_error(); assert_not_eof(); prev_pos = cp->position; cp = reader.read_next(); #if !TOML_EXCEPTIONS if (reader.error()) { err = std::move(reader.error()); return; } #endif if (recording && !is_eof()) { if (recording_whitespace || !(is_whitespace(*cp) || is_line_break(*cp))) recording_buffer.append(cp->as_view()); } } void start_recording(bool include_current = true) noexcept { return_if_error(); recording = true; recording_whitespace = true; recording_buffer.clear(); if (include_current && !is_eof()) recording_buffer.append(cp->as_view()); } void stop_recording(size_t pop_bytes = 0_sz) noexcept { return_if_error(); recording = false; if (pop_bytes) { if (pop_bytes >= recording_buffer.length()) recording_buffer.clear(); else if (pop_bytes == 1_sz) recording_buffer.pop_back(); else recording_buffer.erase( recording_buffer.begin() + static_cast<ptrdiff_t>(recording_buffer.length() - pop_bytes), recording_buffer.end() ); } } bool consume_leading_whitespace() TOML_MAY_THROW { return_if_error_or_eof({}); bool consumed = false; while (!is_eof() && is_whitespace(*cp)) { consumed = true; advance_and_return_if_error({}); } return consumed; } bool consume_line_break() TOML_MAY_THROW { return_if_error_or_eof({}); if (!is_line_break(*cp)) return false; if (*cp == U'\r') { advance_and_return_if_error({}); // skip \r if (is_eof()) return true; //eof after \r is 'fine' else if (*cp != U'\n') set_error_and_return_default("expected \\n, saw '"sv, to_sv(*cp), "'"sv); } advance_and_return_if_error({}); // skip \n (or other single-character line ending) return true; } bool consume_rest_of_line() TOML_MAY_THROW { return_if_error_or_eof({}); do { if (is_line_break(*cp)) return consume_line_break(); else advance(); return_if_error({}); } while (!is_eof()); return true; } bool consume_comment() TOML_MAY_THROW { return_if_error_or_eof({}); if (*cp != U'#') return false; push_parse_scope("comment"sv); advance_and_return_if_error({}); //skip the '#' while (!is_eof()) { if (consume_line_break()) return true; if constexpr (TOML_LANG_AT_LEAST(1, 0, 0)) { // toml/issues/567 (disallow non-TAB control characters in comments) if (is_nontab_control_character(*cp)) set_error_and_return_default( "control characters other than TAB (U+0009) are explicitly prohibited"sv ); // toml/pull/720 (disallow surrogates in comments) else if (is_unicode_surrogate(*cp)) set_error_and_return_default( "unicode surrogates (U+D800 to U+DFFF) are explicitly prohibited"sv ); } advance_and_return_if_error({}); } return true; } [[nodiscard]] bool consume_expected_sequence(std::u32string_view seq) TOML_MAY_THROW { return_if_error({}); TOML_ASSERT(!seq.empty()); for (auto c : seq) { set_error_and_return_if_eof({}); if (*cp != c) return false; advance_and_return_if_error({}); } return true; } template <typename T> [[nodiscard]] bool consume_digit_sequence(T* digits, size_t len) TOML_MAY_THROW { return_if_error({}); assert_or_assume(digits); assert_or_assume(len); for (size_t i = 0; i < len; i++) { set_error_and_return_if_eof({}); if (!is_decimal_digit(*cp)) return false; digits[i] = static_cast<T>(*cp - U'0'); advance_and_return_if_error({}); } return true; } template <typename T> [[nodiscard]] size_t consume_variable_length_digit_sequence(T* buffer, size_t max_len) TOML_MAY_THROW { return_if_error({}); assert_or_assume(buffer); assert_or_assume(max_len); size_t i = {}; for (; i < max_len; i++) { if (is_eof() || !is_decimal_digit(*cp)) break; buffer[i] = static_cast<T>(*cp - U'0'); advance_and_return_if_error({}); } return i; } //template <bool MultiLine> [[nodiscard]] std::string parse_basic_string(bool multi_line) TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'"'); push_parse_scope("string"sv); // skip the '"' advance_and_return_if_error_or_eof({}); // multiline strings ignore a single line ending right at the beginning if (multi_line) { consume_line_break(); return_if_error({}); set_error_and_return_if_eof({}); } std::string str; bool escaped = false; [[maybe_unused]] bool skipping_whitespace = false; do { if (escaped) { escaped = false; // handle 'line ending slashes' in multi-line mode if (multi_line) { if (is_line_break(*cp) || is_whitespace(*cp)) { consume_leading_whitespace(); if (!consume_line_break()) set_error_and_return_default( "line-ending backslashes must be the last non-whitespace character on the line"sv ); skipping_whitespace = true; return_if_error({}); continue; } } bool skipped_escaped_codepoint = false; assert_not_eof(); switch (const auto escaped_codepoint = *cp) { // 'regular' escape codes case U'b': str += '\b'; break; case U'f': str += '\f'; break; case U'n': str += '\n'; break; case U'r': str += '\r'; break; case U't': str += '\t'; break; case U'"': str += '"'; break; case U'\\': str += '\\'; break; // unicode scalar sequences case U'x': #if TOML_LANG_UNRELEASED // toml/pull/709 (\xHH unicode scalar sequences) [[fallthrough]]; #else set_error_and_return_default( "escape sequence '\\x' is not supported in TOML 1.0.0 and earlier"sv ); #endif case U'u': [[fallthrough]]; case U'U': { push_parse_scope("unicode scalar escape sequence"sv); advance_and_return_if_error_or_eof({}); skipped_escaped_codepoint = true; uint32_t place_value = escaped_codepoint == U'U' ? 0x10000000u : (escaped_codepoint == U'u' ? 0x1000u : 0x10u); uint32_t sequence_value{}; while (place_value) { set_error_and_return_if_eof({}); if (!is_hexadecimal_digit(*cp)) set_error_and_return_default("expected hex digit, saw '"sv, to_sv(*cp), "'"sv); sequence_value += place_value * hex_to_dec(*cp); place_value /= 16u; advance_and_return_if_error({}); } if (is_unicode_surrogate(sequence_value)) set_error_and_return_default( "unicode surrogates (U+D800 - U+DFFF) are explicitly prohibited"sv ); else if (sequence_value > 0x10FFFFu) set_error_and_return_default("values greater than U+10FFFF are invalid"sv); else if (sequence_value <= 0x7Fu) //ascii str += static_cast<char>(sequence_value & 0x7Fu); else if (sequence_value <= 0x7FFu) { str += static_cast<char>(0xC0u | ((sequence_value >> 6) & 0x1Fu)); str += static_cast<char>(0x80u | (sequence_value & 0x3Fu)); } else if (sequence_value <= 0xFFFFu) { str += static_cast<char>(0xE0u | ((sequence_value >> 12) & 0x0Fu)); str += static_cast<char>(0x80u | ((sequence_value >> 6) & 0x1Fu)); str += static_cast<char>(0x80u | (sequence_value & 0x3Fu)); } else { str += static_cast<char>(0xF0u | ((sequence_value >> 18) & 0x07u)); str += static_cast<char>(0x80u | ((sequence_value >> 12) & 0x3Fu)); str += static_cast<char>(0x80u | ((sequence_value >> 6) & 0x3Fu)); str += static_cast<char>(0x80u | (sequence_value & 0x3Fu)); } break; } // ??? default: set_error_and_return_default("unknown escape sequence '\\"sv, to_sv(*cp), "'"sv); } // skip the escaped character if (!skipped_escaped_codepoint) advance_and_return_if_error_or_eof({}); } else { // handle closing delimiters if (*cp == U'"') { if (multi_line) { size_t lookaheads = {}; size_t consecutive_delimiters = 1_sz; do { advance_and_return_if_error({}); lookaheads++; if (!is_eof() && *cp == U'"') consecutive_delimiters++; else break; } while (lookaheads < 4_sz); switch (consecutive_delimiters) { // """ " (one quote somewhere in a ML string) case 1_sz: str += '"'; skipping_whitespace = false; continue; // """ "" (two quotes somewhere in a ML string) case 2_sz: str.append("\"\""sv); skipping_whitespace = false; continue; // """ """ (the end of the string) case 3_sz: return str; // """ """" (one at the end of the string) case 4_sz: str += '"'; return str; // """ """"" (two quotes at the end of the string) case 5_sz: str.append("\"\""sv); advance_and_return_if_error({}); // skip the last '"' return str; TOML_NO_DEFAULT_CASE; } } else { advance_and_return_if_error({}); // skip the closing delimiter return str; } } // handle escapes else if (*cp == U'\\') { advance_and_return_if_error_or_eof({}); // skip the '\' skipping_whitespace = false; escaped = true; continue; } // handle line endings in multi-line mode if (multi_line && is_line_break(*cp)) { consume_line_break(); return_if_error({}); if (!skipping_whitespace) str += '\n'; continue; } // handle control characters if (is_nontab_control_character(*cp)) set_error_and_return_default( "unescaped control characters other than TAB (U+0009) are explicitly prohibited"sv ); // handle surrogates in strings (1.0.0 and later) if constexpr (TOML_LANG_AT_LEAST(1, 0, 0)) { if (is_unicode_surrogate(*cp)) set_error_and_return_default( "unescaped unicode surrogates (U+D800 to U+DFFF) are explicitly prohibited"sv ); } if (multi_line) { if (!skipping_whitespace || !is_whitespace(*cp)) { skipping_whitespace = false; str.append(cp->as_view()); } } else str.append(cp->as_view()); advance_and_return_if_error({}); } } while (!is_eof()); set_error_and_return_default("encountered end-of-file"sv); } [[nodiscard]] std::string parse_literal_string(bool multi_line) TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'\''); push_parse_scope("literal string"sv); // skip the delimiter advance_and_return_if_error_or_eof({}); // multiline strings ignore a single line ending right at the beginning if (multi_line) { consume_line_break(); return_if_error({}); set_error_and_return_if_eof({}); } std::string str; do { assert_not_error(); // handle closing delimiters if (*cp == U'\'') { if (multi_line) { size_t lookaheads = {}; size_t consecutive_delimiters = 1_sz; do { advance_and_return_if_error({}); lookaheads++; if (!is_eof() && *cp == U'\'') consecutive_delimiters++; else break; } while (lookaheads < 4_sz); switch (consecutive_delimiters) { // ''' ' (one quote somewhere in a ML string) case 1_sz: str += '\''; continue; // ''' '' (two quotes somewhere in a ML string) case 2_sz: str.append("''"sv); continue; // ''' ''' (the end of the string) case 3_sz: return str; // ''' '''' (one at the end of the string) case 4_sz: str += '\''; return str; // ''' ''''' (two quotes at the end of the string) case 5_sz: str.append("''"sv); advance_and_return_if_error({}); // skip the last ' return str; TOML_NO_DEFAULT_CASE; } } else { advance_and_return_if_error({}); // skip the closing delimiter return str; } } // handle line endings in multi-line mode if (multi_line && is_line_break(*cp)) { consume_line_break(); str += '\n'; continue; } // handle control characters if (is_nontab_control_character(*cp)) set_error_and_return_default( "control characters other than TAB (U+0009) are explicitly prohibited"sv ); // handle surrogates in strings (1.0.0 and later) if constexpr (TOML_LANG_AT_LEAST(1, 0, 0)) { if (is_unicode_surrogate(*cp)) set_error_and_return_default( "unicode surrogates (U+D800 - U+DFFF) are explicitly prohibited"sv ); } str.append(cp->as_view()); advance_and_return_if_error({}); } while (!is_eof()); set_error_and_return_default("encountered end-of-file"sv); } struct parsed_string final { std::string value; bool was_multi_line; }; [[nodiscard]] TOML_NEVER_INLINE parsed_string parse_string() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_string_delimiter(*cp)); push_parse_scope("string"sv); // get the first three characters to determine the string type const auto first = cp->value; advance_and_return_if_error_or_eof({}); const auto second = cp->value; advance_and_return_if_error({}); const auto third = cp ? cp->value : U'\0'; // if we were eof at the third character then first and second need to be // the same string character (otherwise it's an unterminated string) if (is_eof()) { if (second == first) return {}; set_error_and_return_default("encountered end-of-file"sv); } // if the first three characters are all the same string delimiter then // it's a multi-line string. else if (first == second && first == third) { return { first == U'\'' ? parse_literal_string(true) : parse_basic_string(true), true }; } // otherwise it's just a regular string. else { // step back two characters so that the current // character is the string delimiter go_back(2_sz); return { first == U'\'' ? parse_literal_string(false) : parse_basic_string(false), false }; } } [[nodiscard]] std::string parse_bare_key_segment() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_bare_key_character(*cp)); std::string segment; while (!is_eof()) { if (!is_bare_key_character(*cp)) break; segment.append(cp->as_view()); advance_and_return_if_error({}); } return segment; } [[nodiscard]] bool parse_boolean() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_match(*cp, U't', U'f', U'T', U'F')); push_parse_scope("boolean"sv); start_recording(true); auto result = is_match(*cp, U't', U'T'); if (!consume_expected_sequence(result ? U"true"sv : U"false"sv)) set_error_and_return_default( "expected '"sv, to_sv(result), "', saw '"sv, to_sv(recording_buffer), "'"sv ); stop_recording(); if (cp && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); return result; } [[nodiscard]] double parse_inf_or_nan() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_match(*cp, U'i', U'n', U'I', U'N', U'+', U'-')); push_parse_scope("floating-point"sv); start_recording(true); const bool negative = *cp == U'-'; if (negative || *cp == U'+') advance_and_return_if_error_or_eof({}); const bool inf = is_match(*cp, U'i', U'I'); if (!consume_expected_sequence(inf ? U"inf"sv : U"nan"sv)) set_error_and_return_default( "expected '"sv, inf ? "inf"sv : "nan"sv, "', saw '"sv, to_sv(recording_buffer), "'"sv ); stop_recording(); if (cp && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); // control for implementations that don't properly implement std::numeric_limits<double>::quiet_NaN() // and/or std::numeric_limits<double>::infinity() (e.g. due to -ffast-math and friends) constexpr uint64_t neg_inf = 0b1111111111110000000000000000000000000000000000000000000000000000ull; constexpr uint64_t pos_inf = 0b0111111111110000000000000000000000000000000000000000000000000000ull; constexpr uint64_t qnan = 0b1111111111111000000000000000000000000000000000000000000000000001ull; double rval; std::memcpy(&rval, inf ? (negative ? &neg_inf : &pos_inf) : &qnan, sizeof(double)); return rval; } TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS TOML_DISABLE_INIT_WARNINGS [[nodiscard]] double parse_float() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_match(*cp, U'+', U'-', U'.') || is_decimal_digit(*cp)); push_parse_scope("floating-point"sv); // sign const int sign = *cp == U'-' ? -1 : 1; if (is_match(*cp, U'+', U'-')) advance_and_return_if_error_or_eof({}); // consume value chars char chars[64]; size_t length = {}; const utf8_codepoint* prev = {}; bool seen_decimal = false, seen_exponent = false; char first_integer_part = '\0'; while (!is_eof() && !is_value_terminator(*cp)) { if (*cp == U'_') { if (!prev || !is_decimal_digit(*prev)) set_error_and_return_default("underscores may only follow digits"sv); prev = cp; advance_and_return_if_error_or_eof({}); continue; } else if (prev && *prev == U'_' && !is_decimal_digit(*cp)) set_error_and_return_default("underscores must be followed by digits"sv); else if (*cp == U'.') { // .1 // -.1 // +.1 (no integer part) if (!first_integer_part) set_error_and_return_default("expected decimal digit, saw '.'"sv); // 1.0e+.10 (exponent cannot have '.') else if (seen_exponent) set_error_and_return_default("expected exponent decimal digit or sign, saw '.'"sv); // 1.0.e+.10 // 1..0 // (multiple '.') else if (seen_decimal) set_error_and_return_default("expected decimal digit or exponent, saw '.'"sv); seen_decimal = true; } else if (is_match(*cp, U'e', U'E')) { if (prev && !is_decimal_digit(*prev)) set_error_and_return_default("expected decimal digit, saw '"sv, to_sv(*cp), "'"sv); // 1.0ee+10 (multiple 'e') else if (seen_exponent) set_error_and_return_default("expected decimal digit, saw '"sv, to_sv(*cp), "'"sv); seen_decimal = true; // implied seen_exponent = true; } else if (is_match(*cp, U'+', U'-')) { // 1.-0 (sign in mantissa) if (!seen_exponent) set_error_and_return_default("expected decimal digit or '.', saw '"sv, to_sv(*cp), "'"sv); // 1.0e1-0 (misplaced exponent sign) else if (!is_match(*prev, U'e', U'E')) set_error_and_return_default("expected exponent digit, saw '"sv, to_sv(*cp), "'"sv); } else if (length == sizeof(chars)) set_error_and_return_default( "exceeds maximum length of "sv, static_cast<uint64_t>(sizeof(chars)), " characters"sv ); else if (is_decimal_digit(*cp)) { if (!seen_decimal) { if (!first_integer_part) first_integer_part = static_cast<char>(cp->bytes[0]); else if (first_integer_part == '0') set_error_and_return_default("leading zeroes are prohibited"sv); } } else set_error_and_return_default("expected decimal digit, saw '"sv, to_sv(*cp), "'"sv); chars[length++] = static_cast<char>(cp->bytes[0]); prev = cp; advance_and_return_if_error({}); } // sanity-check ending state if (prev) { if (*prev == U'_') { set_error_and_return_if_eof({}); set_error_and_return_default("underscores must be followed by digits"sv); } else if (is_match(*prev, U'e', U'E', U'+', U'-', U'.')) { set_error_and_return_if_eof({}); set_error_and_return_default("expected decimal digit, saw '"sv, to_sv(*cp), "'"sv); } } // convert to double double result; #if TOML_FLOAT_CHARCONV { auto fc_result = std::from_chars(chars, chars + length, result); switch (fc_result.ec) { case std::errc{}: //ok return result * sign; case std::errc::invalid_argument: set_error_and_return_default( "'"sv, std::string_view{ chars, length }, "' could not be interpreted as a value"sv ); break; case std::errc::result_out_of_range: set_error_and_return_default( "'"sv, std::string_view{ chars, length }, "' is not representable in 64 bits"sv ); break; default: //?? set_error_and_return_default( "an unspecified error occurred while trying to interpret '"sv, std::string_view{ chars, length }, "' as a value"sv ); } } #else { std::stringstream ss; ss.imbue(std::locale::classic()); ss.write(chars, static_cast<std::streamsize>(length)); if ((ss >> result)) return result * sign; else set_error_and_return_default( "'"sv, std::string_view{ chars, length }, "' could not be interpreted as a value"sv ); } #endif } [[nodiscard]] double parse_hex_float() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_match(*cp, U'0', U'+', U'-')); push_parse_scope("hexadecimal floating-point"sv); #if TOML_LANG_UNRELEASED // toml/issues/562 (hexfloats) // sign const int sign = *cp == U'-' ? -1 : 1; if (is_match(*cp, U'+', U'-')) advance_and_return_if_error_or_eof({}); // '0' if (*cp != U'0') set_error_and_return_default(" expected '0', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // 'x' or 'X' if (!is_match(*cp, U'x', U'X')) set_error_and_return_default("expected 'x' or 'X', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // <HEX DIGITS> ([.]<HEX DIGITS>)? [pP] [+-]? <DEC DIGITS> // consume value fragments struct fragment { char chars[24]; size_t length; double value; }; fragment fragments[] = { {}, // mantissa, whole part {}, // mantissa, fractional part {} // exponent }; fragment* current_fragment = fragments; const utf8_codepoint* prev = {}; int exponent_sign = 1; while (!is_eof() && !is_value_terminator(*cp)) { if (*cp == U'_') { if (!prev || !is_hexadecimal_digit(*prev)) set_error_and_return_default("underscores may only follow digits"sv); prev = cp; advance_and_return_if_error_or_eof({}); continue; } else if (prev && *prev == U'_' && !is_hexadecimal_digit(*cp)) set_error_and_return_default("underscores must be followed by digits"sv); else if (*cp == U'.') { // 0x10.0p-.0 (exponent cannot have '.') if (current_fragment == fragments + 2) set_error_and_return_default("expected exponent digit or sign, saw '.'"sv); // 0x10.0.p-0 (multiple '.') else if (current_fragment == fragments + 1) set_error_and_return_default("expected hexadecimal digit or exponent, saw '.'"sv); else current_fragment++; } else if (is_match(*cp, U'p', U'P')) { // 0x10.0pp-0 (multiple 'p') if (current_fragment == fragments + 2) set_error_and_return_default("expected exponent digit or sign, saw '"sv, to_sv(*cp), "'"sv); // 0x.p-0 (mantissa is just '.') else if (fragments[0].length == 0_sz && fragments[1].length == 0_sz) set_error_and_return_default("expected hexadecimal digit, saw '"sv, to_sv(*cp), "'"sv); else current_fragment = fragments + 2; } else if (is_match(*cp, U'+', U'-')) { // 0x-10.0p-0 (sign in mantissa) if (current_fragment != fragments + 2) set_error_and_return_default("expected hexadecimal digit or '.', saw '"sv, to_sv(*cp), "'"sv); // 0x10.0p0- (misplaced exponent sign) else if (!is_match(*prev, U'p', U'P')) set_error_and_return_default("expected exponent digit, saw '"sv, to_sv(*cp), "'"sv); else exponent_sign = *cp == U'-' ? -1 : 1; } else if (current_fragment < fragments + 2 && !is_hexadecimal_digit(*cp)) set_error_and_return_default("expected hexadecimal digit or '.', saw '"sv, to_sv(*cp), "'"sv); else if (current_fragment == fragments + 2 && !is_decimal_digit(*cp)) set_error_and_return_default("expected exponent digit or sign, saw '"sv, to_sv(*cp), "'"sv); else if (current_fragment->length == sizeof(fragment::chars)) set_error_and_return_default( "fragment exceeeds maximum length of "sv, static_cast<uint64_t>(sizeof(fragment::chars)), " characters"sv ); else current_fragment->chars[current_fragment->length++] = static_cast<char>(cp->bytes[0]); prev = cp; advance_and_return_if_error({}); } // sanity-check ending state if (current_fragment != fragments + 2 || current_fragment->length == 0_sz) { set_error_and_return_if_eof({}); set_error_and_return_default("missing exponent"sv); } else if (prev && *prev == U'_') { set_error_and_return_if_eof({}); set_error_and_return_default("underscores must be followed by digits"sv); } // calculate values for the three fragments for (int fragment_idx = 0; fragment_idx < 3; fragment_idx++) { auto& f = fragments[fragment_idx]; const uint32_t base = fragment_idx == 2 ? 10 : 16; // left-trim zeroes const char* c = f.chars; size_t sig = {}; while (f.length && *c == '0') { f.length--; c++; sig++; } if (!f.length) continue; // calculate value auto place = 1u; for (size_t i = 0; i < f.length - 1_sz; i++) place *= base; uint32_t val{}; while (place) { if (base == 16) val += place * hex_to_dec(*c); else val += place * static_cast<uint32_t>(*c - '0'); if (fragment_idx == 1) sig++; c++; place /= base; } f.value = static_cast<double>(val); // shift the fractional part if (fragment_idx == 1) { while (sig--) f.value /= base; } } return (fragments[0].value + fragments[1].value) * pow(2.0, fragments[2].value * exponent_sign) * sign; #else // !TOML_LANG_UNRELEASED set_error_and_return_default( "hexadecimal floating-point values are not supported " "in TOML 1.0.0 and earlier"sv ); #endif // !TOML_LANG_UNRELEASED } template <uint64_t base> [[nodiscard]] int64_t parse_integer() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); using traits = parse_integer_traits<base>; push_parse_scope(traits::scope_qualifier); [[maybe_unused]] int64_t sign = 1; if constexpr (traits::is_signed) { sign = *cp == U'-' ? -1 : 1; if (is_match(*cp, U'+', U'-')) advance_and_return_if_error_or_eof({}); } if constexpr (base == 10) { if (!traits::is_digit(*cp)) set_error_and_return_default("expected expected digit or sign, saw '"sv, to_sv(*cp), "'"sv); } else { // '0' if (*cp != U'0') set_error_and_return_default("expected '0', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // 'b', 'o', 'x' if (*cp != traits::prefix_codepoint) set_error_and_return_default("expected '"sv, traits::prefix, "', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); } // consume value chars char chars[traits::buffer_length]; size_t length = {}; const utf8_codepoint* prev = {}; while (!is_eof() && !is_value_terminator(*cp)) { if (*cp == U'_') { if (!prev || !traits::is_digit(*prev)) set_error_and_return_default("underscores may only follow digits"sv); prev = cp; advance_and_return_if_error_or_eof({}); continue; } else if (prev && *prev == U'_' && !traits::is_digit(*cp)) set_error_and_return_default("underscores must be followed by digits"sv); else if (!traits::is_digit(*cp)) set_error_and_return_default("expected digit, saw '"sv, to_sv(*cp), "'"sv); else if (length == sizeof(chars)) set_error_and_return_default( "exceeds maximum length of "sv, static_cast<uint64_t>(sizeof(chars)), " characters"sv ); else chars[length++] = static_cast<char>(cp->bytes[0]); prev = cp; advance_and_return_if_error({}); } // sanity check ending state if (prev && *prev == U'_') { set_error_and_return_if_eof({}); set_error_and_return_default("underscores must be followed by digits"sv); } // check for leading zeroes if constexpr (base == 10) { if (chars[0] == '0') set_error_and_return_default("leading zeroes are prohibited"sv); } // single digits can be converted trivially if (length == 1_sz) { if constexpr (base == 16) return static_cast<int64_t>(hex_to_dec(chars[0])); else if constexpr (base <= 10) return static_cast<int64_t>(chars[0] - '0'); } // otherwise do the thing uint64_t result = {}; { const char* msd = chars; const char* end = msd + length; while (msd < end && *msd == '0') msd++; if (msd == end) return 0ll; uint64_t power = 1; while (--end >= msd) { if constexpr (base == 16) result += power * hex_to_dec(*end); else result += power * static_cast<uint64_t>(*end - '0'); power *= base; } } // range check if (result > static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()) + (sign < 0 ? 1ull : 0ull)) set_error_and_return_default( "'"sv, std::string_view{ chars, length }, "' is not representable in 64 bits"sv ); if constexpr (traits::is_signed) return static_cast<int64_t>(result) * sign; else return static_cast<int64_t>(result); } [[nodiscard]] date parse_date(bool part_of_datetime = false) TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_decimal_digit(*cp)); push_parse_scope("date"sv); // "YYYY" uint32_t digits[4]; if (!consume_digit_sequence(digits, 4_sz)) set_error_and_return_default("expected 4-digit year, saw '"sv, to_sv(*cp), "'"sv); const auto year = digits[3] + digits[2] * 10u + digits[1] * 100u + digits[0] * 1000u; const auto is_leap_year = (year % 4u == 0u) && ((year % 100u != 0u) || (year % 400u == 0u)); set_error_and_return_if_eof({}); // '-' if (*cp != U'-') set_error_and_return_default("expected '-', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "MM" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit month, saw '"sv, to_sv(*cp), "'"sv); const auto month = digits[1] + digits[0] * 10u; if (month == 0u || month > 12u) set_error_and_return_default( "expected month between 1 and 12 (inclusive), saw "sv, static_cast<uint64_t>(month) ); const auto max_days_in_month = month == 2u ? (is_leap_year ? 29u : 28u) : (month == 4u || month == 6u || month == 9u || month == 11u ? 30u : 31u) ; set_error_and_return_if_eof({}); // '-' if (*cp != U'-') set_error_and_return_default("expected '-', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "DD" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit day, saw '"sv, to_sv(*cp), "'"sv); const auto day = digits[1] + digits[0] * 10u; if (day == 0u || day > max_days_in_month) set_error_and_return_default( "expected day between 1 and "sv, static_cast<uint64_t>(max_days_in_month), " (inclusive), saw "sv, static_cast<uint64_t>(day) ); if (!part_of_datetime && !is_eof() && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); return { static_cast<uint16_t>(year), static_cast<uint8_t>(month), static_cast<uint8_t>(day) }; } [[nodiscard]] time parse_time(bool part_of_datetime = false) TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_decimal_digit(*cp)); push_parse_scope("time"sv); static constexpr auto max_digits = 9_sz; uint32_t digits[max_digits]; // "HH" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit hour, saw '"sv, to_sv(*cp), "'"sv); const auto hour = digits[1] + digits[0] * 10u; if (hour > 23u) set_error_and_return_default( "expected hour between 0 to 59 (inclusive), saw "sv, static_cast<uint64_t>(hour) ); set_error_and_return_if_eof({}); // ':' if (*cp != U':') set_error_and_return_default("expected ':', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "MM" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit minute, saw '"sv, to_sv(*cp), "'"sv); const auto minute = digits[1] + digits[0] * 10u; if (minute > 59u) set_error_and_return_default( "expected minute between 0 and 59 (inclusive), saw "sv, static_cast<uint64_t>(minute) ); auto time = ::toml::time{ static_cast<uint8_t>(hour), static_cast<uint8_t>(minute), }; // ':' if constexpr (TOML_LANG_UNRELEASED) // toml/issues/671 (allow omission of seconds) { if (is_eof() || is_value_terminator(*cp) || (part_of_datetime && is_match(*cp, U'+', U'-', U'Z'))) return time; } else set_error_and_return_if_eof({}); if (*cp != U':') set_error_and_return_default("expected ':', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "SS" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit second, saw '"sv, to_sv(*cp), "'"sv); const auto second = digits[1] + digits[0] * 10u; if (second > 59u) set_error_and_return_default( "expected second between 0 and 59 (inclusive), saw "sv, static_cast<uint64_t>(second) ); time.second = static_cast<uint8_t>(second); // '.' (early-exiting is allowed; fractional is optional) if (is_eof() || is_value_terminator(*cp) || (part_of_datetime && is_match(*cp, U'+', U'-', U'Z'))) return time; if (*cp != U'.') set_error_and_return_default("expected '.', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "FFFFFFFFF" auto digit_count = consume_variable_length_digit_sequence(digits, max_digits); if (!digit_count) { set_error_and_return_if_eof({}); set_error_and_return_default("expected fractional digits, saw '"sv, to_sv(*cp), "'"sv); } else if (!is_eof()) { if (digit_count == max_digits && is_decimal_digit(*cp)) set_error_and_return_default( "fractional component exceeds maximum precision of "sv, static_cast<uint64_t>(max_digits) ); else if (!part_of_datetime && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); } uint32_t value = 0u; uint32_t place = 1u; for (auto i = digit_count; i --> 0_sz;) { value += digits[i] * place; place *= 10u; } for (auto i = digit_count; i < max_digits; i++) //implicit zeros value *= 10u; time.nanosecond = value; return time; } [[nodiscard]] date_time parse_date_time() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_decimal_digit(*cp)); push_parse_scope("date-time"sv); // "YYYY-MM-DD" auto date = parse_date(true); set_error_and_return_if_eof({}); // ' ' or 'T' if (!is_match(*cp, U' ', U'T')) set_error_and_return_default("expected space or 'T', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "HH:MM:SS.FFFFFFFFF" auto time = parse_time(true); return_if_error({}); // no offset if (is_eof() || is_value_terminator(*cp)) return { date, time }; // zero offset ("Z") time_offset offset; if (*cp == U'Z') advance_and_return_if_error({}); // explicit offset ("+/-HH:MM") else if (is_match(*cp, U'+', U'-')) { push_parse_scope("date-time offset"sv); // sign int sign = *cp == U'-' ? -1 : 1; advance_and_return_if_error_or_eof({}); // "HH" int digits[2]; if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit hour, saw '"sv, to_sv(*cp), "'"sv); const auto hour = digits[1] + digits[0] * 10; if (hour > 23) set_error_and_return_default( "expected hour between 0 and 23 (inclusive), saw "sv, static_cast<int64_t>(hour) ); set_error_and_return_if_eof({}); // ':' if (*cp != U':') set_error_and_return_default("expected ':', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "MM" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit minute, saw '"sv, to_sv(*cp), "'"sv); const auto minute = digits[1] + digits[0] * 10; if (minute > 59) set_error_and_return_default( "expected minute between 0 and 59 (inclusive), saw "sv, static_cast<int64_t>(minute) ); offset.minutes = static_cast<int16_t>((hour * 60 + minute) * sign); } if (!is_eof() && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); return { date, time, offset }; } TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS, TOML_DISABLE_INIT_WARNINGS [[nodiscard]] toml::array* parse_array() TOML_MAY_THROW; [[nodiscard]] toml::table* parse_inline_table() TOML_MAY_THROW; [[nodiscard]] node* parse_value_known_prefixes() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(!is_control_character(*cp)); assert_or_assume(*cp != U'_'); switch (cp->value) { // arrays case U'[': return parse_array(); // inline tables case U'{': return parse_inline_table(); // floats beginning with '.' case U'.': return new value{ parse_float() }; // strings case U'"': [[fallthrough]]; case U'\'': return new value{ std::move(parse_string().value) }; // bools case U't': [[fallthrough]]; case U'f': [[fallthrough]]; case U'T': [[fallthrough]]; case U'F': return new value{ parse_boolean() }; // inf/nan case U'i': [[fallthrough]]; case U'I': [[fallthrough]]; case U'n': [[fallthrough]]; case U'N': return new value{ parse_inf_or_nan() }; } return nullptr; } [[nodiscard]] node* parse_value() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(!is_value_terminator(*cp)); push_parse_scope("value"sv); // check if it begins with some control character // (note that this will also fail for whitespace but we're assuming we've // called consume_leading_whitespace() before calling parse_value()) if TOML_UNLIKELY(is_control_character(*cp)) set_error_and_return_default("unexpected control character"sv); // underscores at the beginning else if (*cp == U'_') set_error_and_return_default("values may not begin with underscores"sv); const auto begin_pos = cp->position; node* val{}; do { assert_or_assume(!is_control_character(*cp)); assert_or_assume(*cp != U'_'); // detect the value type and parse accordingly, // starting with value types that can be detected // unambiguously from just one character. val = parse_value_known_prefixes(); return_if_error({}); if (val) break; // value types from here down require more than one character to unambiguously identify // so scan ahead and collect a set of value 'traits'. enum value_traits : int { has_nothing = 0, has_digits = 1, has_b = 1 << 1, // as second char only (0b) has_e = 1 << 2, // only float exponents has_o = 1 << 3, // as second char only (0o) has_p = 1 << 4, // only hexfloat exponents has_t = 1 << 5, has_x = 1 << 6, // as second or third char only (0x, -0x, +0x) has_z = 1 << 7, has_colon = 1 << 8, has_plus = 1 << 9, has_minus = 1 << 10, has_dot = 1 << 11, begins_sign = 1 << 12, begins_digit = 1 << 13, begins_zero = 1 << 14 // Q: "why not make these real values in the enum??" // A: because the visual studio debugger stops treating them as a set of flags if you add // non-pow2 values, making them much harder to debug. #define signs_msk (has_plus | has_minus) #define bzero_msk (begins_zero | has_digits) #define bdigit_msk (begins_digit | has_digits) }; value_traits traits = has_nothing; const auto has_any = [&](auto t) noexcept { return (traits & t) != has_nothing; }; const auto has_none = [&](auto t) noexcept { return (traits & t) == has_nothing; }; const auto add_trait = [&](auto t) noexcept { traits = static_cast<value_traits>(traits | t); }; // examine the first character to get the 'begins with' traits // (good fail-fast opportunity; all the remaining types begin with numeric digits or signs) if (is_decimal_digit(*cp)) add_trait(*cp == U'0' ? begins_zero : begins_digit); else if (is_match(*cp, U'+', U'-')) add_trait(begins_sign); else break; // scan the rest of the value to determine the remaining traits char32_t chars[utf8_buffered_reader::max_history_length]; size_t char_count = {}, advance_count = {}; bool eof_while_scanning = false; const auto scan = [&]() TOML_MAY_THROW { if (is_eof()) return; assert_or_assume(!is_value_terminator(*cp)); do { if (const auto c = **cp; c != U'_') { chars[char_count++] = c; if (is_decimal_digit(c)) add_trait(has_digits); else if (is_ascii_letter(c)) { assert_or_assume((c >= U'a' && c <= U'z') || (c >= U'A' && c <= U'Z')); switch (static_cast<char32_t>(c | 32u)) { case U'b': if (char_count == 2_sz && has_any(begins_zero)) add_trait(has_b); break; case U'e': if (char_count > 1_sz && has_none(has_b | has_o | has_p | has_t | has_x | has_z | has_colon) && (has_none(has_plus | has_minus) || has_any(begins_sign))) add_trait(has_e); break; case U'o': if (char_count == 2_sz && has_any(begins_zero)) add_trait(has_o); break; case U'p': if (has_any(has_x)) add_trait(has_p); break; case U'x': if ((char_count == 2_sz && has_any(begins_zero)) || (char_count == 3_sz && has_any(begins_sign) && chars[1] == U'0')) add_trait(has_x); break; case U't': add_trait(has_t); break; case U'z': add_trait(has_z); break; } } else if (c <= U':') { assert_or_assume(c < U'0' || c > U'9'); switch (c) { case U'+': add_trait(has_plus); break; case U'-': add_trait(has_minus); break; case U'.': add_trait(has_dot); break; case U':': add_trait(has_colon); break; } } } advance_and_return_if_error(); advance_count++; eof_while_scanning = is_eof(); } while (advance_count < utf8_buffered_reader::max_history_length && !is_eof() && !is_value_terminator(*cp) ); }; scan(); return_if_error({}); // force further scanning if this could have been a date-time with a space instead of a T if (char_count == 10_sz && traits == (bdigit_msk | has_minus) && chars[4] == U'-' && chars[7] == U'-' && !is_eof() && *cp == U' ') { const auto pre_advance_count = advance_count; const auto pre_scan_traits = traits; chars[char_count++] = *cp; add_trait(has_t); const auto backpedal = [&]() noexcept { go_back(advance_count - pre_advance_count); advance_count = pre_advance_count; traits = pre_scan_traits; char_count = 10_sz; }; advance_and_return_if_error({}); advance_count++; if (is_eof() || !is_decimal_digit(*cp)) backpedal(); else { chars[char_count++] = *cp; advance_and_return_if_error({}); advance_count++; scan(); return_if_error({}); if (char_count == 12_sz) backpedal(); } } // set the reader back to where we started go_back(advance_count); if (char_count < utf8_buffered_reader::max_history_length - 1_sz) chars[char_count] = U'\0'; // if after scanning ahead we still only have one value character, // the only valid value type is an integer. if (char_count == 1_sz) { if (has_any(begins_zero | begins_digit)) { val = new value{ static_cast<int64_t>(chars[0] - U'0') }; advance(); //skip the digit break; } //anything else would be ambiguous. else set_error_and_return_default( eof_while_scanning ? "encountered end-of-file"sv : "could not determine value type"sv ); } // now things that can be identified from two or more characters return_if_error({}); assert_or_assume(char_count >= 2_sz); // do some 'fuzzy matching' where there's no ambiguity, since that allows the specific // typed parse functions to take over and show better diagnostics if there's an issue // (as opposed to the fallback "could not determine type" message) if (has_any(has_p)) val = new value{ parse_hex_float() }; else if (has_any(has_x)) val = new value{ parse_integer<16>() }; else if (has_any(has_o)) val = new value{ parse_integer<8>() }; else if (has_any(has_b)) val = new value{ parse_integer<2>() }; else if (has_any(has_e) || (has_any(begins_zero | begins_digit) && chars[1] == U'.')) val = new value{ parse_float() }; else if (has_any(begins_sign)) { // single-digit signed integers if (char_count == 2_sz && has_any(has_digits)) { val = new value{ static_cast<int64_t>(chars[1] - U'0') * (chars[0] == U'-' ? -1LL : 1LL) }; advance(); //skip the sign advance(); //skip the digit break; } // simple signed floats (e.g. +1.0) if (is_decimal_digit(chars[1]) && chars[2] == U'.') val = new value{ parse_float() }; // signed infinity or nan else if (is_match(chars[1], U'i', U'n', U'I', U'N')) val = new value{ parse_inf_or_nan() }; } return_if_error({}); if (val) break; // match trait masks against what they can match exclusively. // all correct value parses will come out of this list, so doing this as a switch is likely to // be a better friend to the optimizer on the success path (failure path can be slow but that // doesn't matter much). switch (unbox_enum(traits)) { //=================== binary integers // 0b10 case bzero_msk | has_b: val = new value{ parse_integer<2>() }; break; //=================== octal integers // 0o10 case bzero_msk | has_o: val = new value{ parse_integer<8>() }; break; //=================== decimal integers // 00 // 10 // +10 // -10 case bzero_msk: [[fallthrough]]; case bdigit_msk: [[fallthrough]]; case begins_sign | has_digits | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_plus: val = new value{ parse_integer<10>() }; break; //=================== hexadecimal integers // 0x10 case bzero_msk | has_x: val = new value{ parse_integer<16>() }; break; //=================== decimal floats // 0e1 // 0e-1 // 0e+1 // 0.0 // 0.0e1 // 0.0e-1 // 0.0e+1 case bzero_msk | has_e: [[fallthrough]]; case bzero_msk | has_e | has_minus: [[fallthrough]]; case bzero_msk | has_e | has_plus: [[fallthrough]]; case bzero_msk | has_dot: [[fallthrough]]; case bzero_msk | has_dot | has_e: [[fallthrough]]; case bzero_msk | has_dot | has_e | has_minus: [[fallthrough]]; case bzero_msk | has_dot | has_e | has_plus: [[fallthrough]]; // 1e1 // 1e-1 // 1e+1 // 1.0 // 1.0e1 // 1.0e-1 // 1.0e+1 case bdigit_msk | has_e: [[fallthrough]]; case bdigit_msk | has_e | has_minus: [[fallthrough]]; case bdigit_msk | has_e | has_plus: [[fallthrough]]; case bdigit_msk | has_dot: [[fallthrough]]; case bdigit_msk | has_dot | has_e: [[fallthrough]]; case bdigit_msk | has_dot | has_e | has_minus: [[fallthrough]]; case bdigit_msk | has_dot | has_e | has_plus: [[fallthrough]]; // +1e1 // +1.0 // +1.0e1 // +1.0e+1 // +1.0e-1 // -1.0e+1 case begins_sign | has_digits | has_e | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_e | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_e | signs_msk: [[fallthrough]]; // -1e1 // -1e+1 // +1e-1 // -1.0 // -1.0e1 // -1.0e-1 case begins_sign | has_digits | has_e | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_e | signs_msk: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_e | has_minus: val = new value{ parse_float() }; break; //=================== hexadecimal floats // 0x10p0 // 0x10p-0 // 0x10p+0 case bzero_msk | has_x | has_p: [[fallthrough]]; case bzero_msk | has_x | has_p | has_minus: [[fallthrough]]; case bzero_msk | has_x | has_p | has_plus: [[fallthrough]]; // -0x10p0 // -0x10p-0 // +0x10p0 // +0x10p+0 // -0x10p+0 // +0x10p-0 case begins_sign | has_digits | has_x | has_p | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_x | has_p | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_x | has_p | signs_msk: [[fallthrough]]; // 0x10.1p0 // 0x10.1p-0 // 0x10.1p+0 case bzero_msk | has_x | has_dot | has_p: [[fallthrough]]; case bzero_msk | has_x | has_dot | has_p | has_minus: [[fallthrough]]; case bzero_msk | has_x | has_dot | has_p | has_plus: [[fallthrough]]; // -0x10.1p0 // -0x10.1p-0 // +0x10.1p0 // +0x10.1p+0 // -0x10.1p+0 // +0x10.1p-0 case begins_sign | has_digits | has_x | has_dot | has_p | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_x | has_dot | has_p | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_x | has_dot | has_p | signs_msk: val = new value{ parse_hex_float() }; break; //=================== times // HH:MM // HH:MM:SS // HH:MM:SS.FFFFFF case bzero_msk | has_colon: [[fallthrough]]; case bzero_msk | has_colon | has_dot: [[fallthrough]]; case bdigit_msk | has_colon: [[fallthrough]]; case bdigit_msk | has_colon | has_dot: val = new value{ parse_time() }; break; //=================== local dates // YYYY-MM-DD case bzero_msk | has_minus: [[fallthrough]]; case bdigit_msk | has_minus: val = new value{ parse_date() }; break; //=================== date-times // YYYY-MM-DDTHH:MM // YYYY-MM-DDTHH:MM-HH:MM // YYYY-MM-DDTHH:MM+HH:MM // YYYY-MM-DD HH:MM // YYYY-MM-DD HH:MM-HH:MM // YYYY-MM-DD HH:MM+HH:MM // YYYY-MM-DDTHH:MM:SS // YYYY-MM-DDTHH:MM:SS-HH:MM // YYYY-MM-DDTHH:MM:SS+HH:MM // YYYY-MM-DD HH:MM:SS // YYYY-MM-DD HH:MM:SS-HH:MM // YYYY-MM-DD HH:MM:SS+HH:MM case bzero_msk | has_minus | has_colon | has_t: [[fallthrough]]; case bzero_msk | signs_msk | has_colon | has_t: [[fallthrough]]; case bdigit_msk | has_minus | has_colon | has_t: [[fallthrough]]; case bdigit_msk | signs_msk | has_colon | has_t: [[fallthrough]]; // YYYY-MM-DDTHH:MM:SS.FFFFFF // YYYY-MM-DDTHH:MM:SS.FFFFFF-HH:MM // YYYY-MM-DDTHH:MM:SS.FFFFFF+HH:MM // YYYY-MM-DD HH:MM:SS.FFFFFF // YYYY-MM-DD HH:MM:SS.FFFFFF-HH:MM // YYYY-MM-DD HH:MM:SS.FFFFFF+HH:MM case bzero_msk | has_minus | has_colon | has_dot | has_t: [[fallthrough]]; case bzero_msk | signs_msk | has_colon | has_dot | has_t: [[fallthrough]]; case bdigit_msk | has_minus | has_colon | has_dot | has_t: [[fallthrough]]; case bdigit_msk | signs_msk | has_colon | has_dot | has_t: [[fallthrough]]; // YYYY-MM-DDTHH:MMZ // YYYY-MM-DD HH:MMZ // YYYY-MM-DDTHH:MM:SSZ // YYYY-MM-DD HH:MM:SSZ // YYYY-MM-DDTHH:MM:SS.FFFFFFZ // YYYY-MM-DD HH:MM:SS.FFFFFFZ case bzero_msk | has_minus | has_colon | has_z | has_t: [[fallthrough]]; case bzero_msk | has_minus | has_colon | has_dot | has_z | has_t: [[fallthrough]]; case bdigit_msk | has_minus | has_colon | has_z | has_t: [[fallthrough]]; case bdigit_msk | has_minus | has_colon | has_dot | has_z | has_t: val = new value{ parse_date_time() }; break; } #undef signs_msk #undef bzero_msk #undef bdigit_msk } while (false); if (!val) { set_error_at(begin_pos, "could not determine value type"sv); return_after_error({}); } #if !TOML_LANG_AT_LEAST(1, 0, 0) // toml/issues/665 (heterogeneous arrays) { if (auto arr = val->as_array(); arr && !arr->is_homogeneous()) { delete arr; set_error_at( begin_pos, "arrays cannot contain values of different types before TOML 1.0.0"sv ); return_after_error({}); } } #endif val->source_ = { begin_pos, current_position(1), reader.source_path() }; return val; } [[nodiscard]] parsed_key parse_key() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_bare_key_character(*cp) || is_string_delimiter(*cp)); push_parse_scope("key"sv); parsed_key key; recording_whitespace = false; while (!is_error()) { #if TOML_LANG_UNRELEASED // toml/issues/687 (unicode bare keys) if (is_unicode_combining_mark(*cp)) set_error_and_return_default("bare keys may not begin with unicode combining marks"sv); else #endif // bare_key_segment if (is_bare_key_character(*cp)) key.segments.emplace_back(parse_bare_key_segment()); // "quoted key segment" else if (is_string_delimiter(*cp)) { const auto begin_pos = cp->position; recording_whitespace = true; auto str = parse_string(); recording_whitespace = false; return_if_error({}); if (str.was_multi_line) { set_error_at( begin_pos, "multi-line strings are prohibited in "sv, key.segments.empty() ? ""sv : "dotted "sv, "keys"sv ); return_after_error({}); } else key.segments.emplace_back(std::move(str.value)); } // ??? else set_error_and_return_default( "expected bare key starting character or string delimiter, saw '"sv, to_sv(*cp), "'"sv ); // whitespace following the key segment consume_leading_whitespace(); // eof or no more key to come if (is_eof() || *cp != U'.') break; // was a dotted key, so go around again to consume the next segment advance_and_return_if_error_or_eof({}); consume_leading_whitespace(); set_error_and_return_if_eof({}); } return_if_error({}); return key; } [[nodiscard]] parsed_key_value_pair parse_key_value_pair() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_string_delimiter(*cp) || is_bare_key_character(*cp)); push_parse_scope("key-value pair"sv); // get the key start_recording(); auto key = parse_key(); stop_recording(1_sz); // skip past any whitespace that followed the key consume_leading_whitespace(); set_error_and_return_if_eof({}); // '=' if (*cp != U'=') set_error_and_return_default("expected '=', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // skip past any whitespace that followed the '=' consume_leading_whitespace(); return_if_error({}); set_error_and_return_if_eof({}); // get the value if (is_value_terminator(*cp)) set_error_and_return_default("expected value, saw '"sv, to_sv(*cp), "'"sv); return { std::move(key), parse_value() }; } [[nodiscard]] toml::table* parse_table_header() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'['); push_parse_scope("table header"sv); const auto header_begin_pos = cp->position; source_position header_end_pos; parsed_key key; bool is_arr = false; //parse header { // skip first '[' advance_and_return_if_error_or_eof({}); // skip past any whitespace that followed the '[' const bool had_leading_whitespace = consume_leading_whitespace(); set_error_and_return_if_eof({}); // skip second '[' (if present) if (*cp == U'[') { if (had_leading_whitespace) set_error_and_return_default( "[[array-of-table]] brackets must be contiguous (i.e. [ [ this ] ] is prohibited)"sv ); is_arr = true; advance_and_return_if_error_or_eof({}); // skip past any whitespace that followed the '[' consume_leading_whitespace(); set_error_and_return_if_eof({}); } // check for a premature closing ']' if (*cp == U']') set_error_and_return_default("tables with blank bare keys are explicitly prohibited"sv); // get the actual key start_recording(); key = parse_key(); stop_recording(1_sz); return_if_error({}); // skip past any whitespace that followed the key consume_leading_whitespace(); return_if_error({}); set_error_and_return_if_eof({}); // consume the closing ']' if (*cp != U']') set_error_and_return_default("expected ']', saw '"sv, to_sv(*cp), "'"sv); if (is_arr) { advance_and_return_if_error_or_eof({}); if (*cp != U']') set_error_and_return_default("expected ']', saw '"sv, to_sv(*cp), "'"sv); } advance_and_return_if_error({}); header_end_pos = current_position(1); // handle the rest of the line after the header consume_leading_whitespace(); if (!is_eof() && !consume_comment() && !consume_line_break()) set_error_and_return_default("expected a comment or whitespace, saw '"sv, to_sv(*cp), "'"sv); } TOML_ASSERT(!key.segments.empty()); // check if each parent is a table/table array, or can be created implicitly as a table. auto parent = &root; for (size_t i = 0; i < key.segments.size() - 1_sz; i++) { auto child = parent->get(key.segments[i]); if (!child) { child = parent->map.emplace( key.segments[i], new toml::table{} ).first->second.get(); implicit_tables.push_back(&child->ref_cast<table>()); child->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; parent = &child->ref_cast<table>(); } else if (child->is_table()) { parent = &child->ref_cast<table>(); } else if (child->is_array() && find(table_arrays, &child->ref_cast<array>())) { // table arrays are a special case; // the spec dictates we select the most recently declared element in the array. TOML_ASSERT(!child->ref_cast<array>().elements.empty()); TOML_ASSERT(child->ref_cast<array>().elements.back()->is_table()); parent = &child->ref_cast<array>().elements.back()->ref_cast<table>(); } else { if (!is_arr && child->type() == node_type::table) set_error_and_return_default( "cannot redefine existing table '"sv, to_sv(recording_buffer), "'"sv ); else set_error_and_return_default( "cannot redefine existing "sv, to_sv(child->type()), " '"sv, to_sv(recording_buffer), "' as "sv, is_arr ? "array-of-tables"sv : "table"sv ); } } // check the last parent table for a node matching the last key. // if there was no matching node, then sweet; // we can freely instantiate a new table/table array. auto matching_node = parent->get(key.segments.back()); if (!matching_node) { // if it's an array we need to make the array and it's first table element, // set the starting regions, and return the table element if (is_arr) { auto tab_arr = &parent->map.emplace( key.segments.back(), new toml::array{} ).first->second->ref_cast<array>(); table_arrays.push_back(tab_arr); tab_arr->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; tab_arr->elements.emplace_back(new toml::table{}); tab_arr->elements.back()->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; return &tab_arr->elements.back()->ref_cast<table>(); } //otherwise we're just making a table else { auto tab = &parent->map.emplace( key.segments.back(), new toml::table{}) .first->second->ref_cast<table>(); tab->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; return tab; } } // if there was already a matching node some sanity checking is necessary; // this is ok if we're making an array and the existing element is already an array (new element) // or if we're making a table and the existing element is an implicitly-created table (promote it), // otherwise this is a redefinition error. else { if (is_arr && matching_node->is_array() && find(table_arrays, &matching_node->ref_cast<array>())) { auto tab_arr = &matching_node->ref_cast<array>(); tab_arr->elements.emplace_back(new toml::table{}); tab_arr->elements.back()->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; return &tab_arr->elements.back()->ref_cast<table>(); } else if (!is_arr && matching_node->is_table() && !implicit_tables.empty()) { auto tbl = &matching_node->ref_cast<table>(); if (auto found = find(implicit_tables, tbl)) { implicit_tables.erase(implicit_tables.cbegin() + (found - implicit_tables.data())); tbl->source_.begin = header_begin_pos; tbl->source_.end = header_end_pos; return tbl; } } //if we get here it's a redefinition error. if (!is_arr && matching_node->type() == node_type::table) set_error_and_return_default("cannot redefine existing table '"sv, to_sv(recording_buffer), "'"sv); else set_error_and_return_default( "cannot redefine existing "sv, to_sv(matching_node->type()), " '"sv, to_sv(recording_buffer), "' as "sv, is_arr ? "array-of-tables"sv : "table"sv ); } } void parse_key_value_pair_and_insert(toml::table* tab) TOML_MAY_THROW { return_if_error(); assert_not_eof(); push_parse_scope("key-value pair"sv); auto kvp = parse_key_value_pair(); return_if_error(); TOML_ASSERT(kvp.key.segments.size() >= 1_sz); if (kvp.key.segments.size() > 1_sz) { for (size_t i = 0; i < kvp.key.segments.size() - 1_sz; i++) { auto child = tab->get(kvp.key.segments[i]); if (!child) { child = tab->map.emplace( std::move(kvp.key.segments[i]), new toml::table{} ).first->second.get(); dotted_key_tables.push_back(&child->ref_cast<table>()); dotted_key_tables.back()->inline_ = true; child->source_ = kvp.value->source_; } else if (!child->is_table() || !find(dotted_key_tables, &child->ref_cast<table>())) set_error("cannot redefine existing "sv, to_sv(child->type()), " as dotted key-value pair"sv); else child->source_.end = kvp.value->source_.end; return_if_error(); tab = &child->ref_cast<table>(); } } if (auto conflicting_node = tab->get(kvp.key.segments.back())) { if (conflicting_node->type() == kvp.value->type()) set_error( "cannot redefine existing "sv, to_sv(conflicting_node->type()), " '"sv, to_sv(recording_buffer), "'"sv ); else set_error( "cannot redefine existing "sv, to_sv(conflicting_node->type()), " '"sv, to_sv(recording_buffer), "' as "sv, to_sv(kvp.value->type()) ); } return_if_error(); tab->map.emplace( std::move(kvp.key.segments.back()), std::unique_ptr<node>{ kvp.value } ); } void parse_document() TOML_MAY_THROW { assert_not_error(); assert_not_eof(); push_parse_scope("root table"sv); table* current_table = &root; do { return_if_error(); // leading whitespace, line endings, comments if (consume_leading_whitespace() || consume_line_break() || consume_comment()) continue; // [tables] // [[table array]] else if (*cp == U'[') current_table = parse_table_header(); // bare_keys // dotted.keys // "quoted keys" else if (is_bare_key_character(*cp) || is_string_delimiter(*cp)) { push_parse_scope("key-value pair"sv); parse_key_value_pair_and_insert(current_table); // handle the rest of the line after the kvp // (this is not done in parse_key_value_pair() because that is also used for inline tables) consume_leading_whitespace(); return_if_error(); if (!is_eof() && !consume_comment() && !consume_line_break()) set_error("expected a comment or whitespace, saw '"sv, to_sv(*cp), "'"sv); } else // ?? set_error("expected keys, tables, whitespace or comments, saw '"sv, to_sv(*cp), "'"sv); } while (!is_eof()); auto eof_pos = current_position(1); root.source_.end = eof_pos; if (current_table && current_table != &root && current_table->source_.end <= current_table->source_.begin) current_table->source_.end = eof_pos; } static void update_region_ends(node& nde) noexcept { const auto type = nde.type(); if (type > node_type::array) return; if (type == node_type::table) { auto& tbl = nde.ref_cast<table>(); if (tbl.inline_) //inline tables (and all their inline descendants) are already correctly terminated return; auto end = nde.source_.end; for (auto& [k, v] : tbl.map) { (void)k; update_region_ends(*v); if (end < v->source_.end) end = v->source_.end; } } else //arrays { auto& arr = nde.ref_cast<array>(); auto end = nde.source_.end; for (auto& v : arr.elements) { update_region_ends(*v); if (end < v->source_.end) end = v->source_.end; } nde.source_.end = end; } } public: parser(utf8_reader_interface&& reader_) TOML_MAY_THROW : reader{ reader_ } { root.source_ = { prev_pos, prev_pos, reader.source_path() }; if (!reader.peek_eof()) { cp = reader.read_next(); #if !TOML_EXCEPTIONS if (reader.error()) { err = std::move(reader.error()); return; } #endif if (cp) parse_document(); } update_region_ends(root); } TOML_PUSH_WARNINGS TOML_DISABLE_INIT_WARNINGS [[nodiscard]] operator parse_result() && noexcept { #if TOML_EXCEPTIONS return { std::move(root) }; #else if (err) return parse_result{ *std::move(err) }; else return parse_result{ std::move(root) }; #endif } TOML_POP_WARNINGS }; TOML_EXTERNAL_LINKAGE toml::array* parser::parse_array() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'['); push_parse_scope("array"sv); // skip opening '[' advance_and_return_if_error_or_eof({}); auto arr = new array{}; auto& vals = arr->elements; enum parse_elem : int { none, comma, val }; parse_elem prev = none; while (!is_error()) { while (consume_leading_whitespace() || consume_line_break() || consume_comment()) continue; set_error_and_return_if_eof({}); // commas - only legal after a value if (*cp == U',') { if (prev == val) { prev = comma; advance_and_return_if_error_or_eof({}); continue; } set_error_and_return_default("expected value or closing ']', saw comma"sv); } // closing ']' else if (*cp == U']') { advance_and_return_if_error({}); break; } // must be a value else { if (prev == val) { set_error_and_return_default("expected comma or closing ']', saw '"sv, to_sv(*cp), "'"sv); continue; } prev = val; vals.emplace_back(parse_value()); } } return_if_error({}); return arr; } TOML_EXTERNAL_LINKAGE toml::table* parser::parse_inline_table() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'{'); push_parse_scope("inline table"sv); // skip opening '{' advance_and_return_if_error_or_eof({}); auto tab = new table{}; tab->inline_ = true; enum parse_elem : int { none, comma, kvp }; parse_elem prev = none; while (!is_error()) { if constexpr (TOML_LANG_UNRELEASED) // toml/issues/516 (newlines/trailing commas in inline tables) { while (consume_leading_whitespace() || consume_line_break() || consume_comment()) continue; } else { while (consume_leading_whitespace()) continue; } set_error_and_return_if_eof({}); // commas - only legal after a key-value pair if (*cp == U',') { if (prev == kvp) { prev = comma; advance_and_return_if_error_or_eof({}); } else set_error_and_return_default("expected key-value pair or closing '}', saw comma"sv); } // closing '}' else if (*cp == U'}') { if constexpr (!TOML_LANG_UNRELEASED) // toml/issues/516 (newlines/trailing commas in inline tables) { if (prev == comma) { set_error_and_return_default("expected key-value pair, saw closing '}' (dangling comma)"sv); continue; } } advance_and_return_if_error({}); break; } // key-value pair else if (is_string_delimiter(*cp) || is_bare_key_character(*cp)) { if (prev == kvp) set_error_and_return_default("expected comma or closing '}', saw '"sv, to_sv(*cp), "'"sv); else { prev = kvp; parse_key_value_pair_and_insert(tab); } } /// ??? else set_error_and_return_default("expected key or closing '}', saw '"sv, to_sv(*cp), "'"sv); } return_if_error({}); return tab; } TOML_API TOML_EXTERNAL_LINKAGE parse_result do_parse(utf8_reader_interface&& reader) TOML_MAY_THROW { return impl::parser{ std::move(reader) }; } TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS #undef push_parse_scope_2 #undef push_parse_scope_1 #undef push_parse_scope #undef TOML_RETURNS_BY_THROWING #undef is_eof #undef assert_not_eof #undef return_if_eof #undef is_error #undef return_after_error #undef assert_not_error #undef return_if_error #undef return_if_error_or_eof #undef set_error_and_return #undef set_error_and_return_default #undef set_error_and_return_if_eof #undef advance_and_return_if_error #undef advance_and_return_if_error_or_eof #undef assert_or_assume } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::string_view doc, std::string_view source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, source_path }); } TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::string_view doc, std::string&& source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, std::move(source_path) }); } #if TOML_WINDOWS_COMPAT TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::string_view doc, std::wstring_view source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, impl::narrow(source_path) }); } #endif // TOML_WINDOWS_COMPAT #ifdef __cpp_lib_char8_t TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::u8string_view doc, std::string_view source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, source_path }); } TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::u8string_view doc, std::string&& source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, std::move(source_path) }); } #if TOML_WINDOWS_COMPAT TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::u8string_view doc, std::wstring_view source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, impl::narrow(source_path) }); } #endif // TOML_WINDOWS_COMPAT #endif // __cpp_lib_char8_t inline namespace literals { TOML_API TOML_EXTERNAL_LINKAGE parse_result operator"" _toml(const char* str, size_t len) TOML_MAY_THROW { return parse(std::string_view{ str, len }); } #ifdef __cpp_lib_char8_t TOML_API TOML_EXTERNAL_LINKAGE parse_result operator"" _toml(const char8_t* str, size_t len) TOML_MAY_THROW { return parse(std::u8string_view{ str, len }); } #endif // __cpp_lib_char8_t } TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS } TOML_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS, TOML_DISABLE_PADDING_WARNINGS
;----------------------------------------------------------------------------- [bits 32] ; Global symbols global _start ;----------------------------------------------------------------------------- section .code ;================================================================================================================================ _start: push ebp mov ebp, esp push ecx push edx push ebx push esi push edi mov eax, [ebp + 8] mov ecx, [ebp + 12] mov edx, [ebp + 16] mov ebx, [ebp + 20] mov esi, [ebp + 24] mov edi, [ebp + 28] vmcall mov eax, edx pop edi pop esi pop ebx pop edx pop ecx pop ebp retn 24
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <game/generated/protocol.h> #include <game/server/gamecontext.h> #include "projectile.h" #include "game/server/city/items/plasma.h" CProjectile::CProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span, int Damage, bool Explosive, float Force, int SoundImpact, int Weapon) : CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) { m_Type = Type; m_Pos = Pos; m_Direction = Dir; m_LifeSpan = Span; m_Owner = Owner; m_Force = Force; m_Damage = Damage; m_SoundImpact = SoundImpact; m_Weapon = Weapon; m_StartTick = Server()->Tick(); m_Explosive = Explosive; m_Bounces = 0; GameWorld()->InsertEntity(this); } void CProjectile::Reset() { GameServer()->m_World.DestroyEntity(this); } vec2 CProjectile::GetPos(float Time) { float Curvature = 0; float Speed = 0; switch(m_Type) { case WEAPON_GRENADE: Curvature = GameServer()->Tuning()->m_GrenadeCurvature; Speed = GameServer()->Tuning()->m_GrenadeSpeed; break; case WEAPON_SHOTGUN: Curvature = GameServer()->Tuning()->m_ShotgunCurvature; Speed = GameServer()->Tuning()->m_ShotgunSpeed; break; case WEAPON_GUN: Curvature = GameServer()->Tuning()->m_GunCurvature; Speed = GameServer()->Tuning()->m_GunSpeed; break; } return CalcPos(m_Pos, m_Direction, Curvature, Speed, Time); } void CProjectile::Tick() { float Pt = (Server()->Tick()-m_StartTick-1)/(float)Server()->TickSpeed(); float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); vec2 PrevPos = GetPos(Pt); vec2 CurPos = GetPos(Ct); // City int Collide = GameServer()->Collision()->IntersectLine(PrevPos, CurPos, &CurPos, &m_BouncePos); CCharacter *OwnerChar = GameServer()->GetPlayerChar(m_Owner); CCharacter *TargetChr = GameServer()->m_World.IntersectCharacter(PrevPos, CurPos, 6.0f, CurPos, OwnerChar); if(TargetChr) { if(TargetChr->GetPlayer()->m_Insta) return; } m_LifeSpan--; bool Destroy = false; const int MAX_PLASMA = 4*16; CPlasma *apEnts[MAX_PLASMA]; int Num = GameServer()->m_World.FindEntities(CurPos, 1024, (CEntity**)apEnts, MAX_PLASMA, CGameWorld::ENTTYPE_PLASMA); for(int i = 0; i < Num; i++) { CPlasma *pTarget = apEnts[i]; if(pTarget) { if(distance(pTarget->m_Pos, CurPos) < 16) { pTarget->Reset(); Destroy = true; } } } int Bounces; // City if(OwnerChar && TargetChr) { if(OwnerChar->GetPlayer()->m_AccData.m_GunFreeze && m_Type == WEAPON_GUN && !TargetChr->GetPlayer()->m_God && !TargetChr->Protected() && !TargetChr->m_Frozen && !TargetChr->m_GunFreezeCooldown && !GameServer()->HasDmgDisabled(OwnerChar->GetPlayer()->GetCID(), TargetChr->GetPlayer()->GetCID()) && OwnerChar->GetPlayer()->m_AciveUpgrade[WEAPON_GUN] == UPGRADE_GUNFREEZE) { TargetChr->Freeze(OwnerChar->GetPlayer()->m_AccData.m_GunFreeze * Server()->TickSpeed()); TargetChr->m_GunFreezeCooldown = 5; } } if(OwnerChar) { Bounces = OwnerChar->Protected()?0:OwnerChar->GetPlayer()->m_AccData.m_GrenadeBounce; if(Collide && m_Weapon == WEAPON_GRENADE && m_Bounces <= Bounces) { vec2 TempPos = m_BouncePos; vec2 TempDir = m_Direction * 4.0f; GameServer()->Collision()->MovePoint(&TempPos, &TempDir, 1.0f, 0); m_Pos = TempPos; m_Direction = normalize(TempDir); m_StartTick = Server()->Tick(); m_Bounces++; } } if(TargetChr || Collide || m_LifeSpan < 0 || GameLayerClipped(CurPos) || Destroy) { if(m_LifeSpan >= 0 || m_Weapon == WEAPON_GRENADE) GameServer()->CreateSound(CurPos, m_SoundImpact); if(m_Explosive) GameServer()->CreateExplosion(CurPos, m_Owner, m_Weapon, false); else if(TargetChr) TargetChr->TakeDamage(m_Direction * max(0.001f, m_Force), m_Damage, m_Owner, m_Weapon); if((Bounces && (!Collide || m_Weapon != WEAPON_GRENADE || m_LifeSpan < 0 || m_Bounces > Bounces || !OwnerChar)) || !Bounces || Destroy) GameServer()->m_World.DestroyEntity(this); } } void CProjectile::FillInfo(CNetObj_Projectile *pProj) { pProj->m_X = (int)m_Pos.x; pProj->m_Y = (int)m_Pos.y; pProj->m_VelX = (int)(m_Direction.x*100.0f); pProj->m_VelY = (int)(m_Direction.y*100.0f); pProj->m_StartTick = m_StartTick; pProj->m_Type = m_Type; } void CProjectile::Snap(int SnappingClient) { float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); if(NetworkClipped(SnappingClient, GetPos(Ct))) return; CCharacter *pOwner = GameServer()->GetPlayerChar(m_Owner); if(pOwner) { if(pOwner->m_Invisible == 2 && !Server()->IsAuthed(SnappingClient) && SnappingClient != m_Owner) return; } CNetObj_Projectile *pProj = static_cast<CNetObj_Projectile *>(Server()->SnapNewItem(NETOBJTYPE_PROJECTILE, m_ID, sizeof(CNetObj_Projectile))); if(pProj) FillInfo(pProj); /*if(SnappingClient == m_Owner) { CNetEvent_Spawn *ev = (CNetEvent_Spawn *)GameServer()->m_Events.Create(NETEVENTTYPE_SPAWN, sizeof(CNetEvent_Spawn)); if(ev) { ev->m_X = (int)m_Pos.x; ev->m_Y = (int)m_Pos.y; } }*/ }
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/waf/model/DeleteSqlInjectionMatchSetResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::WAF::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DeleteSqlInjectionMatchSetResult::DeleteSqlInjectionMatchSetResult() { } DeleteSqlInjectionMatchSetResult::DeleteSqlInjectionMatchSetResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DeleteSqlInjectionMatchSetResult& DeleteSqlInjectionMatchSetResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("ChangeToken")) { m_changeToken = jsonValue.GetString("ChangeToken"); } return *this; }
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r15 push %r8 push %r9 push %rbp push %rcx push %rdi push %rsi lea addresses_UC_ht+0xbfdb, %rsi lea addresses_UC_ht+0x1687b, %rdi clflush (%rdi) nop nop nop nop nop sub $6872, %r12 mov $81, %rcx rep movsw nop nop xor %r12, %r12 lea addresses_WT_ht+0x1ce33, %r9 xor $32529, %r8 mov (%r9), %r15 nop nop nop nop xor %rcx, %rcx lea addresses_WC_ht+0x4a7b, %rsi lea addresses_A_ht+0x36fb, %rdi nop nop nop nop dec %rbp mov $76, %rcx rep movsb nop xor %r8, %r8 lea addresses_WC_ht+0x18bbb, %rdi nop nop nop and $3478, %rbp mov (%rdi), %r8w sub %rbp, %rbp lea addresses_A_ht+0xe873, %rsi lea addresses_UC_ht+0x1b07b, %rdi nop nop nop sub %r8, %r8 mov $97, %rcx rep movsb nop nop nop nop xor %rdi, %rdi lea addresses_A_ht+0x1e3cf, %rsi lea addresses_WC_ht+0x4c3b, %rdi clflush (%rsi) nop nop nop sub %r15, %r15 mov $37, %rcx rep movsw nop nop nop nop and %r8, %r8 lea addresses_WT_ht+0x69bb, %rsi lea addresses_WT_ht+0xfa1b, %rdi nop nop nop cmp %r12, %r12 mov $22, %rcx rep movsb nop cmp %r9, %r9 lea addresses_normal_ht+0x1807b, %r9 add %rdi, %rdi movw $0x6162, (%r9) nop nop nop nop sub %r12, %r12 lea addresses_D_ht+0xfdab, %rdi nop nop nop nop nop cmp $14658, %rbp mov $0x6162636465666768, %r8 movq %r8, (%rdi) nop nop nop nop and $51306, %rcx lea addresses_UC_ht+0x1523b, %rsi lea addresses_D_ht+0x1e7b, %rdi clflush (%rsi) nop and $15752, %r15 mov $90, %rcx rep movsb nop nop nop sub %rbp, %rbp pop %rsi pop %rdi pop %rcx pop %rbp pop %r9 pop %r8 pop %r15 pop %r12 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r8 push %rax push %rbx push %rcx push %rdx // Store lea addresses_A+0x154ab, %rcx nop xor $27921, %r8 mov $0x5152535455565758, %r12 movq %r12, (%rcx) nop nop nop nop cmp %rbx, %rbx // Store mov $0x87b, %rax nop nop nop add $32760, %rdx mov $0x5152535455565758, %rcx movq %rcx, (%rax) nop add $64818, %rcx // Load mov $0x4241640000000bfb, %rcx nop nop nop nop nop cmp $64693, %rbx mov (%rcx), %r12 nop nop nop sub %rdx, %rdx // Faulty Load lea addresses_A+0x1b07b, %r13 cmp %rbx, %rbx movups (%r13), %xmm6 vpextrq $1, %xmm6, %rax lea oracles, %r8 and $0xff, %rax shlq $12, %rax mov (%r8,%rax,1), %rax pop %rdx pop %rcx pop %rbx pop %rax pop %r8 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 3}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 8, 'type': 'addresses_WC_ht'}, 'dst': {'same': True, 'congruent': 7, 'type': 'addresses_A_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 5}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}, 'dst': {'same': True, 'congruent': 10, 'type': 'addresses_UC_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WC_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 4}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}, 'dst': {'same': True, 'congruent': 7, 'type': 'addresses_D_ht'}} {'00': 9147, '45': 12297, '48': 385} 00 45 45 00 00 45 45 45 00 45 00 00 45 45 00 00 00 00 45 00 45 45 45 45 00 00 00 00 45 00 00 45 00 00 48 45 00 45 45 45 45 45 45 00 00 00 45 45 45 45 45 45 45 00 45 45 00 45 45 00 45 00 45 45 00 45 45 00 48 45 00 45 00 00 45 45 45 45 45 00 45 00 00 45 00 00 45 00 45 45 00 45 00 00 45 00 00 45 45 45 00 45 00 45 45 45 45 45 45 45 00 00 00 45 45 45 45 45 00 45 00 48 45 00 45 45 45 45 45 00 45 45 45 00 45 00 00 00 45 00 45 00 45 45 45 00 45 45 00 00 45 00 45 00 00 45 45 00 45 00 00 00 45 45 45 45 00 45 45 00 45 45 00 45 45 45 45 48 45 45 00 00 45 00 00 45 45 00 45 00 00 45 00 00 45 45 00 00 45 00 45 45 00 45 45 00 48 45 00 00 45 00 45 00 00 45 00 00 45 45 45 45 00 00 45 00 45 45 45 00 45 00 00 00 45 00 45 45 00 45 00 45 45 45 00 45 45 45 45 45 00 00 45 00 45 45 00 45 00 00 45 45 00 45 45 00 45 45 45 45 00 00 00 00 45 00 45 00 45 00 45 00 45 45 45 45 45 45 45 00 45 45 45 00 00 00 45 00 45 00 00 45 00 45 45 00 00 45 45 00 45 45 45 00 00 00 00 00 00 00 00 45 00 45 45 00 45 45 45 45 45 45 00 45 00 45 45 00 45 00 00 00 45 45 45 45 45 00 45 45 45 00 45 00 45 00 45 00 00 00 00 45 00 00 45 00 45 45 00 00 45 45 45 45 45 45 00 45 45 45 45 00 45 00 45 45 00 00 45 00 45 45 45 45 00 00 45 45 45 45 45 45 45 00 45 45 00 45 00 00 45 45 45 45 00 45 45 45 45 00 00 45 00 45 00 00 45 45 00 45 45 00 00 00 00 00 45 00 48 45 45 48 00 00 45 45 00 45 45 00 00 45 45 00 00 45 00 00 00 45 00 45 45 00 45 00 45 45 45 45 00 45 45 45 45 45 00 45 00 45 00 45 45 00 45 00 00 00 45 45 45 45 00 45 45 45 45 00 00 45 45 00 45 00 00 45 00 45 45 00 45 00 00 00 00 45 00 00 45 45 00 45 45 45 45 45 00 00 45 00 00 00 45 00 45 45 00 00 45 45 45 45 45 45 00 00 45 45 00 45 45 00 00 45 00 45 00 45 00 00 45 45 45 00 45 00 45 45 00 45 00 00 45 45 00 45 45 48 45 45 00 45 00 45 45 00 45 45 45 00 45 45 00 45 00 45 45 45 00 45 00 00 45 45 00 00 45 45 45 45 45 45 45 00 45 45 45 45 45 45 45 45 45 45 00 45 45 48 45 45 00 00 00 45 00 45 45 00 45 00 00 00 45 45 00 45 00 00 00 00 45 45 45 00 45 00 45 45 45 45 45 00 45 45 45 00 45 00 00 45 45 00 45 45 45 45 45 00 00 00 45 45 00 45 45 45 45 45 00 45 00 00 45 00 45 45 45 45 45 00 45 45 45 45 45 45 45 00 45 00 45 45 00 45 00 00 45 00 45 00 00 45 45 45 45 45 00 45 00 45 00 00 00 45 00 45 00 45 45 00 48 00 00 45 00 45 00 45 00 45 45 00 45 45 00 45 45 00 45 00 45 00 00 45 45 45 45 00 00 45 00 48 00 00 45 45 00 45 45 00 00 45 00 00 00 45 00 45 45 00 45 45 00 45 00 45 45 00 00 00 45 45 00 45 45 00 45 00 00 45 00 00 45 00 45 00 00 45 45 45 00 00 45 45 00 45 00 00 45 45 45 45 45 00 45 45 00 45 00 45 45 45 45 45 45 00 45 45 00 45 45 45 00 00 45 00 00 00 00 45 00 45 45 45 45 45 45 45 00 00 45 45 45 00 45 00 45 00 45 45 45 00 45 00 45 00 00 45 00 48 45 45 45 45 00 00 48 00 00 45 00 48 00 00 45 45 45 45 00 45 00 45 00 00 45 00 00 00 00 45 00 45 00 00 00 45 45 00 45 00 45 45 00 45 00 00 45 00 45 00 45 00 00 45 45 00 45 00 00 45 00 00 45 45 00 45 00 45 45 45 00 00 45 00 45 45 45 00 45 00 00 45 00 00 45 45 45 45 00 00 00 45 00 00 45 45 45 48 45 00 45 00 00 45 00 00 45 00 00 45 */
#include "NodeService.h" void NodeService::MoveNode(int id, int x, int y){ }
// push constant 0: @0 D=A @SP A=M M=D @SP M=M+1 // pop local 0 // initializes sum = 0: @0 D=A @LCL D=M+D @R13 M=D @SP M=M-1 A=M D=M @R13 A=M M=D // label LOOP_START: ($LOOP_START) // push argument 0: @0 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 // push local 0: @0 D=A @LCL A=M+D D=M @SP A=M M=D @SP M=M+1 // add: @SP M=M-1 @SP A=M D=M @SP M=M-1 @SP A=M D=D+M @SP A=M M=D @SP M=M+1 // pop local 0 // sum = sum + counter: @0 D=A @LCL D=M+D @R13 M=D @SP M=M-1 A=M D=M @R13 A=M M=D // push argument 0: @0 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 // push constant 1: @1 D=A @SP A=M M=D @SP M=M+1 // sub: @SP M=M-1 @SP A=M D=M @SP M=M-1 @SP A=M D=M-D @SP A=M M=D @SP M=M+1 // pop argument 0 // counter--: @0 D=A @ARG D=M+D @R13 M=D @SP M=M-1 A=M D=M @R13 A=M M=D // push argument 0: @0 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 // if-goto LOOP_START // If counter > 0, goto LOOP_START: @SP M=M-1 A=M D=M @$LOOP_START D;JNE // push local 0: @0 D=A @LCL A=M+D D=M @SP A=M M=D @SP M=M+1
.data .text .globl main main: li $t0, 0x1100 li $t1, 0x1010 sub $t1,$t1,$t0 li $v0,10 syscall
; A083726: a(n) = (prime(n)+1)*n. ; 0,3,8,18,32,60,84,126,160,216,300,352,456,546,616,720,864,1020,1116,1292,1440,1554,1760,1932,2160,2450,2652,2808,3024,3190,3420,3968,4224,4554,4760,5250,5472,5846,6232,6552,6960,7380,7644,8256,8536,8910,9200,9964,10752,11172,11500,11934,12480,12826,13608,14190,14784,15390,15776,16402,16920,17324,18228,19404,19968,20410,20988,22244,22984,24012,24500,25134,25920,26864,27676,28500,29184,30030,31044,31758,32800,34020,34604,35856,36456,37400,38184,39150,40304,41118,41760,42588,44160,45384,46248 mov $1,$0 trn $1,1 seq $1,40 ; The prime numbers. add $1,1 mul $0,$1
SECTION "Map Blocks 1", ROMX DebugRoom_Blocks: INCBIN "maps/DebugRoom.blk" SandgemPokemonCenter1F_Blocks: JubilifePokemonCenter1F_Blocks: OreburghPokemonCenter1F_Blocks: FloaromaPokemonCenter1F_Blocks: INCBIN "maps/PokemonCenter1F.blk" Pokecenter2F_Blocks: INCBIN "maps/Pokecenter2F.blk" JubilifeWestGate_Blocks: CanalaveEastGate_Blocks: INCBIN "maps/EastWestGate.blk" TradeCenter_Blocks: TimeCapsule_Blocks: INCBIN "maps/TradeCenter.blk" Colosseum_Blocks: INCBIN "maps/Colosseum.blk" MobileTradeRoom_Blocks: INCBIN "maps/MobileTradeRoom.blk" MobileBattleRoom_Blocks: INCBIN "maps/MobileBattleRoom.blk" SandgemPokeMart_Blocks: JubilifePokeMart_Blocks: OreburghPokeMart_Blocks: FloaromaPokeMart_Blocks: INCBIN "maps/PokeMart.blk" TwinleafTown_Blocks: INCBIN "maps/TwinleafTown.blk" PlayersHouse1F_Blocks: INCBIN "maps/PlayersHouse1F.blk" PlayersHouse2F_Blocks: INCBIN "maps/PlayersHouse2F.blk" RivalHouse1F_Blocks: INCBIN "maps/RivalHouse1F.blk" RivalHouse2F_Blocks: INCBIN "maps/RivalHouse2F.blk" TwinleafHouse1_Blocks: TwinleafHouse2_Blocks: SandgemHouse1_Blocks: OreburghHouseW_Blocks: OreburghHouseN_Blocks: OreburghHouseE_Blocks: FloaromaHouseW_Blocks: FloaromaHouseE_Blocks: INCBIN "maps/HouseInterior1.blk" LakeVerityHigh_Blocks: INCBIN "maps/LakeVerityHigh.blk" LakeVerityLow_Blocks: INCBIN "maps/LakeVerityLow.blk" LakeVerityCavern_Blocks: INCBIN "maps/LakeVerityCavern.blk" Route201_Blocks: INCBIN "maps/Route201.blk" SandgemTown_Blocks: INCBIN "maps/SandgemTown.blk" RowansLab_Blocks: INCBIN "maps/RowansLab.blk" AssistantHouse1F_Blocks: INCBIN "maps/AssistantHouse1F.blk" AssistantHouse2F_Blocks: INCBIN "maps/AssistantHouse2F.blk" Route202_Blocks: INCBIN "maps/Route202.blk" Route219_Blocks: INCBIN "maps/Route219.blk" JubilifeCity_Blocks: INCBIN "maps/JubilifeCity.blk" Route203_Blocks: INCBIN "maps/Route203.blk" Route204S_Blocks: INCBIN "maps/Route204S.blk" JubilifeApartmentSE1F_Blocks: JubilifeApartmentNE1F_Blocks: JubilifeApartmentSW1F_Blocks: OreburghApartmentNW1F_Blocks: OreburghApartmentN1F_Blocks: OreburghApartmentE1F_Blocks: INCBIN "maps/Apartment1F.blk" JubilifeApartmentSE2F_Blocks: JubilifeApartmentNE2F_Blocks: JubilifeApartmentSW2F_Blocks: OreburghApartmentNW2F_Blocks: OreburghApartmentN2F_Blocks: OreburghApartmentE2F_Blocks: INCBIN "maps/Apartment2F.blk" TrainersSchool_Blocks: INCBIN "maps/TrainersSchool.blk" PoketchCompany1F_Blocks: INCBIN "maps/PoketchCompany1F.blk" PoketchCompany2F_Blocks: INCBIN "maps/PoketchCompany2F.blk" PoketchCompany3F_Blocks: INCBIN "maps/PoketchCompany3F.blk" TVStation1F_Blocks: INCBIN "maps/TVStation1F.blk" TVStation2F_Blocks: INCBIN "maps/TVStation2F.blk" TVStation2F2_Blocks: INCBIN "maps/TVStation2F2.blk" TVStation3F_Blocks: INCBIN "maps/TVStation3F.blk" TVStation3F2_Blocks: INCBIN "maps/TVStation3F2.blk" TVStation3F3_Blocks: INCBIN "maps/TVStation3F3.blk" TVStation4F_Blocks: INCBIN "maps/TVStation4F.blk" TVStationElevator_Blocks: INCBIN "maps/TVStationElevator.blk" PokemonCommunicationCenter_Blocks: INCBIN "maps/PokemonCommunicationCenter.blk" RavagedPath_Blocks: INCBIN "maps/RavagedPath.blk" Route218_Blocks: INCBIN "maps/Route218.blk" OreburghGate1F_Blocks: INCBIN "maps/OreburghGate1F.blk" OreburghGateB1F_Blocks: INCBIN "maps/OreburghGateB1F.blk" OreburghCity_Blocks: INCBIN "maps/OreburghCity.blk" OreburghGym_Blocks: INCBIN "maps/OreburghGym.blk" OreburghMuseum_Blocks: INCBIN "maps/OreburghMuseum.blk" OreburghMineB1F_Blocks: INCBIN "maps/OreburghMineB1F.blk" OreburghMineB2F_Blocks: INCBIN "maps/OreburghMineB2F.blk" Route207_Blocks: INCBIN "maps/Route207.blk" Route204N_Blocks: INCBIN "maps/Route204N.blk" FloaromaTown_Blocks: INCBIN "maps/FloaromaTown.blk" FloaromaFlowerShop_Blocks: INCBIN "maps/FloaromaFlowerShop.blk" SECTION "Map Blocks 2", ROMX SECTION "Map Blocks 3", ROMX ;if 0 ;SECTION "Map Blocks 1", ROMX ; ;Route32_Blocks: ; INCBIN "maps/Route32.blk" ; ;Route40_Blocks: ; INCBIN "maps/Route40.blk" ; ;Route36_Blocks: ; INCBIN "maps/Route36.blk" ; ;Route44_Blocks: ; INCBIN "maps/Route44.blk" ; ;Route28_Blocks: ; INCBIN "maps/Route28.blk" ; ;BetaPlayersHouse2F_Blocks: ; INCBIN "maps/unused/BetaPlayersHouse2F.blk" ; ;CeladonCity_Blocks: ; INCBIN "maps/CeladonCity.blk" ; ;SaffronCity_Blocks: ; INCBIN "maps/SaffronCity.blk" ; ;Route2_Blocks: ; INCBIN "maps/Route2.blk" ; ;ElmsHouse_Blocks: ; INCBIN "maps/ElmsHouse.blk" ; ;BetaSproutTower1_Blocks: ; INCBIN "maps/unused/BetaSproutTower1.blk" ; ;Route11_Blocks: ; INCBIN "maps/Route11.blk" ; ;BetaSproutTower5_Blocks: ; INCBIN "maps/unused/BetaSproutTower5.blk" ; ;Route15_Blocks: ; INCBIN "maps/Route15.blk" ; ;BetaSproutTower9_Blocks: ; INCBIN "maps/unused/BetaSproutTower9.blk" ; ;Route19_Blocks: ; INCBIN "maps/Route19.blk" ; ;BetaBlackthornCity_Blocks: ; INCBIN "maps/unused/BetaBlackthornCity.blk" ; ;Route10South_Blocks: ; INCBIN "maps/Route10South.blk" ; ;CinnabarPokecenter2FBeta_Blocks: ;CeruleanPokecenter2FBeta_Blocks: ;Route10Pokecenter2FBeta_Blocks: ;VermilionPokecenter2FBeta_Blocks: ;PewterPokecenter2FBeta_Blocks: ;FuchsiaPokecenter2FBeta_Blocks: ;LavenderPokecenter2FBeta_Blocks: ;CeladonPokecenter2FBeta_Blocks: ;ViridianPokecenter2FBeta_Blocks: ;SaffronPokecenter2FBeta_Blocks: ; ;Route41_Blocks: ; INCBIN "maps/Route41.blk" ; ;Route33_Blocks: ; INCBIN "maps/Route33.blk" ; ;Route45_Blocks: ; INCBIN "maps/Route45.blk" ; ;Route37_Blocks: ; INCBIN "maps/Route37.blk" ; ;LavenderTown_Blocks: ; INCBIN "maps/LavenderTown.blk" ; ;PalletTown_Blocks: ; INCBIN "maps/PalletTown.blk" ; ;Route25_Blocks: ; INCBIN "maps/Route25.blk" ; ;Route24_Blocks: ; INCBIN "maps/Route24.blk" ; ;BetaVioletCity_Blocks: ; INCBIN "maps/unused/BetaVioletCity.blk" ; ;Route3_Blocks: ; INCBIN "maps/Route3.blk" ; ;PewterCity_Blocks: ; INCBIN "maps/PewterCity.blk" ; ;BetaSilverCaveOutside_Blocks: ; INCBIN "maps/unused/BetaSilverCaveOutside.blk" ; ;BetaSproutTower2_Blocks: ; INCBIN "maps/unused/BetaSproutTower2.blk" ; ;Route12_Blocks: ; INCBIN "maps/Route12.blk" ; ;BetaGoldenrodCity_Blocks: ; INCBIN "maps/unused/BetaGoldenrodCity.blk" ; ;Route20_Blocks: ; INCBIN "maps/Route20.blk" ; ;BetaSproutTower6_Blocks: ; INCBIN "maps/unused/BetaSproutTower6.blk" ; ;BetaPokecenter_Blocks: ; INCBIN "maps/unused/BetaPokecenter.blk" ; ;Route26_Blocks: ; INCBIN "maps/Route26.blk" ; ;Route42_Blocks: ; INCBIN "maps/Route42.blk" ; ;Route34_Blocks: ; INCBIN "maps/Route34.blk" ; ;Route46_Blocks: ; INCBIN "maps/Route46.blk" ; ;FuchsiaCity_Blocks: ; INCBIN "maps/FuchsiaCity.blk" ; ;Route38_Blocks: ; INCBIN "maps/Route38.blk" ; ;BetaCianwoodCity_Blocks: ; INCBIN "maps/unused/BetaCianwoodCity.blk" ; ;OlivineTimsHouse_Blocks: ;OlivineHouseBeta_Blocks: ;OlivinePunishmentSpeechHouse_Blocks: ;OlivineGoodRodHouse_Blocks: ;Route39Farmhouse_Blocks: ;MahoganyRedGyaradosSpeechHouse_Blocks: ;BlackthornDragonSpeechHouse_Blocks: ;BlackthornEmysHouse_Blocks: ;MoveDeletersHouse_Blocks: ;CeruleanGymBadgeSpeechHouse_Blocks: ;CeruleanPoliceStation_Blocks: ;CeruleanTradeSpeechHouse_Blocks: ;BillsHouse_Blocks: ;CharcoalKiln_Blocks: ;LakeOfRageHiddenPowerHouse_Blocks: ;LakeOfRageMagikarpHouse_Blocks: ;GoldenrodHappinessRater_Blocks: ;BillsFamilysHouse_Blocks: ;GoldenrodPPSpeechHouse_Blocks: ;GoldenrodNameRater_Blocks: ;VermilionFishingSpeechHouse_Blocks: ;VermilionMagnetTrainSpeechHouse_Blocks: ;VermilionDiglettsCaveSpeechHouse_Blocks: ;BluesHouse_Blocks: ;PewterNidoranSpeechHouse_Blocks: ;PewterSnoozeSpeechHouse_Blocks: ;BillsBrothersHouse_Blocks: ;LavenderSpeechHouse_Blocks: ;LavenderNameRater_Blocks: ;Route12SuperRodHouse_Blocks: ;Route28SteelWingHouse_Blocks: ;CeladonMansionRoofHouse_Blocks: ;Route16FuchsiaSpeechHouse_Blocks: ;ManiasHouse_Blocks: ;CianwoodPharmacy_Blocks: ;CianwoodPhotoStudio_Blocks: ;CianwoodLugiaSpeechHouse_Blocks: ;PokeSeersHouse_Blocks: ;ViridianNicknameSpeechHouse_Blocks: ;Route2NuggetHouse_Blocks: ;PlayersNeighborsHouse_Blocks: ;Route26HealHouse_Blocks: ;DayOfWeekSiblingsHouse_Blocks: ;Route27SandstormHouse_Blocks: ;MrPsychicsHouse_Blocks: ;Route5CleanseTagHouse_Blocks: ;CherrygroveGymSpeechHouse_Blocks: ;GuideGentsHouse_Blocks: ;CherrygroveEvolutionSpeechHouse_Blocks: ;Route30BerryHouse_Blocks: ; INCBIN "maps/House1.blk" ; ;SafariZoneFuchsiaGateBeta_Blocks: ;Route19FuchsiaGate_Blocks: ;Route43MahoganyGate_Blocks: ;Route43Gate_Blocks: ;Route35GoldenrodGate_Blocks: ;Route36RuinsOfAlphGate_Blocks: ;Route34IlexForestGate_Blocks: ;Route6SaffronGate_Blocks: ;Route40BattleTowerGate_Blocks: ;Route2Gate_Blocks: ;Route29Route46Gate_Blocks: ;Route5SaffronGate_Blocks: ; INCBIN "maps/NorthSouthGate.blk" ; ;BetaEcruteakCity_Blocks: ; INCBIN "maps/unused/BetaEcruteakCity.blk" ; ;BetaCherrygroveCity_Blocks: ; INCBIN "maps/unused/BetaCherrygroveCity.blk" ; ;CinnabarIsland_Blocks: ; INCBIN "maps/CinnabarIsland.blk" ; ;Route4_Blocks: ; INCBIN "maps/Route4.blk" ; ;Route8_Blocks: ; INCBIN "maps/Route8.blk" ; ;BetaSproutTower3_Blocks: ; INCBIN "maps/unused/BetaSproutTower3.blk" ; ;ViridianCity_Blocks: ; INCBIN "maps/ViridianCity.blk" ; ;Route13_Blocks: ; INCBIN "maps/Route13.blk" ; ;Route21_Blocks: ; INCBIN "maps/Route21.blk" ; ;BetaSproutTower7_Blocks: ; INCBIN "maps/unused/BetaSproutTower7.blk" ; ;Route17_Blocks: ; INCBIN "maps/Route17.blk" ; ;BetaMahoganyTown_Blocks: ; INCBIN "maps/unused/BetaMahoganyTown.blk" ; ;Route27_Blocks: ; INCBIN "maps/Route27.blk" ; ;Route35_Blocks: ; INCBIN "maps/Route35.blk" ; ;Route43_Blocks: ; INCBIN "maps/Route43.blk" ; ;Route39_Blocks: ; INCBIN "maps/Route39.blk" ; ; ;Route38EcruteakGate_Blocks: ;Route42EcruteakGate_Blocks: ;Route32RuinsOfAlphGate_Blocks: ;IlexForestAzaleaGate_Blocks: ;Route15FuchsiaGate_Blocks: ;Route8SaffronGate_Blocks: ;Route16Gate_Blocks: ;Route7SaffronGate_Blocks: ;Route17Route18Gate_Blocks: ;Route31VioletGate_Blocks: ; INCBIN "maps/EastWestGate.blk" ; ;BetaAzaleaTown_Blocks: ; INCBIN "maps/unused/BetaAzaleaTown.blk" ; ;VermilionCity_Blocks: ; INCBIN "maps/VermilionCity.blk" ; ;BetaOlivineCity_Blocks: ; INCBIN "maps/unused/BetaOlivineCity.blk" ; ;BetaNewBarkTown_Blocks: ; INCBIN "maps/unused/BetaNewBarkTown.blk" ; ;CeruleanCity_Blocks: ; INCBIN "maps/CeruleanCity.blk" ; ;Route1_Blocks: ; INCBIN "maps/Route1.blk" ; ;Route5_Blocks: ; INCBIN "maps/Route5.blk" ; ;Route9_Blocks: ; INCBIN "maps/Route9.blk" ; ;Route22_Blocks: ; INCBIN "maps/Route22.blk" ; ; ;SECTION "Map Blocks 2", ROMX ; ;Route14_Blocks: ; INCBIN "maps/Route14.blk" ; ;BetaSproutTower8_Blocks: ; INCBIN "maps/unused/BetaSproutTower8.blk" ; ;OlivineMart_Blocks: ;EcruteakMart_Blocks: ;BlackthornMart_Blocks: ;CeruleanMart_Blocks: ;AzaleaMart_Blocks: ;VioletMart_Blocks: ;VermilionMart_Blocks: ;PewterMart_Blocks: ;FuchsiaMart_Blocks: ;LavenderMart_Blocks: ;ViridianMart_Blocks: ;SaffronMart_Blocks: ;CherrygroveMart_Blocks: ; INCBIN "maps/Mart.blk" ; ;Route10North_Blocks: ; INCBIN "maps/Route10North.blk" ; ;BetaLakeOfRage_Blocks: ; INCBIN "maps/unused/BetaLakeOfRage.blk" ; ;OlivinePokecenter1F_Blocks: ;MahoganyPokecenter1F_Blocks: ;EcruteakPokecenter1F_Blocks: ;BlackthornPokecenter1F_Blocks: ;CinnabarPokecenter1F_Blocks: ;CeruleanPokecenter1F_Blocks: ;Route10Pokecenter1F_Blocks: ;AzaleaPokecenter1F_Blocks: ;VioletPokecenter1F_Blocks: ;Route32Pokecenter1F_Blocks: ;GoldenrodPokecenter1F_Blocks: ;VermilionPokecenter1F_Blocks: ;PewterPokecenter1F_Blocks: ;FuchsiaPokecenter1F_Blocks: ;LavenderPokecenter1F_Blocks: ;SilverCavePokecenter1F_Blocks: ;CeladonPokecenter1F_Blocks: ;CianwoodPokecenter1F_Blocks: ;ViridianPokecenter1F_Blocks: ;SaffronPokecenter1F_Blocks: ;CherrygrovePokecenter1F_Blocks: ; INCBIN "maps/Pokecenter1F.blk" ; ;BetaPewterMuseumOfScience1F_Blocks: ; INCBIN "maps/unused/BetaPewterMuseumOfScience1F.blk" ; ;BetaPewterMuseumOfScience2F_Blocks: ; INCBIN "maps/unused/BetaPewterMuseumOfScience2F.blk" ; ;EarlsPokemonAcademy_Blocks: ; INCBIN "maps/EarlsPokemonAcademy.blk" ; ;BetaCinnabarPokemonLabHallway_Blocks: ; INCBIN "maps/unused/BetaCinnabarPokemonLabHallway.blk" ; ;BetaCinnabarPokemonLabRoom1_Blocks: ; INCBIN "maps/unused/BetaCinnabarPokemonLabRoom1.blk" ; ;BetaCinnabarPokemonLabRoom2_Blocks: ; INCBIN "maps/unused/BetaCinnabarPokemonLabRoom2.blk" ; ;BetaCinnabarPokemonLabRoom3_Blocks: ; INCBIN "maps/unused/BetaCinnabarPokemonLabRoom3.blk" ; ;GoldenrodDeptStore1F_Blocks: ;CeladonDeptStore1F_Blocks: ; INCBIN "maps/DeptStore1F.blk" ; ;GoldenrodDeptStore2F_Blocks: ;CeladonDeptStore2F_Blocks: ; INCBIN "maps/DeptStore2F.blk" ; ;GoldenrodDeptStore3F_Blocks: ;CeladonDeptStore3F_Blocks: ; INCBIN "maps/DeptStore3F.blk" ; ;GoldenrodDeptStore4F_Blocks: ;CeladonDeptStore4F_Blocks: ; INCBIN "maps/DeptStore4F.blk" ; ;GoldenrodDeptStore5F_Blocks: ;CeladonDeptStore5F_Blocks: ; INCBIN "maps/DeptStore5F.blk" ; ;GoldenrodDeptStore6F_Blocks: ;CeladonDeptStore6F_Blocks: ; INCBIN "maps/DeptStore6F.blk" ; ;GoldenrodDeptStoreElevator_Blocks: ;CeladonDeptStoreElevator_Blocks: ; INCBIN "maps/DeptStoreElevator.blk" ; ;CeladonMansion1F_Blocks: ; INCBIN "maps/CeladonMansion1F.blk" ; ;CeladonMansion2F_Blocks: ; INCBIN "maps/CeladonMansion2F.blk" ; ;CeladonMansion3F_Blocks: ; INCBIN "maps/CeladonMansion3F.blk" ; ;CeladonMansionRoof_Blocks: ; INCBIN "maps/CeladonMansionRoof.blk" ; ;BetaHouse_Blocks: ; INCBIN "maps/unused/BetaHouse.blk" ; ;CeladonGameCorner_Blocks: ; INCBIN "maps/CeladonGameCorner.blk" ; ;CeladonGameCornerPrizeRoom_Blocks: ; INCBIN "maps/CeladonGameCornerPrizeRoom.blk" ; ;EcruteakLugiaSpeechHouse_Blocks: ;EcruteakItemfinderHouse_Blocks: ;VioletNicknameSpeechHouse_Blocks: ;VioletKylesHouse_Blocks: ; INCBIN "maps/House2.blk" ; ;BetaUnionCave_Blocks: ; INCBIN "maps/unused/BetaUnionCave.blk" ; ;UnionCaveB1F_Blocks: ; INCBIN "maps/UnionCaveB1F.blk" ; ;UnionCaveB2F_Blocks: ; INCBIN "maps/UnionCaveB2F.blk" ; ;UnionCave1F_Blocks: ; INCBIN "maps/UnionCave1F.blk" ; ;NationalPark_Blocks: ;NationalParkBugContest_Blocks: ; INCBIN "maps/NationalPark.blk" ; ;Route5UndergroundPathEntrance_Blocks: ;Route6UndergroundPathEntrance_Blocks: ; INCBIN "maps/UndergroundPathEntrance.blk" ; ;BetaCapsuleHouse_Blocks: ; INCBIN "maps/unused/BetaCapsuleHouse.blk" ; ;KurtsHouse_Blocks: ; INCBIN "maps/KurtsHouse.blk" ; ;GoldenrodMagnetTrainStation_Blocks: ; INCBIN "maps/GoldenrodMagnetTrainStation.blk" ; ;RuinsOfAlphOutside_Blocks: ; INCBIN "maps/RuinsOfAlphOutside.blk" ; ;BetaRuinsOfAlphUnsolvedPuzzleRoom_Blocks: ; INCBIN "maps/unused/BetaRuinsOfAlphUnsolvedPuzzleRoom.blk" ; ;RuinsOfAlphInnerChamber_Blocks: ; INCBIN "maps/RuinsOfAlphInnerChamber.blk" ; ;RuinsOfAlphHoOhChamber_Blocks: ;RuinsOfAlphKabutoChamber_Blocks: ;RuinsOfAlphOmanyteChamber_Blocks: ;RuinsOfAlphAerodactylChamber_Blocks: ; INCBIN "maps/RuinsOfAlphPuzzleChamber.blk" ; ; ;BetaSproutTowerCutOut1_Blocks: ; INCBIN "maps/unused/BetaSproutTowerCutOut1.blk" ; ;SproutTower2F_Blocks: ; INCBIN "maps/SproutTower2F.blk" ; ;BetaSproutTowerCutOut2_Blocks: ; INCBIN "maps/unused/BetaSproutTowerCutOut2.blk" ; ;SproutTower3F_Blocks: ; INCBIN "maps/SproutTower3F.blk" ; ;BetaSproutTowerCutOut3_Blocks: ; INCBIN "maps/unused/BetaSproutTowerCutOut3.blk" ; ;RadioTower1F_Blocks: ; INCBIN "maps/RadioTower1F.blk" ; ;RadioTower2F_Blocks: ; INCBIN "maps/RadioTower2F.blk" ; ;RadioTower3F_Blocks: ; INCBIN "maps/RadioTower3F.blk" ; ;RadioTower4F_Blocks: ; INCBIN "maps/RadioTower4F.blk" ; ;RadioTower5F_Blocks: ; INCBIN "maps/RadioTower5F.blk" ; ;CherrygroveCity_Blocks: ; INCBIN "maps/CherrygroveCity.blk" ; ;AzaleaTown_Blocks: ; INCBIN "maps/AzaleaTown.blk" ; ;CianwoodCity_Blocks: ; INCBIN "maps/CianwoodCity.blk" ; ;GoldenrodCity_Blocks: ; INCBIN "maps/GoldenrodCity.blk" ; ;OlivineCity_Blocks: ; INCBIN "maps/OlivineCity.blk" ; ;EcruteakCity_Blocks: ; INCBIN "maps/EcruteakCity.blk" ; ;MahoganyTown_Blocks: ; INCBIN "maps/MahoganyTown.blk" ; ;LakeOfRage_Blocks: ; INCBIN "maps/LakeOfRage.blk" ; ;BlackthornCity_Blocks: ; INCBIN "maps/BlackthornCity.blk" ; ;SilverCaveOutside_Blocks: ; INCBIN "maps/SilverCaveOutside.blk" ; ;Route6_Blocks: ; INCBIN "maps/Route6.blk" ; ;Route7_Blocks: ; INCBIN "maps/Route7.blk" ; ;Route16_Blocks: ; INCBIN "maps/Route16.blk" ; ;Route18_Blocks: ; INCBIN "maps/Route18.blk" ; ;GoldenrodUnderground_Blocks: ; INCBIN "maps/GoldenrodUnderground.blk" ; ;GoldenrodUndergroundSwitchRoomEntrances_Blocks: ; INCBIN "maps/GoldenrodUndergroundSwitchRoomEntrances.blk" ; ;GoldenrodDeptStoreB1F_Blocks: ; INCBIN "maps/GoldenrodDeptStoreB1F.blk" ; ;GoldenrodUndergroundWarehouse_Blocks: ; INCBIN "maps/GoldenrodUndergroundWarehouse.blk" ; ;BetaElevator_Blocks: ; INCBIN "maps/unused/BetaElevator.blk" ; ;TinTower1F_Blocks: ; INCBIN "maps/TinTower1F.blk" ; ;TinTower2F_Blocks: ; INCBIN "maps/TinTower2F.blk" ; ;TinTower3F_Blocks: ; INCBIN "maps/TinTower3F.blk" ; ;TinTower4F_Blocks: ; INCBIN "maps/TinTower4F.blk" ; ;TinTower5F_Blocks: ; INCBIN "maps/TinTower5F.blk" ; ;TinTower6F_Blocks: ; INCBIN "maps/TinTower6F.blk" ; ;TinTower7F_Blocks: ; INCBIN "maps/TinTower7F.blk" ; ;TinTower8F_Blocks: ; INCBIN "maps/TinTower8F.blk" ; ;TinTower9F_Blocks: ; INCBIN "maps/TinTower9F.blk" ; ;TinTowerRoof_Blocks: ; INCBIN "maps/TinTowerRoof.blk" ; ;BurnedTower1F_Blocks: ; INCBIN "maps/BurnedTower1F.blk" ; ;BurnedTowerB1F_Blocks: ; INCBIN "maps/BurnedTowerB1F.blk" ; ;BetaCaveTestMap_Blocks: ; INCBIN "maps/unused/BetaCaveTestMap.blk" ; ;MountMortar1FOutside_Blocks: ; INCBIN "maps/MountMortar1FOutside.blk" ; ;MountMortar1FInside_Blocks: ; INCBIN "maps/MountMortar1FInside.blk" ; ;MountMortar2FInside_Blocks: ; INCBIN "maps/MountMortar2FInside.blk" ; ;MountMortarB1F_Blocks: ; INCBIN "maps/MountMortarB1F.blk" ; ;IcePath1F_Blocks: ; INCBIN "maps/IcePath1F.blk" ; ;IcePathB1F_Blocks: ; INCBIN "maps/IcePathB1F.blk" ; ;IcePathB2FMahoganySide_Blocks: ; INCBIN "maps/IcePathB2FMahoganySide.blk" ; ;IcePathB2FBlackthornSide_Blocks: ; INCBIN "maps/IcePathB2FBlackthornSide.blk" ; ;IcePathB3F_Blocks: ; INCBIN "maps/IcePathB3F.blk" ; ;WhirlIslandNW_Blocks: ; INCBIN "maps/WhirlIslandNW.blk" ; ;WhirlIslandNE_Blocks: ; INCBIN "maps/WhirlIslandNE.blk" ; ;WhirlIslandSW_Blocks: ; INCBIN "maps/WhirlIslandSW.blk" ; ;WhirlIslandCave_Blocks: ; INCBIN "maps/WhirlIslandCave.blk" ; ;WhirlIslandSE_Blocks: ; INCBIN "maps/WhirlIslandSE.blk" ; ;WhirlIslandB1F_Blocks: ; INCBIN "maps/WhirlIslandB1F.blk" ; ;WhirlIslandB2F_Blocks: ; INCBIN "maps/WhirlIslandB2F.blk" ; ;WhirlIslandLugiaChamber_Blocks: ; INCBIN "maps/WhirlIslandLugiaChamber.blk" ; ;SilverCaveRoom1_Blocks: ; INCBIN "maps/SilverCaveRoom1.blk" ; ;SilverCaveRoom2_Blocks: ; INCBIN "maps/SilverCaveRoom2.blk" ; ;SilverCaveRoom3_Blocks: ; INCBIN "maps/SilverCaveRoom3.blk" ; ;BetaRocketHideoutB2F_Blocks: ; INCBIN "maps/unused/BetaRocketHideoutB2F.blk" ; ;BetaRocketHideoutB1F_Blocks: ; INCBIN "maps/unused/BetaRocketHideoutB1F.blk" ; ;BetaRocketHideout1F_Blocks: ; INCBIN "maps/unused/BetaRocketHideout1F.blk" ; ;BetaRocketHideoutB3F_Blocks: ; INCBIN "maps/unused/BetaRocketHideoutB3F.blk" ; ;MahoganyMart1F_Blocks: ;MountMoonGiftShop_Blocks: ; INCBIN "maps/GiftShop.blk" ; ;TeamRocketBaseB1F_Blocks: ; INCBIN "maps/TeamRocketBaseB1F.blk" ; ;TeamRocketBaseB2F_Blocks: ; INCBIN "maps/TeamRocketBaseB2F.blk" ; ;TeamRocketBaseB3F_Blocks: ; INCBIN "maps/TeamRocketBaseB3F.blk" ; ;BetaRoute23_Blocks: ; INCBIN "maps/unused/BetaRoute23.blk" ; ;IndigoPlateauPokecenter1F_Blocks: ; INCBIN "maps/IndigoPlateauPokecenter1F.blk" ; ;WillsRoom_Blocks: ; INCBIN "maps/WillsRoom.blk" ; ;KogasRoom_Blocks: ; INCBIN "maps/KogasRoom.blk" ; ;BrunosRoom_Blocks: ; INCBIN "maps/BrunosRoom.blk" ; ;KarensRoom_Blocks: ; INCBIN "maps/KarensRoom.blk" ; ;AzaleaGym_Blocks: ; INCBIN "maps/AzaleaGym.blk" ; ;VioletGym_Blocks: ; INCBIN "maps/VioletGym.blk" ; ;GoldenrodGym_Blocks: ; INCBIN "maps/GoldenrodGym.blk" ; ;EcruteakGym_Blocks: ; INCBIN "maps/EcruteakGym.blk" ; ;MahoganyGym_Blocks: ; INCBIN "maps/MahoganyGym.blk" ; ;OlivineGym_Blocks: ; INCBIN "maps/OlivineGym.blk" ; ;BetaUnknownGym_Blocks: ; INCBIN "maps/unused/BetaUnknownGym.blk" ; ;CianwoodGym_Blocks: ; INCBIN "maps/CianwoodGym.blk" ; ;BlackthornGym1F_Blocks: ; INCBIN "maps/BlackthornGym1F.blk" ; ;BlackthornGym2F_Blocks: ; INCBIN "maps/BlackthornGym2F.blk" ; ;OlivineLighthouse1F_Blocks: ; INCBIN "maps/OlivineLighthouse1F.blk" ; ;OlivineLighthouse2F_Blocks: ; INCBIN "maps/OlivineLighthouse2F.blk" ; ;OlivineLighthouse3F_Blocks: ; INCBIN "maps/OlivineLighthouse3F.blk" ; ;OlivineLighthouse4F_Blocks: ; INCBIN "maps/OlivineLighthouse4F.blk" ; ;OlivineLighthouse5F_Blocks: ; INCBIN "maps/OlivineLighthouse5F.blk" ; ;OlivineLighthouse6F_Blocks: ; INCBIN "maps/OlivineLighthouse6F.blk" ; ; ;SECTION "Map Blocks 3", ROMX ; ;BetaSlowpokeWell1F_Blocks: ; INCBIN "maps/unused/BetaSlowpokeWell1F.blk" ; ;SlowpokeWellB1F_Blocks: ; INCBIN "maps/SlowpokeWellB1F.blk" ; ;SlowpokeWellB2F_Blocks: ; INCBIN "maps/SlowpokeWellB2F.blk" ; ;IlexForest_Blocks: ; INCBIN "maps/IlexForest.blk" ; ;DarkCaveVioletEntrance_Blocks: ; INCBIN "maps/DarkCaveVioletEntrance.blk" ; ;DarkCaveBlackthornEntrance_Blocks: ; INCBIN "maps/DarkCaveBlackthornEntrance.blk" ; ;RuinsOfAlphResearchCenter_Blocks: ; INCBIN "maps/RuinsOfAlphResearchCenter.blk" ; ;GoldenrodBikeShop_Blocks: ; INCBIN "maps/GoldenrodBikeShop.blk" ; ;DanceTheatre_Blocks: ; INCBIN "maps/DanceTheatre.blk" ; ;EcruteakTinTowerEntrance_Blocks: ; INCBIN "maps/EcruteakTinTowerEntrance.blk" ; ;GoldenrodGameCorner_Blocks: ; INCBIN "maps/GoldenrodGameCorner.blk" ; ;Route35NationalParkGate_Blocks: ; INCBIN "maps/Route35NationalParkGate.blk" ; ;Route36NationalParkGate_Blocks: ; INCBIN "maps/Route36NationalParkGate.blk" ; ;FastShip1F_Blocks: ; INCBIN "maps/FastShip1F.blk" ; ;FastShipB1F_Blocks: ; INCBIN "maps/FastShipB1F.blk" ; ;BetaFastShipInsideCutOut_Blocks: ; INCBIN "maps/unused/BetaFastShipInsideCutOut.blk" ; ;FastShipCabins_NNW_NNE_NE_Blocks: ; INCBIN "maps/FastShipCabins_NNW_NNE_NE.blk" ; ;FastShipCabins_SW_SSW_NW_Blocks: ; INCBIN "maps/FastShipCabins_SW_SSW_NW.blk" ; ;FastShipCabins_SE_SSE_CaptainsCabin_Blocks: ; INCBIN "maps/FastShipCabins_SE_SSE_CaptainsCabin.blk" ; ;OlivinePort_Blocks: ; INCBIN "maps/OlivinePort.blk" ; ;VermilionPort_Blocks: ; INCBIN "maps/VermilionPort.blk" ; ;OlivineCafe_Blocks: ;SafariZoneMainOffice_Blocks: ; INCBIN "maps/OlivineCafe.blk" ; ;SaffronMagnetTrainStation_Blocks: ; INCBIN "maps/SaffronMagnetTrainStation.blk" ; ;CeruleanGym_Blocks: ; INCBIN "maps/CeruleanGym.blk" ; ;VermilionGym_Blocks: ; INCBIN "maps/VermilionGym.blk" ; ;SaffronGym_Blocks: ; INCBIN "maps/SaffronGym.blk" ; ;PowerPlant_Blocks: ; INCBIN "maps/PowerPlant.blk" ; ;PokemonFanClub_Blocks: ;SafariZoneWardensHome_Blocks: ; INCBIN "maps/PokemonFanClub.blk" ; ;FightingDojo_Blocks: ; INCBIN "maps/FightingDojo.blk" ; ;SilphCo1F_Blocks: ; INCBIN "maps/SilphCo1F.blk" ; ;ViridianGym_Blocks: ; INCBIN "maps/ViridianGym.blk" ; ;TrainerHouse1F_Blocks: ; INCBIN "maps/TrainerHouse1F.blk" ; ;TrainerHouseB1F_Blocks: ; INCBIN "maps/TrainerHouseB1F.blk" ; ;RedsHouse1F_Blocks: ; INCBIN "maps/RedsHouse1F.blk" ; ;RedsHouse2F_Blocks: ; INCBIN "maps/RedsHouse2F.blk" ; ;OaksLab_Blocks: ; INCBIN "maps/OaksLab.blk" ; ;MrFujisHouse_Blocks: ; INCBIN "maps/MrFujisHouse.blk" ; ;LavRadioTower1F_Blocks: ; INCBIN "maps/LavRadioTower1F.blk" ; ;SilverCaveItemRooms_Blocks: ; INCBIN "maps/SilverCaveItemRooms.blk" ; ;DayCare_Blocks: ; INCBIN "maps/DayCare.blk" ; ;SoulHouse_Blocks: ; INCBIN "maps/SoulHouse.blk" ; ;PewterGym_Blocks: ; INCBIN "maps/PewterGym.blk" ; ;CeladonGym_Blocks: ; INCBIN "maps/CeladonGym.blk" ; ;BetaCeladonMansion1F_Blocks: ; INCBIN "maps/unused/BetaCeladonMansion1F.blk" ; ;CeladonCafe_Blocks: ; INCBIN "maps/CeladonCafe.blk" ; ;BetaCeladonMansion2F_Blocks: ; INCBIN "maps/unused/BetaCeladonMansion2F.blk" ; ;RockTunnel1F_Blocks: ; INCBIN "maps/RockTunnel1F.blk" ; ;RockTunnelB1F_Blocks: ; INCBIN "maps/RockTunnelB1F.blk" ; ;DiglettsCave_Blocks: ; INCBIN "maps/DiglettsCave.blk" ; ;MountMoon_Blocks: ; INCBIN "maps/MountMoon.blk" ; ;SeafoamGym_Blocks: ; INCBIN "maps/SeafoamGym.blk" ; ;MrPokemonsHouse_Blocks: ; INCBIN "maps/MrPokemonsHouse.blk" ; ;VictoryRoadGate_Blocks: ; INCBIN "maps/VictoryRoadGate.blk" ; ;OlivinePortPassage_Blocks: ;VermilionPortPassage_Blocks: ; INCBIN "maps/PortPassage.blk" ; ;FuchsiaGym_Blocks: ; INCBIN "maps/FuchsiaGym.blk" ; ;UndergroundPath_Blocks: ; INCBIN "maps/UndergroundPath.blk" ; ;Route39Barn_Blocks: ; INCBIN "maps/Route39Barn.blk" ; ;VictoryRoad_Blocks: ; INCBIN "maps/VictoryRoad.blk" ; ;Route23_Blocks: ; INCBIN "maps/Route23.blk" ; ;LancesRoom_Blocks: ; INCBIN "maps/LancesRoom.blk" ; ;HallOfFame_Blocks: ; INCBIN "maps/HallOfFame.blk" ; ;CopycatsHouse1F_Blocks: ; INCBIN "maps/CopycatsHouse1F.blk" ; ;CopycatsHouse2F_Blocks: ; INCBIN "maps/CopycatsHouse2F.blk" ; ;GoldenrodFlowerShop_Blocks: ; INCBIN "maps/GoldenrodFlowerShop.blk" ; ;MountMoonSquare_Blocks: ; INCBIN "maps/MountMoonSquare.blk" ; ;WiseTriosRoom_Blocks: ; INCBIN "maps/WiseTriosRoom.blk" ; ;DragonsDen1F_Blocks: ; INCBIN "maps/DragonsDen1F.blk" ; ;DragonsDenB1F_Blocks: ; INCBIN "maps/DragonsDenB1F.blk" ; ;TohjoFalls_Blocks: ; INCBIN "maps/TohjoFalls.blk" ; ;RuinsOfAlphHoOhItemRoom_Blocks: ;RuinsOfAlphKabutoItemRoom_Blocks: ;RuinsOfAlphOmanyteItemRoom_Blocks: ;RuinsOfAlphAerodactylItemRoom_Blocks: ; INCBIN "maps/RuinsOfAlphItemRoom.blk" ; ;RuinsOfAlphHoOhWordRoom_Blocks: ; INCBIN "maps/RuinsOfAlphHoOhWordRoom.blk" ; ;RuinsOfAlphKabutoWordRoom_Blocks: ; INCBIN "maps/RuinsOfAlphKabutoWordRoom.blk" ; ;RuinsOfAlphOmanyteWordRoom_Blocks: ; INCBIN "maps/RuinsOfAlphOmanyteWordRoom.blk" ; ;RuinsOfAlphAerodactylWordRoom_Blocks: ; INCBIN "maps/RuinsOfAlphAerodactylWordRoom.blk" ; ;DragonShrine_Blocks: ; INCBIN "maps/DragonShrine.blk" ; ;BattleTower1F_Blocks: ; INCBIN "maps/BattleTower1F.blk" ; ;BattleTowerBattleRoom_Blocks: ; INCBIN "maps/BattleTowerBattleRoom.blk" ; ;PokecomCenterAdminOfficeMobile_Blocks: ; INCBIN "maps/PokecomCenterAdminOfficeMobile.blk" ; ;BattleTowerHallway_Blocks: ; INCBIN "maps/BattleTowerHallway.blk" ; ;BattleTowerElevator_Blocks: ; INCBIN "maps/BattleTowerElevator.blk" ; ;BattleTowerOutside_Blocks: ; INCBIN "maps/BattleTowerOutside.blk" ; ;BetaBlank_Blocks: ; INCBIN "maps/unused/BetaBlank.blk" ; ;GoldenrodDeptStoreRoof_Blocks: ; INCBIN "maps/GoldenrodDeptStoreRoof.blk" ; ;endc
obj/user/sh.debug: 文件格式 elf32-i386 Disassembly of section .text: 00800020 <_start>: // starts us running when we are initially loaded into a new environment. .text .globl _start _start: // See if we were started with arguments on the stack cmpl $USTACKTOP, %esp 800020: 81 fc 00 e0 bf ee cmp $0xeebfe000,%esp jne args_exist 800026: 75 04 jne 80002c <args_exist> // If not, push dummy argc/argv arguments. // This happens when we are loaded by the kernel, // because the kernel does not know about passing arguments. pushl $0 800028: 6a 00 push $0x0 pushl $0 80002a: 6a 00 push $0x0 0080002c <args_exist>: args_exist: call libmain 80002c: e8 aa 09 00 00 call 8009db <libmain> 1: jmp 1b 800031: eb fe jmp 800031 <args_exist+0x5> 00800033 <_gettoken>: #define WHITESPACE " \t\r\n" #define SYMBOLS "<|>&;()" int _gettoken(char *s, char **p1, char **p2) { 800033: 55 push %ebp 800034: 89 e5 mov %esp,%ebp 800036: 56 push %esi 800037: 53 push %ebx 800038: 8b 5d 08 mov 0x8(%ebp),%ebx int t; if (s == 0) { 80003b: 85 db test %ebx,%ebx 80003d: 74 1d je 80005c <_gettoken+0x29> if (debug > 1) cprintf("GETTOKEN NULL\n"); return 0; } if (debug > 1) 80003f: 83 3d 00 50 80 00 01 cmpl $0x1,0x805000 800046: 7f 34 jg 80007c <_gettoken+0x49> cprintf("GETTOKEN: %s\n", s); *p1 = 0; 800048: 8b 45 0c mov 0xc(%ebp),%eax 80004b: c7 00 00 00 00 00 movl $0x0,(%eax) *p2 = 0; 800051: 8b 45 10 mov 0x10(%ebp),%eax 800054: c7 00 00 00 00 00 movl $0x0,(%eax) while (strchr(WHITESPACE, *s)) 80005a: eb 3a jmp 800096 <_gettoken+0x63> return 0; 80005c: be 00 00 00 00 mov $0x0,%esi if (debug > 1) 800061: 83 3d 00 50 80 00 01 cmpl $0x1,0x805000 800068: 7e 59 jle 8000c3 <_gettoken+0x90> cprintf("GETTOKEN NULL\n"); 80006a: 83 ec 0c sub $0xc,%esp 80006d: 68 60 32 80 00 push $0x803260 800072: e8 97 0a 00 00 call 800b0e <cprintf> 800077: 83 c4 10 add $0x10,%esp 80007a: eb 47 jmp 8000c3 <_gettoken+0x90> cprintf("GETTOKEN: %s\n", s); 80007c: 83 ec 08 sub $0x8,%esp 80007f: 53 push %ebx 800080: 68 6f 32 80 00 push $0x80326f 800085: e8 84 0a 00 00 call 800b0e <cprintf> 80008a: 83 c4 10 add $0x10,%esp 80008d: eb b9 jmp 800048 <_gettoken+0x15> *s++ = 0; 80008f: 83 c3 01 add $0x1,%ebx 800092: c6 43 ff 00 movb $0x0,-0x1(%ebx) while (strchr(WHITESPACE, *s)) 800096: 83 ec 08 sub $0x8,%esp 800099: 0f be 03 movsbl (%ebx),%eax 80009c: 50 push %eax 80009d: 68 7d 32 80 00 push $0x80327d 8000a2: e8 7a 12 00 00 call 801321 <strchr> 8000a7: 83 c4 10 add $0x10,%esp 8000aa: 85 c0 test %eax,%eax 8000ac: 75 e1 jne 80008f <_gettoken+0x5c> if (*s == 0) { 8000ae: 0f b6 03 movzbl (%ebx),%eax 8000b1: 84 c0 test %al,%al 8000b3: 75 29 jne 8000de <_gettoken+0xab> if (debug > 1) cprintf("EOL\n"); return 0; 8000b5: be 00 00 00 00 mov $0x0,%esi if (debug > 1) 8000ba: 83 3d 00 50 80 00 01 cmpl $0x1,0x805000 8000c1: 7f 09 jg 8000cc <_gettoken+0x99> **p2 = 0; cprintf("WORD: %s\n", *p1); **p2 = t; } return 'w'; } 8000c3: 89 f0 mov %esi,%eax 8000c5: 8d 65 f8 lea -0x8(%ebp),%esp 8000c8: 5b pop %ebx 8000c9: 5e pop %esi 8000ca: 5d pop %ebp 8000cb: c3 ret cprintf("EOL\n"); 8000cc: 83 ec 0c sub $0xc,%esp 8000cf: 68 82 32 80 00 push $0x803282 8000d4: e8 35 0a 00 00 call 800b0e <cprintf> 8000d9: 83 c4 10 add $0x10,%esp 8000dc: eb e5 jmp 8000c3 <_gettoken+0x90> if (strchr(SYMBOLS, *s)) { 8000de: 83 ec 08 sub $0x8,%esp 8000e1: 0f be c0 movsbl %al,%eax 8000e4: 50 push %eax 8000e5: 68 93 32 80 00 push $0x803293 8000ea: e8 32 12 00 00 call 801321 <strchr> 8000ef: 83 c4 10 add $0x10,%esp 8000f2: 85 c0 test %eax,%eax 8000f4: 74 2f je 800125 <_gettoken+0xf2> t = *s; 8000f6: 0f be 33 movsbl (%ebx),%esi *p1 = s; 8000f9: 8b 45 0c mov 0xc(%ebp),%eax 8000fc: 89 18 mov %ebx,(%eax) *s++ = 0; 8000fe: c6 03 00 movb $0x0,(%ebx) 800101: 83 c3 01 add $0x1,%ebx 800104: 8b 45 10 mov 0x10(%ebp),%eax 800107: 89 18 mov %ebx,(%eax) if (debug > 1) 800109: 83 3d 00 50 80 00 01 cmpl $0x1,0x805000 800110: 7e b1 jle 8000c3 <_gettoken+0x90> cprintf("TOK %c\n", t); 800112: 83 ec 08 sub $0x8,%esp 800115: 56 push %esi 800116: 68 87 32 80 00 push $0x803287 80011b: e8 ee 09 00 00 call 800b0e <cprintf> 800120: 83 c4 10 add $0x10,%esp 800123: eb 9e jmp 8000c3 <_gettoken+0x90> *p1 = s; 800125: 8b 45 0c mov 0xc(%ebp),%eax 800128: 89 18 mov %ebx,(%eax) while (*s && !strchr(WHITESPACE SYMBOLS, *s)) 80012a: eb 03 jmp 80012f <_gettoken+0xfc> s++; 80012c: 83 c3 01 add $0x1,%ebx while (*s && !strchr(WHITESPACE SYMBOLS, *s)) 80012f: 0f b6 03 movzbl (%ebx),%eax 800132: 84 c0 test %al,%al 800134: 74 18 je 80014e <_gettoken+0x11b> 800136: 83 ec 08 sub $0x8,%esp 800139: 0f be c0 movsbl %al,%eax 80013c: 50 push %eax 80013d: 68 8f 32 80 00 push $0x80328f 800142: e8 da 11 00 00 call 801321 <strchr> 800147: 83 c4 10 add $0x10,%esp 80014a: 85 c0 test %eax,%eax 80014c: 74 de je 80012c <_gettoken+0xf9> *p2 = s; 80014e: 8b 45 10 mov 0x10(%ebp),%eax 800151: 89 18 mov %ebx,(%eax) return 'w'; 800153: be 77 00 00 00 mov $0x77,%esi if (debug > 1) { 800158: 83 3d 00 50 80 00 01 cmpl $0x1,0x805000 80015f: 0f 8e 5e ff ff ff jle 8000c3 <_gettoken+0x90> t = **p2; 800165: 0f b6 33 movzbl (%ebx),%esi **p2 = 0; 800168: c6 03 00 movb $0x0,(%ebx) cprintf("WORD: %s\n", *p1); 80016b: 83 ec 08 sub $0x8,%esp 80016e: 8b 45 0c mov 0xc(%ebp),%eax 800171: ff 30 pushl (%eax) 800173: 68 9b 32 80 00 push $0x80329b 800178: e8 91 09 00 00 call 800b0e <cprintf> **p2 = t; 80017d: 8b 45 10 mov 0x10(%ebp),%eax 800180: 8b 00 mov (%eax),%eax 800182: 89 f2 mov %esi,%edx 800184: 88 10 mov %dl,(%eax) 800186: 83 c4 10 add $0x10,%esp return 'w'; 800189: be 77 00 00 00 mov $0x77,%esi 80018e: e9 30 ff ff ff jmp 8000c3 <_gettoken+0x90> 00800193 <gettoken>: int gettoken(char *s, char **p1) { 800193: 55 push %ebp 800194: 89 e5 mov %esp,%ebp 800196: 83 ec 08 sub $0x8,%esp 800199: 8b 45 08 mov 0x8(%ebp),%eax static int c, nc; static char* np1, *np2; if (s) { 80019c: 85 c0 test %eax,%eax 80019e: 74 22 je 8001c2 <gettoken+0x2f> nc = _gettoken(s, &np1, &np2); 8001a0: 83 ec 04 sub $0x4,%esp 8001a3: 68 0c 50 80 00 push $0x80500c 8001a8: 68 10 50 80 00 push $0x805010 8001ad: 50 push %eax 8001ae: e8 80 fe ff ff call 800033 <_gettoken> 8001b3: a3 08 50 80 00 mov %eax,0x805008 return 0; 8001b8: 83 c4 10 add $0x10,%esp 8001bb: b8 00 00 00 00 mov $0x0,%eax } c = nc; *p1 = np1; nc = _gettoken(np2, &np1, &np2); return c; } 8001c0: c9 leave 8001c1: c3 ret c = nc; 8001c2: a1 08 50 80 00 mov 0x805008,%eax 8001c7: a3 04 50 80 00 mov %eax,0x805004 *p1 = np1; 8001cc: 8b 15 10 50 80 00 mov 0x805010,%edx 8001d2: 8b 45 0c mov 0xc(%ebp),%eax 8001d5: 89 10 mov %edx,(%eax) nc = _gettoken(np2, &np1, &np2); 8001d7: 83 ec 04 sub $0x4,%esp 8001da: 68 0c 50 80 00 push $0x80500c 8001df: 68 10 50 80 00 push $0x805010 8001e4: ff 35 0c 50 80 00 pushl 0x80500c 8001ea: e8 44 fe ff ff call 800033 <_gettoken> 8001ef: a3 08 50 80 00 mov %eax,0x805008 return c; 8001f4: a1 04 50 80 00 mov 0x805004,%eax 8001f9: 83 c4 10 add $0x10,%esp 8001fc: eb c2 jmp 8001c0 <gettoken+0x2d> 008001fe <runcmd>: { 8001fe: 55 push %ebp 8001ff: 89 e5 mov %esp,%ebp 800201: 57 push %edi 800202: 56 push %esi 800203: 53 push %ebx 800204: 81 ec 64 04 00 00 sub $0x464,%esp gettoken(s, 0); 80020a: 6a 00 push $0x0 80020c: ff 75 08 pushl 0x8(%ebp) 80020f: e8 7f ff ff ff call 800193 <gettoken> 800214: 83 c4 10 add $0x10,%esp switch ((c = gettoken(0, &t))) { 800217: 8d 7d a4 lea -0x5c(%ebp),%edi argc = 0; 80021a: be 00 00 00 00 mov $0x0,%esi switch ((c = gettoken(0, &t))) { 80021f: 83 ec 08 sub $0x8,%esp 800222: 57 push %edi 800223: 6a 00 push $0x0 800225: e8 69 ff ff ff call 800193 <gettoken> 80022a: 89 c3 mov %eax,%ebx 80022c: 83 c4 10 add $0x10,%esp 80022f: 83 f8 3e cmp $0x3e,%eax 800232: 0f 84 1a 01 00 00 je 800352 <runcmd+0x154> 800238: 83 f8 3e cmp $0x3e,%eax 80023b: 7e 74 jle 8002b1 <runcmd+0xb3> 80023d: 83 f8 77 cmp $0x77,%eax 800240: 0f 84 e1 00 00 00 je 800327 <runcmd+0x129> 800246: 83 f8 7c cmp $0x7c,%eax 800249: 0f 85 37 02 00 00 jne 800486 <runcmd+0x288> if ((r = pipe(p)) < 0) { 80024f: 83 ec 0c sub $0xc,%esp 800252: 8d 85 9c fb ff ff lea -0x464(%ebp),%eax 800258: 50 push %eax 800259: e8 47 2a 00 00 call 802ca5 <pipe> 80025e: 83 c4 10 add $0x10,%esp 800261: 85 c0 test %eax,%eax 800263: 0f 88 6b 01 00 00 js 8003d4 <runcmd+0x1d6> if (debug) 800269: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 800270: 0f 85 79 01 00 00 jne 8003ef <runcmd+0x1f1> if ((r = fork()) < 0) { 800276: e8 5c 16 00 00 call 8018d7 <fork> 80027b: 89 c3 mov %eax,%ebx 80027d: 85 c0 test %eax,%eax 80027f: 0f 88 8b 01 00 00 js 800410 <runcmd+0x212> if (r == 0) { 800285: 85 c0 test %eax,%eax 800287: 0f 85 99 01 00 00 jne 800426 <runcmd+0x228> if (p[0] != 0) { 80028d: 8b 85 9c fb ff ff mov -0x464(%ebp),%eax 800293: 85 c0 test %eax,%eax 800295: 0f 85 ac 01 00 00 jne 800447 <runcmd+0x249> close(p[1]); 80029b: 83 ec 0c sub $0xc,%esp 80029e: ff b5 a0 fb ff ff pushl -0x460(%ebp) 8002a4: e8 19 1b 00 00 call 801dc2 <close> goto again; 8002a9: 83 c4 10 add $0x10,%esp 8002ac: e9 69 ff ff ff jmp 80021a <runcmd+0x1c> switch ((c = gettoken(0, &t))) { 8002b1: 85 c0 test %eax,%eax 8002b3: 75 2a jne 8002df <runcmd+0xe1> if(argc == 0) { 8002b5: 85 f6 test %esi,%esi 8002b7: 0f 85 db 01 00 00 jne 800498 <runcmd+0x29a> if (debug) 8002bd: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 8002c4: 0f 84 58 02 00 00 je 800522 <runcmd+0x324> cprintf("EMPTY COMMAND\n"); 8002ca: 83 ec 0c sub $0xc,%esp 8002cd: 68 29 33 80 00 push $0x803329 8002d2: e8 37 08 00 00 call 800b0e <cprintf> 8002d7: 83 c4 10 add $0x10,%esp 8002da: e9 43 02 00 00 jmp 800522 <runcmd+0x324> switch ((c = gettoken(0, &t))) { 8002df: 83 f8 3c cmp $0x3c,%eax 8002e2: 0f 85 9e 01 00 00 jne 800486 <runcmd+0x288> if (gettoken(0, &t) != 'w') { 8002e8: 83 ec 08 sub $0x8,%esp 8002eb: 8d 45 a4 lea -0x5c(%ebp),%eax 8002ee: 50 push %eax 8002ef: 6a 00 push $0x0 8002f1: e8 9d fe ff ff call 800193 <gettoken> 8002f6: 83 c4 10 add $0x10,%esp 8002f9: 83 f8 77 cmp $0x77,%eax 8002fc: 74 15 je 800313 <runcmd+0x115> cprintf("syntax error: < not followed by word\n"); 8002fe: 83 ec 0c sub $0xc,%esp 800301: 68 f8 33 80 00 push $0x8033f8 800306: e8 03 08 00 00 call 800b0e <cprintf> exit(); 80030b: e8 11 07 00 00 call 800a21 <exit> 800310: 83 c4 10 add $0x10,%esp panic("< redirection not implemented"); 800313: 83 ec 04 sub $0x4,%esp 800316: 68 b9 32 80 00 push $0x8032b9 80031b: 6a 3a push $0x3a 80031d: 68 d7 32 80 00 push $0x8032d7 800322: e8 0c 07 00 00 call 800a33 <_panic> if (argc == MAXARGS) { 800327: 83 fe 10 cmp $0x10,%esi 80032a: 74 0f je 80033b <runcmd+0x13d> argv[argc++] = t; 80032c: 8b 45 a4 mov -0x5c(%ebp),%eax 80032f: 89 44 b5 a8 mov %eax,-0x58(%ebp,%esi,4) 800333: 8d 76 01 lea 0x1(%esi),%esi break; 800336: e9 e4 fe ff ff jmp 80021f <runcmd+0x21> cprintf("too many arguments\n"); 80033b: 83 ec 0c sub $0xc,%esp 80033e: 68 a5 32 80 00 push $0x8032a5 800343: e8 c6 07 00 00 call 800b0e <cprintf> exit(); 800348: e8 d4 06 00 00 call 800a21 <exit> 80034d: 83 c4 10 add $0x10,%esp 800350: eb da jmp 80032c <runcmd+0x12e> if (gettoken(0, &t) != 'w') { 800352: 83 ec 08 sub $0x8,%esp 800355: 57 push %edi 800356: 6a 00 push $0x0 800358: e8 36 fe ff ff call 800193 <gettoken> 80035d: 83 c4 10 add $0x10,%esp 800360: 83 f8 77 cmp $0x77,%eax 800363: 75 3d jne 8003a2 <runcmd+0x1a4> if ((fd = open(t, O_WRONLY|O_CREAT|O_TRUNC)) < 0) { 800365: 83 ec 08 sub $0x8,%esp 800368: 68 01 03 00 00 push $0x301 80036d: ff 75 a4 pushl -0x5c(%ebp) 800370: e8 37 20 00 00 call 8023ac <open> 800375: 89 c3 mov %eax,%ebx 800377: 83 c4 10 add $0x10,%esp 80037a: 85 c0 test %eax,%eax 80037c: 78 3b js 8003b9 <runcmd+0x1bb> if (fd != 1) { 80037e: 83 fb 01 cmp $0x1,%ebx 800381: 0f 84 98 fe ff ff je 80021f <runcmd+0x21> dup(fd, 1); 800387: 83 ec 08 sub $0x8,%esp 80038a: 6a 01 push $0x1 80038c: 53 push %ebx 80038d: e8 80 1a 00 00 call 801e12 <dup> close(fd); 800392: 89 1c 24 mov %ebx,(%esp) 800395: e8 28 1a 00 00 call 801dc2 <close> 80039a: 83 c4 10 add $0x10,%esp 80039d: e9 7d fe ff ff jmp 80021f <runcmd+0x21> cprintf("syntax error: > not followed by word\n"); 8003a2: 83 ec 0c sub $0xc,%esp 8003a5: 68 20 34 80 00 push $0x803420 8003aa: e8 5f 07 00 00 call 800b0e <cprintf> exit(); 8003af: e8 6d 06 00 00 call 800a21 <exit> 8003b4: 83 c4 10 add $0x10,%esp 8003b7: eb ac jmp 800365 <runcmd+0x167> cprintf("open %s for write: %e", t, fd); 8003b9: 83 ec 04 sub $0x4,%esp 8003bc: 50 push %eax 8003bd: ff 75 a4 pushl -0x5c(%ebp) 8003c0: 68 e1 32 80 00 push $0x8032e1 8003c5: e8 44 07 00 00 call 800b0e <cprintf> exit(); 8003ca: e8 52 06 00 00 call 800a21 <exit> 8003cf: 83 c4 10 add $0x10,%esp 8003d2: eb aa jmp 80037e <runcmd+0x180> cprintf("pipe: %e", r); 8003d4: 83 ec 08 sub $0x8,%esp 8003d7: 50 push %eax 8003d8: 68 f7 32 80 00 push $0x8032f7 8003dd: e8 2c 07 00 00 call 800b0e <cprintf> exit(); 8003e2: e8 3a 06 00 00 call 800a21 <exit> 8003e7: 83 c4 10 add $0x10,%esp 8003ea: e9 7a fe ff ff jmp 800269 <runcmd+0x6b> cprintf("PIPE: %d %d\n", p[0], p[1]); 8003ef: 83 ec 04 sub $0x4,%esp 8003f2: ff b5 a0 fb ff ff pushl -0x460(%ebp) 8003f8: ff b5 9c fb ff ff pushl -0x464(%ebp) 8003fe: 68 00 33 80 00 push $0x803300 800403: e8 06 07 00 00 call 800b0e <cprintf> 800408: 83 c4 10 add $0x10,%esp 80040b: e9 66 fe ff ff jmp 800276 <runcmd+0x78> cprintf("fork: %e", r); 800410: 83 ec 08 sub $0x8,%esp 800413: 50 push %eax 800414: 68 35 38 80 00 push $0x803835 800419: e8 f0 06 00 00 call 800b0e <cprintf> exit(); 80041e: e8 fe 05 00 00 call 800a21 <exit> 800423: 83 c4 10 add $0x10,%esp if (p[1] != 1) { 800426: 8b 85 a0 fb ff ff mov -0x460(%ebp),%eax 80042c: 83 f8 01 cmp $0x1,%eax 80042f: 75 37 jne 800468 <runcmd+0x26a> close(p[0]); 800431: 83 ec 0c sub $0xc,%esp 800434: ff b5 9c fb ff ff pushl -0x464(%ebp) 80043a: e8 83 19 00 00 call 801dc2 <close> goto runit; 80043f: 83 c4 10 add $0x10,%esp 800442: e9 6e fe ff ff jmp 8002b5 <runcmd+0xb7> dup(p[0], 0); 800447: 83 ec 08 sub $0x8,%esp 80044a: 6a 00 push $0x0 80044c: 50 push %eax 80044d: e8 c0 19 00 00 call 801e12 <dup> close(p[0]); 800452: 83 c4 04 add $0x4,%esp 800455: ff b5 9c fb ff ff pushl -0x464(%ebp) 80045b: e8 62 19 00 00 call 801dc2 <close> 800460: 83 c4 10 add $0x10,%esp 800463: e9 33 fe ff ff jmp 80029b <runcmd+0x9d> dup(p[1], 1); 800468: 83 ec 08 sub $0x8,%esp 80046b: 6a 01 push $0x1 80046d: 50 push %eax 80046e: e8 9f 19 00 00 call 801e12 <dup> close(p[1]); 800473: 83 c4 04 add $0x4,%esp 800476: ff b5 a0 fb ff ff pushl -0x460(%ebp) 80047c: e8 41 19 00 00 call 801dc2 <close> 800481: 83 c4 10 add $0x10,%esp 800484: eb ab jmp 800431 <runcmd+0x233> panic("bad return %d from gettoken", c); 800486: 53 push %ebx 800487: 68 0d 33 80 00 push $0x80330d 80048c: 6a 70 push $0x70 80048e: 68 d7 32 80 00 push $0x8032d7 800493: e8 9b 05 00 00 call 800a33 <_panic> if (argv[0][0] != '/') { 800498: 8b 45 a8 mov -0x58(%ebp),%eax 80049b: 80 38 2f cmpb $0x2f,(%eax) 80049e: 0f 85 86 00 00 00 jne 80052a <runcmd+0x32c> argv[argc] = 0; 8004a4: c7 44 b5 a8 00 00 00 movl $0x0,-0x58(%ebp,%esi,4) 8004ab: 00 if (debug) { 8004ac: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 8004b3: 0f 85 99 00 00 00 jne 800552 <runcmd+0x354> if ((r = spawn(argv[0], (const char**) argv)) < 0) 8004b9: 83 ec 08 sub $0x8,%esp 8004bc: 8d 45 a8 lea -0x58(%ebp),%eax 8004bf: 50 push %eax 8004c0: ff 75 a8 pushl -0x58(%ebp) 8004c3: e8 9e 20 00 00 call 802566 <spawn> 8004c8: 89 c6 mov %eax,%esi 8004ca: 83 c4 10 add $0x10,%esp 8004cd: 85 c0 test %eax,%eax 8004cf: 0f 88 cb 00 00 00 js 8005a0 <runcmd+0x3a2> close_all(); 8004d5: e8 13 19 00 00 call 801ded <close_all> if (debug) 8004da: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 8004e1: 0f 85 06 01 00 00 jne 8005ed <runcmd+0x3ef> wait(r); 8004e7: 83 ec 0c sub $0xc,%esp 8004ea: 56 push %esi 8004eb: e8 31 29 00 00 call 802e21 <wait> if (debug) 8004f0: 83 c4 10 add $0x10,%esp 8004f3: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 8004fa: 0f 85 0c 01 00 00 jne 80060c <runcmd+0x40e> if (pipe_child) { 800500: 85 db test %ebx,%ebx 800502: 74 19 je 80051d <runcmd+0x31f> wait(pipe_child); 800504: 83 ec 0c sub $0xc,%esp 800507: 53 push %ebx 800508: e8 14 29 00 00 call 802e21 <wait> if (debug) 80050d: 83 c4 10 add $0x10,%esp 800510: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 800517: 0f 85 0a 01 00 00 jne 800627 <runcmd+0x429> exit(); 80051d: e8 ff 04 00 00 call 800a21 <exit> } 800522: 8d 65 f4 lea -0xc(%ebp),%esp 800525: 5b pop %ebx 800526: 5e pop %esi 800527: 5f pop %edi 800528: 5d pop %ebp 800529: c3 ret argv0buf[0] = '/'; 80052a: c6 85 a4 fb ff ff 2f movb $0x2f,-0x45c(%ebp) strcpy(argv0buf + 1, argv[0]); 800531: 83 ec 08 sub $0x8,%esp 800534: 50 push %eax 800535: 8d bd a4 fb ff ff lea -0x45c(%ebp),%edi 80053b: 8d 85 a5 fb ff ff lea -0x45b(%ebp),%eax 800541: 50 push %eax 800542: e8 d6 0c 00 00 call 80121d <strcpy> argv[0] = argv0buf; 800547: 89 7d a8 mov %edi,-0x58(%ebp) 80054a: 83 c4 10 add $0x10,%esp 80054d: e9 52 ff ff ff jmp 8004a4 <runcmd+0x2a6> cprintf("[%08x] SPAWN:", thisenv->env_id); 800552: a1 24 54 80 00 mov 0x805424,%eax 800557: 8b 40 48 mov 0x48(%eax),%eax 80055a: 83 ec 08 sub $0x8,%esp 80055d: 50 push %eax 80055e: 68 38 33 80 00 push $0x803338 800563: e8 a6 05 00 00 call 800b0e <cprintf> 800568: 8d 75 a8 lea -0x58(%ebp),%esi for (i = 0; argv[i]; i++) 80056b: 83 c4 10 add $0x10,%esp 80056e: eb 11 jmp 800581 <runcmd+0x383> cprintf(" %s", argv[i]); 800570: 83 ec 08 sub $0x8,%esp 800573: 50 push %eax 800574: 68 c0 33 80 00 push $0x8033c0 800579: e8 90 05 00 00 call 800b0e <cprintf> 80057e: 83 c4 10 add $0x10,%esp 800581: 83 c6 04 add $0x4,%esi for (i = 0; argv[i]; i++) 800584: 8b 46 fc mov -0x4(%esi),%eax 800587: 85 c0 test %eax,%eax 800589: 75 e5 jne 800570 <runcmd+0x372> cprintf("\n"); 80058b: 83 ec 0c sub $0xc,%esp 80058e: 68 80 32 80 00 push $0x803280 800593: e8 76 05 00 00 call 800b0e <cprintf> 800598: 83 c4 10 add $0x10,%esp 80059b: e9 19 ff ff ff jmp 8004b9 <runcmd+0x2bb> cprintf("spawn %s: %e\n", argv[0], r); 8005a0: 83 ec 04 sub $0x4,%esp 8005a3: 50 push %eax 8005a4: ff 75 a8 pushl -0x58(%ebp) 8005a7: 68 46 33 80 00 push $0x803346 8005ac: e8 5d 05 00 00 call 800b0e <cprintf> close_all(); 8005b1: e8 37 18 00 00 call 801ded <close_all> 8005b6: 83 c4 10 add $0x10,%esp if (pipe_child) { 8005b9: 85 db test %ebx,%ebx 8005bb: 0f 84 5c ff ff ff je 80051d <runcmd+0x31f> if (debug) 8005c1: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 8005c8: 0f 84 36 ff ff ff je 800504 <runcmd+0x306> cprintf("[%08x] WAIT pipe_child %08x\n", thisenv->env_id, pipe_child); 8005ce: a1 24 54 80 00 mov 0x805424,%eax 8005d3: 8b 40 48 mov 0x48(%eax),%eax 8005d6: 83 ec 04 sub $0x4,%esp 8005d9: 53 push %ebx 8005da: 50 push %eax 8005db: 68 7f 33 80 00 push $0x80337f 8005e0: e8 29 05 00 00 call 800b0e <cprintf> 8005e5: 83 c4 10 add $0x10,%esp 8005e8: e9 17 ff ff ff jmp 800504 <runcmd+0x306> cprintf("[%08x] WAIT %s %08x\n", thisenv->env_id, argv[0], r); 8005ed: a1 24 54 80 00 mov 0x805424,%eax 8005f2: 8b 40 48 mov 0x48(%eax),%eax 8005f5: 56 push %esi 8005f6: ff 75 a8 pushl -0x58(%ebp) 8005f9: 50 push %eax 8005fa: 68 54 33 80 00 push $0x803354 8005ff: e8 0a 05 00 00 call 800b0e <cprintf> 800604: 83 c4 10 add $0x10,%esp 800607: e9 db fe ff ff jmp 8004e7 <runcmd+0x2e9> cprintf("[%08x] wait finished\n", thisenv->env_id); 80060c: a1 24 54 80 00 mov 0x805424,%eax 800611: 8b 40 48 mov 0x48(%eax),%eax 800614: 83 ec 08 sub $0x8,%esp 800617: 50 push %eax 800618: 68 69 33 80 00 push $0x803369 80061d: e8 ec 04 00 00 call 800b0e <cprintf> 800622: 83 c4 10 add $0x10,%esp 800625: eb 92 jmp 8005b9 <runcmd+0x3bb> cprintf("[%08x] wait finished\n", thisenv->env_id); 800627: a1 24 54 80 00 mov 0x805424,%eax 80062c: 8b 40 48 mov 0x48(%eax),%eax 80062f: 83 ec 08 sub $0x8,%esp 800632: 50 push %eax 800633: 68 69 33 80 00 push $0x803369 800638: e8 d1 04 00 00 call 800b0e <cprintf> 80063d: 83 c4 10 add $0x10,%esp 800640: e9 d8 fe ff ff jmp 80051d <runcmd+0x31f> 00800645 <usage>: void usage(void) { 800645: 55 push %ebp 800646: 89 e5 mov %esp,%ebp 800648: 83 ec 14 sub $0x14,%esp cprintf("usage: sh [-dix] [command-file]\n"); 80064b: 68 48 34 80 00 push $0x803448 800650: e8 b9 04 00 00 call 800b0e <cprintf> exit(); 800655: e8 c7 03 00 00 call 800a21 <exit> } 80065a: 83 c4 10 add $0x10,%esp 80065d: c9 leave 80065e: c3 ret 0080065f <umain>: void umain(int argc, char **argv) { 80065f: 55 push %ebp 800660: 89 e5 mov %esp,%ebp 800662: 57 push %edi 800663: 56 push %esi 800664: 53 push %ebx 800665: 83 ec 30 sub $0x30,%esp int r, interactive, echocmds; struct Argstate args; interactive = '?'; echocmds = 0; argstart(&argc, argv, &args); 800668: 8d 45 d8 lea -0x28(%ebp),%eax 80066b: 50 push %eax 80066c: ff 75 0c pushl 0xc(%ebp) 80066f: 8d 45 08 lea 0x8(%ebp),%eax 800672: 50 push %eax 800673: e8 4b 14 00 00 call 801ac3 <argstart> while ((r = argnext(&args)) >= 0) 800678: 83 c4 10 add $0x10,%esp echocmds = 0; 80067b: c7 45 d4 00 00 00 00 movl $0x0,-0x2c(%ebp) interactive = '?'; 800682: bf 3f 00 00 00 mov $0x3f,%edi while ((r = argnext(&args)) >= 0) 800687: 8d 5d d8 lea -0x28(%ebp),%ebx switch (r) { case 'd': debug++; break; case 'i': interactive = 1; 80068a: be 01 00 00 00 mov $0x1,%esi while ((r = argnext(&args)) >= 0) 80068f: eb 03 jmp 800694 <umain+0x35> break; case 'x': echocmds = 1; 800691: 89 75 d4 mov %esi,-0x2c(%ebp) while ((r = argnext(&args)) >= 0) 800694: 83 ec 0c sub $0xc,%esp 800697: 53 push %ebx 800698: e8 56 14 00 00 call 801af3 <argnext> 80069d: 83 c4 10 add $0x10,%esp 8006a0: 85 c0 test %eax,%eax 8006a2: 78 23 js 8006c7 <umain+0x68> switch (r) { 8006a4: 83 f8 69 cmp $0x69,%eax 8006a7: 74 1a je 8006c3 <umain+0x64> 8006a9: 83 f8 78 cmp $0x78,%eax 8006ac: 74 e3 je 800691 <umain+0x32> 8006ae: 83 f8 64 cmp $0x64,%eax 8006b1: 74 07 je 8006ba <umain+0x5b> break; default: usage(); 8006b3: e8 8d ff ff ff call 800645 <usage> 8006b8: eb da jmp 800694 <umain+0x35> debug++; 8006ba: 83 05 00 50 80 00 01 addl $0x1,0x805000 break; 8006c1: eb d1 jmp 800694 <umain+0x35> interactive = 1; 8006c3: 89 f7 mov %esi,%edi 8006c5: eb cd jmp 800694 <umain+0x35> } if (argc > 2) 8006c7: 83 7d 08 02 cmpl $0x2,0x8(%ebp) 8006cb: 7f 1f jg 8006ec <umain+0x8d> usage(); if (argc == 2) { 8006cd: 83 7d 08 02 cmpl $0x2,0x8(%ebp) 8006d1: 74 20 je 8006f3 <umain+0x94> close(0); if ((r = open(argv[1], O_RDONLY)) < 0) panic("open %s: %e", argv[1], r); assert(r == 0); } if (interactive == '?') 8006d3: 83 ff 3f cmp $0x3f,%edi 8006d6: 74 77 je 80074f <umain+0xf0> 8006d8: 85 ff test %edi,%edi 8006da: bf c4 33 80 00 mov $0x8033c4,%edi 8006df: b8 00 00 00 00 mov $0x0,%eax 8006e4: 0f 44 f8 cmove %eax,%edi 8006e7: e9 08 01 00 00 jmp 8007f4 <umain+0x195> usage(); 8006ec: e8 54 ff ff ff call 800645 <usage> 8006f1: eb da jmp 8006cd <umain+0x6e> close(0); 8006f3: 83 ec 0c sub $0xc,%esp 8006f6: 6a 00 push $0x0 8006f8: e8 c5 16 00 00 call 801dc2 <close> if ((r = open(argv[1], O_RDONLY)) < 0) 8006fd: 83 c4 08 add $0x8,%esp 800700: 6a 00 push $0x0 800702: 8b 45 0c mov 0xc(%ebp),%eax 800705: ff 70 04 pushl 0x4(%eax) 800708: e8 9f 1c 00 00 call 8023ac <open> 80070d: 83 c4 10 add $0x10,%esp 800710: 85 c0 test %eax,%eax 800712: 78 1d js 800731 <umain+0xd2> assert(r == 0); 800714: 85 c0 test %eax,%eax 800716: 74 bb je 8006d3 <umain+0x74> 800718: 68 a8 33 80 00 push $0x8033a8 80071d: 68 af 33 80 00 push $0x8033af 800722: 68 21 01 00 00 push $0x121 800727: 68 d7 32 80 00 push $0x8032d7 80072c: e8 02 03 00 00 call 800a33 <_panic> panic("open %s: %e", argv[1], r); 800731: 83 ec 0c sub $0xc,%esp 800734: 50 push %eax 800735: 8b 45 0c mov 0xc(%ebp),%eax 800738: ff 70 04 pushl 0x4(%eax) 80073b: 68 9c 33 80 00 push $0x80339c 800740: 68 20 01 00 00 push $0x120 800745: 68 d7 32 80 00 push $0x8032d7 80074a: e8 e4 02 00 00 call 800a33 <_panic> interactive = iscons(0); 80074f: 83 ec 0c sub $0xc,%esp 800752: 6a 00 push $0x0 800754: e8 04 02 00 00 call 80095d <iscons> 800759: 89 c7 mov %eax,%edi 80075b: 83 c4 10 add $0x10,%esp 80075e: e9 75 ff ff ff jmp 8006d8 <umain+0x79> while (1) { char *buf; buf = readline(interactive ? "$ " : NULL); if (buf == NULL) { if (debug) 800763: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 80076a: 75 0a jne 800776 <umain+0x117> cprintf("EXITING\n"); exit(); // end of file 80076c: e8 b0 02 00 00 call 800a21 <exit> 800771: e9 94 00 00 00 jmp 80080a <umain+0x1ab> cprintf("EXITING\n"); 800776: 83 ec 0c sub $0xc,%esp 800779: 68 c7 33 80 00 push $0x8033c7 80077e: e8 8b 03 00 00 call 800b0e <cprintf> 800783: 83 c4 10 add $0x10,%esp 800786: eb e4 jmp 80076c <umain+0x10d> } if (debug) cprintf("LINE: %s\n", buf); 800788: 83 ec 08 sub $0x8,%esp 80078b: 53 push %ebx 80078c: 68 d0 33 80 00 push $0x8033d0 800791: e8 78 03 00 00 call 800b0e <cprintf> 800796: 83 c4 10 add $0x10,%esp 800799: eb 7c jmp 800817 <umain+0x1b8> if (buf[0] == '#') continue; if (echocmds) printf("# %s\n", buf); 80079b: 83 ec 08 sub $0x8,%esp 80079e: 53 push %ebx 80079f: 68 da 33 80 00 push $0x8033da 8007a4: e8 a7 1d 00 00 call 802550 <printf> 8007a9: 83 c4 10 add $0x10,%esp 8007ac: eb 78 jmp 800826 <umain+0x1c7> if (debug) cprintf("BEFORE FORK\n"); 8007ae: 83 ec 0c sub $0xc,%esp 8007b1: 68 e0 33 80 00 push $0x8033e0 8007b6: e8 53 03 00 00 call 800b0e <cprintf> 8007bb: 83 c4 10 add $0x10,%esp 8007be: eb 73 jmp 800833 <umain+0x1d4> if ((r = fork()) < 0) panic("fork: %e", r); 8007c0: 50 push %eax 8007c1: 68 35 38 80 00 push $0x803835 8007c6: 68 38 01 00 00 push $0x138 8007cb: 68 d7 32 80 00 push $0x8032d7 8007d0: e8 5e 02 00 00 call 800a33 <_panic> if (debug) cprintf("FORK: %d\n", r); 8007d5: 83 ec 08 sub $0x8,%esp 8007d8: 50 push %eax 8007d9: 68 ed 33 80 00 push $0x8033ed 8007de: e8 2b 03 00 00 call 800b0e <cprintf> 8007e3: 83 c4 10 add $0x10,%esp 8007e6: eb 5f jmp 800847 <umain+0x1e8> if (r == 0) { runcmd(buf); exit(); } else wait(r); 8007e8: 83 ec 0c sub $0xc,%esp 8007eb: 56 push %esi 8007ec: e8 30 26 00 00 call 802e21 <wait> 8007f1: 83 c4 10 add $0x10,%esp buf = readline(interactive ? "$ " : NULL); 8007f4: 83 ec 0c sub $0xc,%esp 8007f7: 57 push %edi 8007f8: e8 f9 08 00 00 call 8010f6 <readline> 8007fd: 89 c3 mov %eax,%ebx if (buf == NULL) { 8007ff: 83 c4 10 add $0x10,%esp 800802: 85 c0 test %eax,%eax 800804: 0f 84 59 ff ff ff je 800763 <umain+0x104> if (debug) 80080a: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 800811: 0f 85 71 ff ff ff jne 800788 <umain+0x129> if (buf[0] == '#') 800817: 80 3b 23 cmpb $0x23,(%ebx) 80081a: 74 d8 je 8007f4 <umain+0x195> if (echocmds) 80081c: 83 7d d4 00 cmpl $0x0,-0x2c(%ebp) 800820: 0f 85 75 ff ff ff jne 80079b <umain+0x13c> if (debug) 800826: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 80082d: 0f 85 7b ff ff ff jne 8007ae <umain+0x14f> if ((r = fork()) < 0) 800833: e8 9f 10 00 00 call 8018d7 <fork> 800838: 89 c6 mov %eax,%esi 80083a: 85 c0 test %eax,%eax 80083c: 78 82 js 8007c0 <umain+0x161> if (debug) 80083e: 83 3d 00 50 80 00 00 cmpl $0x0,0x805000 800845: 75 8e jne 8007d5 <umain+0x176> if (r == 0) { 800847: 85 f6 test %esi,%esi 800849: 75 9d jne 8007e8 <umain+0x189> runcmd(buf); 80084b: 83 ec 0c sub $0xc,%esp 80084e: 53 push %ebx 80084f: e8 aa f9 ff ff call 8001fe <runcmd> exit(); 800854: e8 c8 01 00 00 call 800a21 <exit> 800859: 83 c4 10 add $0x10,%esp 80085c: eb 96 jmp 8007f4 <umain+0x195> 0080085e <devcons_close>: return tot; } static int devcons_close(struct Fd *fd) { 80085e: 55 push %ebp 80085f: 89 e5 mov %esp,%ebp USED(fd); return 0; } 800861: b8 00 00 00 00 mov $0x0,%eax 800866: 5d pop %ebp 800867: c3 ret 00800868 <devcons_stat>: static int devcons_stat(struct Fd *fd, struct Stat *stat) { 800868: 55 push %ebp 800869: 89 e5 mov %esp,%ebp 80086b: 83 ec 10 sub $0x10,%esp strcpy(stat->st_name, "<cons>"); 80086e: 68 69 34 80 00 push $0x803469 800873: ff 75 0c pushl 0xc(%ebp) 800876: e8 a2 09 00 00 call 80121d <strcpy> return 0; } 80087b: b8 00 00 00 00 mov $0x0,%eax 800880: c9 leave 800881: c3 ret 00800882 <devcons_write>: { 800882: 55 push %ebp 800883: 89 e5 mov %esp,%ebp 800885: 57 push %edi 800886: 56 push %esi 800887: 53 push %ebx 800888: 81 ec 8c 00 00 00 sub $0x8c,%esp for (tot = 0; tot < n; tot += m) { 80088e: be 00 00 00 00 mov $0x0,%esi memmove(buf, (char*)vbuf + tot, m); 800893: 8d bd 68 ff ff ff lea -0x98(%ebp),%edi for (tot = 0; tot < n; tot += m) { 800899: eb 2f jmp 8008ca <devcons_write+0x48> m = n - tot; 80089b: 8b 5d 10 mov 0x10(%ebp),%ebx 80089e: 29 f3 sub %esi,%ebx 8008a0: 83 fb 7f cmp $0x7f,%ebx 8008a3: b8 7f 00 00 00 mov $0x7f,%eax 8008a8: 0f 47 d8 cmova %eax,%ebx memmove(buf, (char*)vbuf + tot, m); 8008ab: 83 ec 04 sub $0x4,%esp 8008ae: 53 push %ebx 8008af: 89 f0 mov %esi,%eax 8008b1: 03 45 0c add 0xc(%ebp),%eax 8008b4: 50 push %eax 8008b5: 57 push %edi 8008b6: e8 f0 0a 00 00 call 8013ab <memmove> sys_cputs(buf, m); 8008bb: 83 c4 08 add $0x8,%esp 8008be: 53 push %ebx 8008bf: 57 push %edi 8008c0: e8 95 0c 00 00 call 80155a <sys_cputs> for (tot = 0; tot < n; tot += m) { 8008c5: 01 de add %ebx,%esi 8008c7: 83 c4 10 add $0x10,%esp 8008ca: 3b 75 10 cmp 0x10(%ebp),%esi 8008cd: 72 cc jb 80089b <devcons_write+0x19> } 8008cf: 89 f0 mov %esi,%eax 8008d1: 8d 65 f4 lea -0xc(%ebp),%esp 8008d4: 5b pop %ebx 8008d5: 5e pop %esi 8008d6: 5f pop %edi 8008d7: 5d pop %ebp 8008d8: c3 ret 008008d9 <devcons_read>: { 8008d9: 55 push %ebp 8008da: 89 e5 mov %esp,%ebp 8008dc: 83 ec 08 sub $0x8,%esp 8008df: b8 00 00 00 00 mov $0x0,%eax if (n == 0) 8008e4: 83 7d 10 00 cmpl $0x0,0x10(%ebp) 8008e8: 75 07 jne 8008f1 <devcons_read+0x18> } 8008ea: c9 leave 8008eb: c3 ret sys_yield(); 8008ec: e8 06 0d 00 00 call 8015f7 <sys_yield> while ((c = sys_cgetc()) == 0) 8008f1: e8 82 0c 00 00 call 801578 <sys_cgetc> 8008f6: 85 c0 test %eax,%eax 8008f8: 74 f2 je 8008ec <devcons_read+0x13> if (c < 0) 8008fa: 85 c0 test %eax,%eax 8008fc: 78 ec js 8008ea <devcons_read+0x11> if (c == 0x04) // ctl-d is eof 8008fe: 83 f8 04 cmp $0x4,%eax 800901: 74 0c je 80090f <devcons_read+0x36> *(char*)vbuf = c; 800903: 8b 55 0c mov 0xc(%ebp),%edx 800906: 88 02 mov %al,(%edx) return 1; 800908: b8 01 00 00 00 mov $0x1,%eax 80090d: eb db jmp 8008ea <devcons_read+0x11> return 0; 80090f: b8 00 00 00 00 mov $0x0,%eax 800914: eb d4 jmp 8008ea <devcons_read+0x11> 00800916 <cputchar>: { 800916: 55 push %ebp 800917: 89 e5 mov %esp,%ebp 800919: 83 ec 20 sub $0x20,%esp char c = ch; 80091c: 8b 45 08 mov 0x8(%ebp),%eax 80091f: 88 45 f7 mov %al,-0x9(%ebp) sys_cputs(&c, 1); 800922: 6a 01 push $0x1 800924: 8d 45 f7 lea -0x9(%ebp),%eax 800927: 50 push %eax 800928: e8 2d 0c 00 00 call 80155a <sys_cputs> } 80092d: 83 c4 10 add $0x10,%esp 800930: c9 leave 800931: c3 ret 00800932 <getchar>: { 800932: 55 push %ebp 800933: 89 e5 mov %esp,%ebp 800935: 83 ec 1c sub $0x1c,%esp r = read(0, &c, 1); 800938: 6a 01 push $0x1 80093a: 8d 45 f7 lea -0x9(%ebp),%eax 80093d: 50 push %eax 80093e: 6a 00 push $0x0 800940: e8 b9 15 00 00 call 801efe <read> if (r < 0) 800945: 83 c4 10 add $0x10,%esp 800948: 85 c0 test %eax,%eax 80094a: 78 08 js 800954 <getchar+0x22> if (r < 1) 80094c: 85 c0 test %eax,%eax 80094e: 7e 06 jle 800956 <getchar+0x24> return c; 800950: 0f b6 45 f7 movzbl -0x9(%ebp),%eax } 800954: c9 leave 800955: c3 ret return -E_EOF; 800956: b8 f8 ff ff ff mov $0xfffffff8,%eax 80095b: eb f7 jmp 800954 <getchar+0x22> 0080095d <iscons>: { 80095d: 55 push %ebp 80095e: 89 e5 mov %esp,%ebp 800960: 83 ec 20 sub $0x20,%esp if ((r = fd_lookup(fdnum, &fd)) < 0) 800963: 8d 45 f4 lea -0xc(%ebp),%eax 800966: 50 push %eax 800967: ff 75 08 pushl 0x8(%ebp) 80096a: e8 1e 13 00 00 call 801c8d <fd_lookup> 80096f: 83 c4 10 add $0x10,%esp 800972: 85 c0 test %eax,%eax 800974: 78 11 js 800987 <iscons+0x2a> return fd->fd_dev_id == devcons.dev_id; 800976: 8b 45 f4 mov -0xc(%ebp),%eax 800979: 8b 15 00 40 80 00 mov 0x804000,%edx 80097f: 39 10 cmp %edx,(%eax) 800981: 0f 94 c0 sete %al 800984: 0f b6 c0 movzbl %al,%eax } 800987: c9 leave 800988: c3 ret 00800989 <opencons>: { 800989: 55 push %ebp 80098a: 89 e5 mov %esp,%ebp 80098c: 83 ec 24 sub $0x24,%esp if ((r = fd_alloc(&fd)) < 0) 80098f: 8d 45 f4 lea -0xc(%ebp),%eax 800992: 50 push %eax 800993: e8 a6 12 00 00 call 801c3e <fd_alloc> 800998: 83 c4 10 add $0x10,%esp 80099b: 85 c0 test %eax,%eax 80099d: 78 3a js 8009d9 <opencons+0x50> if ((r = sys_page_alloc(0, fd, PTE_P|PTE_U|PTE_W|PTE_SHARE)) < 0) 80099f: 83 ec 04 sub $0x4,%esp 8009a2: 68 07 04 00 00 push $0x407 8009a7: ff 75 f4 pushl -0xc(%ebp) 8009aa: 6a 00 push $0x0 8009ac: e8 65 0c 00 00 call 801616 <sys_page_alloc> 8009b1: 83 c4 10 add $0x10,%esp 8009b4: 85 c0 test %eax,%eax 8009b6: 78 21 js 8009d9 <opencons+0x50> fd->fd_dev_id = devcons.dev_id; 8009b8: 8b 45 f4 mov -0xc(%ebp),%eax 8009bb: 8b 15 00 40 80 00 mov 0x804000,%edx 8009c1: 89 10 mov %edx,(%eax) fd->fd_omode = O_RDWR; 8009c3: 8b 45 f4 mov -0xc(%ebp),%eax 8009c6: c7 40 08 02 00 00 00 movl $0x2,0x8(%eax) return fd2num(fd); 8009cd: 83 ec 0c sub $0xc,%esp 8009d0: 50 push %eax 8009d1: e8 41 12 00 00 call 801c17 <fd2num> 8009d6: 83 c4 10 add $0x10,%esp } 8009d9: c9 leave 8009da: c3 ret 008009db <libmain>: const volatile struct Env *thisenv; const char *binaryname = "<unknown>"; void libmain(int argc, char **argv) { 8009db: 55 push %ebp 8009dc: 89 e5 mov %esp,%ebp 8009de: 56 push %esi 8009df: 53 push %ebx 8009e0: 8b 5d 08 mov 0x8(%ebp),%ebx 8009e3: 8b 75 0c mov 0xc(%ebp),%esi // set thisenv to point at our Env structure in envs[]. // LAB 3: Your code here. envid_t envid = sys_getenvid(); 8009e6: e8 ed 0b 00 00 call 8015d8 <sys_getenvid> thisenv = envs + ENVX(envid); 8009eb: 25 ff 03 00 00 and $0x3ff,%eax 8009f0: 6b c0 7c imul $0x7c,%eax,%eax 8009f3: 05 00 00 c0 ee add $0xeec00000,%eax 8009f8: a3 24 54 80 00 mov %eax,0x805424 // save the name of the program so that panic() can use it if (argc > 0) 8009fd: 85 db test %ebx,%ebx 8009ff: 7e 07 jle 800a08 <libmain+0x2d> binaryname = argv[0]; 800a01: 8b 06 mov (%esi),%eax 800a03: a3 1c 40 80 00 mov %eax,0x80401c // call user main routine umain(argc, argv); 800a08: 83 ec 08 sub $0x8,%esp 800a0b: 56 push %esi 800a0c: 53 push %ebx 800a0d: e8 4d fc ff ff call 80065f <umain> // exit gracefully exit(); 800a12: e8 0a 00 00 00 call 800a21 <exit> } 800a17: 83 c4 10 add $0x10,%esp 800a1a: 8d 65 f8 lea -0x8(%ebp),%esp 800a1d: 5b pop %ebx 800a1e: 5e pop %esi 800a1f: 5d pop %ebp 800a20: c3 ret 00800a21 <exit>: #include <inc/lib.h> void exit(void) { 800a21: 55 push %ebp 800a22: 89 e5 mov %esp,%ebp 800a24: 83 ec 14 sub $0x14,%esp // close_all(); sys_env_destroy(0); 800a27: 6a 00 push $0x0 800a29: e8 69 0b 00 00 call 801597 <sys_env_destroy> } 800a2e: 83 c4 10 add $0x10,%esp 800a31: c9 leave 800a32: c3 ret 00800a33 <_panic>: * It prints "panic: <message>", then causes a breakpoint exception, * which causes JOS to enter the JOS kernel monitor. */ void _panic(const char *file, int line, const char *fmt, ...) { 800a33: 55 push %ebp 800a34: 89 e5 mov %esp,%ebp 800a36: 56 push %esi 800a37: 53 push %ebx va_list ap; va_start(ap, fmt); 800a38: 8d 5d 14 lea 0x14(%ebp),%ebx // Print the panic message cprintf("[%08x] user panic in %s at %s:%d: ", 800a3b: 8b 35 1c 40 80 00 mov 0x80401c,%esi 800a41: e8 92 0b 00 00 call 8015d8 <sys_getenvid> 800a46: 83 ec 0c sub $0xc,%esp 800a49: ff 75 0c pushl 0xc(%ebp) 800a4c: ff 75 08 pushl 0x8(%ebp) 800a4f: 56 push %esi 800a50: 50 push %eax 800a51: 68 80 34 80 00 push $0x803480 800a56: e8 b3 00 00 00 call 800b0e <cprintf> sys_getenvid(), binaryname, file, line); vcprintf(fmt, ap); 800a5b: 83 c4 18 add $0x18,%esp 800a5e: 53 push %ebx 800a5f: ff 75 10 pushl 0x10(%ebp) 800a62: e8 56 00 00 00 call 800abd <vcprintf> cprintf("\n"); 800a67: c7 04 24 80 32 80 00 movl $0x803280,(%esp) 800a6e: e8 9b 00 00 00 call 800b0e <cprintf> 800a73: 83 c4 10 add $0x10,%esp // Cause a breakpoint exception while (1) asm volatile("int3"); 800a76: cc int3 800a77: eb fd jmp 800a76 <_panic+0x43> 00800a79 <putch>: }; static void putch(int ch, struct printbuf *b) { 800a79: 55 push %ebp 800a7a: 89 e5 mov %esp,%ebp 800a7c: 53 push %ebx 800a7d: 83 ec 04 sub $0x4,%esp 800a80: 8b 5d 0c mov 0xc(%ebp),%ebx b->buf[b->idx++] = ch; 800a83: 8b 13 mov (%ebx),%edx 800a85: 8d 42 01 lea 0x1(%edx),%eax 800a88: 89 03 mov %eax,(%ebx) 800a8a: 8b 4d 08 mov 0x8(%ebp),%ecx 800a8d: 88 4c 13 08 mov %cl,0x8(%ebx,%edx,1) if (b->idx == 256-1) { 800a91: 3d ff 00 00 00 cmp $0xff,%eax 800a96: 74 09 je 800aa1 <putch+0x28> sys_cputs(b->buf, b->idx); b->idx = 0; } b->cnt++; 800a98: 83 43 04 01 addl $0x1,0x4(%ebx) } 800a9c: 8b 5d fc mov -0x4(%ebp),%ebx 800a9f: c9 leave 800aa0: c3 ret sys_cputs(b->buf, b->idx); 800aa1: 83 ec 08 sub $0x8,%esp 800aa4: 68 ff 00 00 00 push $0xff 800aa9: 8d 43 08 lea 0x8(%ebx),%eax 800aac: 50 push %eax 800aad: e8 a8 0a 00 00 call 80155a <sys_cputs> b->idx = 0; 800ab2: c7 03 00 00 00 00 movl $0x0,(%ebx) 800ab8: 83 c4 10 add $0x10,%esp 800abb: eb db jmp 800a98 <putch+0x1f> 00800abd <vcprintf>: int vcprintf(const char *fmt, va_list ap) { 800abd: 55 push %ebp 800abe: 89 e5 mov %esp,%ebp 800ac0: 81 ec 18 01 00 00 sub $0x118,%esp struct printbuf b; b.idx = 0; 800ac6: c7 85 f0 fe ff ff 00 movl $0x0,-0x110(%ebp) 800acd: 00 00 00 b.cnt = 0; 800ad0: c7 85 f4 fe ff ff 00 movl $0x0,-0x10c(%ebp) 800ad7: 00 00 00 vprintfmt((void*)putch, &b, fmt, ap); 800ada: ff 75 0c pushl 0xc(%ebp) 800add: ff 75 08 pushl 0x8(%ebp) 800ae0: 8d 85 f0 fe ff ff lea -0x110(%ebp),%eax 800ae6: 50 push %eax 800ae7: 68 79 0a 80 00 push $0x800a79 800aec: e8 1a 01 00 00 call 800c0b <vprintfmt> sys_cputs(b.buf, b.idx); 800af1: 83 c4 08 add $0x8,%esp 800af4: ff b5 f0 fe ff ff pushl -0x110(%ebp) 800afa: 8d 85 f8 fe ff ff lea -0x108(%ebp),%eax 800b00: 50 push %eax 800b01: e8 54 0a 00 00 call 80155a <sys_cputs> return b.cnt; } 800b06: 8b 85 f4 fe ff ff mov -0x10c(%ebp),%eax 800b0c: c9 leave 800b0d: c3 ret 00800b0e <cprintf>: int cprintf(const char *fmt, ...) { 800b0e: 55 push %ebp 800b0f: 89 e5 mov %esp,%ebp 800b11: 83 ec 10 sub $0x10,%esp va_list ap; int cnt; va_start(ap, fmt); 800b14: 8d 45 0c lea 0xc(%ebp),%eax cnt = vcprintf(fmt, ap); 800b17: 50 push %eax 800b18: ff 75 08 pushl 0x8(%ebp) 800b1b: e8 9d ff ff ff call 800abd <vcprintf> va_end(ap); return cnt; } 800b20: c9 leave 800b21: c3 ret 00800b22 <printnum>: * using specified putch function and associated pointer putdat. */ static void printnum(void (*putch)(int, void*), void *putdat, unsigned long long num, unsigned base, int width, int padc) { 800b22: 55 push %ebp 800b23: 89 e5 mov %esp,%ebp 800b25: 57 push %edi 800b26: 56 push %esi 800b27: 53 push %ebx 800b28: 83 ec 1c sub $0x1c,%esp 800b2b: 89 c7 mov %eax,%edi 800b2d: 89 d6 mov %edx,%esi 800b2f: 8b 45 08 mov 0x8(%ebp),%eax 800b32: 8b 55 0c mov 0xc(%ebp),%edx 800b35: 89 45 d8 mov %eax,-0x28(%ebp) 800b38: 89 55 dc mov %edx,-0x24(%ebp) // first recursively print all preceding (more significant) digits if (num >= base) { 800b3b: 8b 4d 10 mov 0x10(%ebp),%ecx 800b3e: bb 00 00 00 00 mov $0x0,%ebx 800b43: 89 4d e0 mov %ecx,-0x20(%ebp) 800b46: 89 5d e4 mov %ebx,-0x1c(%ebp) 800b49: 39 d3 cmp %edx,%ebx 800b4b: 72 05 jb 800b52 <printnum+0x30> 800b4d: 39 45 10 cmp %eax,0x10(%ebp) 800b50: 77 7a ja 800bcc <printnum+0xaa> printnum(putch, putdat, num / base, base, width - 1, padc); 800b52: 83 ec 0c sub $0xc,%esp 800b55: ff 75 18 pushl 0x18(%ebp) 800b58: 8b 45 14 mov 0x14(%ebp),%eax 800b5b: 8d 58 ff lea -0x1(%eax),%ebx 800b5e: 53 push %ebx 800b5f: ff 75 10 pushl 0x10(%ebp) 800b62: 83 ec 08 sub $0x8,%esp 800b65: ff 75 e4 pushl -0x1c(%ebp) 800b68: ff 75 e0 pushl -0x20(%ebp) 800b6b: ff 75 dc pushl -0x24(%ebp) 800b6e: ff 75 d8 pushl -0x28(%ebp) 800b71: e8 aa 24 00 00 call 803020 <__udivdi3> 800b76: 83 c4 18 add $0x18,%esp 800b79: 52 push %edx 800b7a: 50 push %eax 800b7b: 89 f2 mov %esi,%edx 800b7d: 89 f8 mov %edi,%eax 800b7f: e8 9e ff ff ff call 800b22 <printnum> 800b84: 83 c4 20 add $0x20,%esp 800b87: eb 13 jmp 800b9c <printnum+0x7a> } else { // print any needed pad characters before first digit while (--width > 0) putch(padc, putdat); 800b89: 83 ec 08 sub $0x8,%esp 800b8c: 56 push %esi 800b8d: ff 75 18 pushl 0x18(%ebp) 800b90: ff d7 call *%edi 800b92: 83 c4 10 add $0x10,%esp while (--width > 0) 800b95: 83 eb 01 sub $0x1,%ebx 800b98: 85 db test %ebx,%ebx 800b9a: 7f ed jg 800b89 <printnum+0x67> } // then print this (the least significant) digit putch("0123456789abcdef"[num % base], putdat); 800b9c: 83 ec 08 sub $0x8,%esp 800b9f: 56 push %esi 800ba0: 83 ec 04 sub $0x4,%esp 800ba3: ff 75 e4 pushl -0x1c(%ebp) 800ba6: ff 75 e0 pushl -0x20(%ebp) 800ba9: ff 75 dc pushl -0x24(%ebp) 800bac: ff 75 d8 pushl -0x28(%ebp) 800baf: e8 8c 25 00 00 call 803140 <__umoddi3> 800bb4: 83 c4 14 add $0x14,%esp 800bb7: 0f be 80 a3 34 80 00 movsbl 0x8034a3(%eax),%eax 800bbe: 50 push %eax 800bbf: ff d7 call *%edi } 800bc1: 83 c4 10 add $0x10,%esp 800bc4: 8d 65 f4 lea -0xc(%ebp),%esp 800bc7: 5b pop %ebx 800bc8: 5e pop %esi 800bc9: 5f pop %edi 800bca: 5d pop %ebp 800bcb: c3 ret 800bcc: 8b 5d 14 mov 0x14(%ebp),%ebx 800bcf: eb c4 jmp 800b95 <printnum+0x73> 00800bd1 <sprintputch>: int cnt; }; static void sprintputch(int ch, struct sprintbuf *b) { 800bd1: 55 push %ebp 800bd2: 89 e5 mov %esp,%ebp 800bd4: 8b 45 0c mov 0xc(%ebp),%eax b->cnt++; 800bd7: 83 40 08 01 addl $0x1,0x8(%eax) if (b->buf < b->ebuf) 800bdb: 8b 10 mov (%eax),%edx 800bdd: 3b 50 04 cmp 0x4(%eax),%edx 800be0: 73 0a jae 800bec <sprintputch+0x1b> *b->buf++ = ch; 800be2: 8d 4a 01 lea 0x1(%edx),%ecx 800be5: 89 08 mov %ecx,(%eax) 800be7: 8b 45 08 mov 0x8(%ebp),%eax 800bea: 88 02 mov %al,(%edx) } 800bec: 5d pop %ebp 800bed: c3 ret 00800bee <printfmt>: { 800bee: 55 push %ebp 800bef: 89 e5 mov %esp,%ebp 800bf1: 83 ec 08 sub $0x8,%esp va_start(ap, fmt); 800bf4: 8d 45 14 lea 0x14(%ebp),%eax vprintfmt(putch, putdat, fmt, ap); 800bf7: 50 push %eax 800bf8: ff 75 10 pushl 0x10(%ebp) 800bfb: ff 75 0c pushl 0xc(%ebp) 800bfe: ff 75 08 pushl 0x8(%ebp) 800c01: e8 05 00 00 00 call 800c0b <vprintfmt> } 800c06: 83 c4 10 add $0x10,%esp 800c09: c9 leave 800c0a: c3 ret 00800c0b <vprintfmt>: { 800c0b: 55 push %ebp 800c0c: 89 e5 mov %esp,%ebp 800c0e: 57 push %edi 800c0f: 56 push %esi 800c10: 53 push %ebx 800c11: 83 ec 2c sub $0x2c,%esp 800c14: 8b 75 08 mov 0x8(%ebp),%esi 800c17: 8b 5d 0c mov 0xc(%ebp),%ebx 800c1a: 8b 7d 10 mov 0x10(%ebp),%edi 800c1d: e9 c1 03 00 00 jmp 800fe3 <vprintfmt+0x3d8> padc = ' '; 800c22: c6 45 d4 20 movb $0x20,-0x2c(%ebp) altflag = 0; 800c26: c7 45 d8 00 00 00 00 movl $0x0,-0x28(%ebp) precision = -1; 800c2d: c7 45 d0 ff ff ff ff movl $0xffffffff,-0x30(%ebp) width = -1; 800c34: c7 45 e0 ff ff ff ff movl $0xffffffff,-0x20(%ebp) lflag = 0; 800c3b: b9 00 00 00 00 mov $0x0,%ecx switch (ch = *(unsigned char *) fmt++) { 800c40: 8d 47 01 lea 0x1(%edi),%eax 800c43: 89 45 e4 mov %eax,-0x1c(%ebp) 800c46: 0f b6 17 movzbl (%edi),%edx 800c49: 8d 42 dd lea -0x23(%edx),%eax 800c4c: 3c 55 cmp $0x55,%al 800c4e: 0f 87 12 04 00 00 ja 801066 <vprintfmt+0x45b> 800c54: 0f b6 c0 movzbl %al,%eax 800c57: ff 24 85 e0 35 80 00 jmp *0x8035e0(,%eax,4) 800c5e: 8b 7d e4 mov -0x1c(%ebp),%edi padc = '-'; 800c61: c6 45 d4 2d movb $0x2d,-0x2c(%ebp) 800c65: eb d9 jmp 800c40 <vprintfmt+0x35> switch (ch = *(unsigned char *) fmt++) { 800c67: 8b 7d e4 mov -0x1c(%ebp),%edi padc = '0'; 800c6a: c6 45 d4 30 movb $0x30,-0x2c(%ebp) 800c6e: eb d0 jmp 800c40 <vprintfmt+0x35> switch (ch = *(unsigned char *) fmt++) { 800c70: 0f b6 d2 movzbl %dl,%edx 800c73: 8b 7d e4 mov -0x1c(%ebp),%edi for (precision = 0; ; ++fmt) { 800c76: b8 00 00 00 00 mov $0x0,%eax 800c7b: 89 4d e4 mov %ecx,-0x1c(%ebp) precision = precision * 10 + ch - '0'; 800c7e: 8d 04 80 lea (%eax,%eax,4),%eax 800c81: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax ch = *fmt; 800c85: 0f be 17 movsbl (%edi),%edx if (ch < '0' || ch > '9') 800c88: 8d 4a d0 lea -0x30(%edx),%ecx 800c8b: 83 f9 09 cmp $0x9,%ecx 800c8e: 77 55 ja 800ce5 <vprintfmt+0xda> for (precision = 0; ; ++fmt) { 800c90: 83 c7 01 add $0x1,%edi precision = precision * 10 + ch - '0'; 800c93: eb e9 jmp 800c7e <vprintfmt+0x73> precision = va_arg(ap, int); 800c95: 8b 45 14 mov 0x14(%ebp),%eax 800c98: 8b 00 mov (%eax),%eax 800c9a: 89 45 d0 mov %eax,-0x30(%ebp) 800c9d: 8b 45 14 mov 0x14(%ebp),%eax 800ca0: 8d 40 04 lea 0x4(%eax),%eax 800ca3: 89 45 14 mov %eax,0x14(%ebp) switch (ch = *(unsigned char *) fmt++) { 800ca6: 8b 7d e4 mov -0x1c(%ebp),%edi if (width < 0) 800ca9: 83 7d e0 00 cmpl $0x0,-0x20(%ebp) 800cad: 79 91 jns 800c40 <vprintfmt+0x35> width = precision, precision = -1; 800caf: 8b 45 d0 mov -0x30(%ebp),%eax 800cb2: 89 45 e0 mov %eax,-0x20(%ebp) 800cb5: c7 45 d0 ff ff ff ff movl $0xffffffff,-0x30(%ebp) 800cbc: eb 82 jmp 800c40 <vprintfmt+0x35> 800cbe: 8b 45 e0 mov -0x20(%ebp),%eax 800cc1: 85 c0 test %eax,%eax 800cc3: ba 00 00 00 00 mov $0x0,%edx 800cc8: 0f 49 d0 cmovns %eax,%edx 800ccb: 89 55 e0 mov %edx,-0x20(%ebp) switch (ch = *(unsigned char *) fmt++) { 800cce: 8b 7d e4 mov -0x1c(%ebp),%edi 800cd1: e9 6a ff ff ff jmp 800c40 <vprintfmt+0x35> 800cd6: 8b 7d e4 mov -0x1c(%ebp),%edi altflag = 1; 800cd9: c7 45 d8 01 00 00 00 movl $0x1,-0x28(%ebp) goto reswitch; 800ce0: e9 5b ff ff ff jmp 800c40 <vprintfmt+0x35> 800ce5: 8b 4d e4 mov -0x1c(%ebp),%ecx 800ce8: 89 45 d0 mov %eax,-0x30(%ebp) 800ceb: eb bc jmp 800ca9 <vprintfmt+0x9e> lflag++; 800ced: 83 c1 01 add $0x1,%ecx switch (ch = *(unsigned char *) fmt++) { 800cf0: 8b 7d e4 mov -0x1c(%ebp),%edi goto reswitch; 800cf3: e9 48 ff ff ff jmp 800c40 <vprintfmt+0x35> putch(va_arg(ap, int), putdat); 800cf8: 8b 45 14 mov 0x14(%ebp),%eax 800cfb: 8d 78 04 lea 0x4(%eax),%edi 800cfe: 83 ec 08 sub $0x8,%esp 800d01: 53 push %ebx 800d02: ff 30 pushl (%eax) 800d04: ff d6 call *%esi break; 800d06: 83 c4 10 add $0x10,%esp putch(va_arg(ap, int), putdat); 800d09: 89 7d 14 mov %edi,0x14(%ebp) break; 800d0c: e9 cf 02 00 00 jmp 800fe0 <vprintfmt+0x3d5> err = va_arg(ap, int); 800d11: 8b 45 14 mov 0x14(%ebp),%eax 800d14: 8d 78 04 lea 0x4(%eax),%edi 800d17: 8b 00 mov (%eax),%eax 800d19: 99 cltd 800d1a: 31 d0 xor %edx,%eax 800d1c: 29 d0 sub %edx,%eax if (err >= MAXERROR || (p = error_string[err]) == NULL) 800d1e: 83 f8 0f cmp $0xf,%eax 800d21: 7f 23 jg 800d46 <vprintfmt+0x13b> 800d23: 8b 14 85 40 37 80 00 mov 0x803740(,%eax,4),%edx 800d2a: 85 d2 test %edx,%edx 800d2c: 74 18 je 800d46 <vprintfmt+0x13b> printfmt(putch, putdat, "%s", p); 800d2e: 52 push %edx 800d2f: 68 c1 33 80 00 push $0x8033c1 800d34: 53 push %ebx 800d35: 56 push %esi 800d36: e8 b3 fe ff ff call 800bee <printfmt> 800d3b: 83 c4 10 add $0x10,%esp err = va_arg(ap, int); 800d3e: 89 7d 14 mov %edi,0x14(%ebp) 800d41: e9 9a 02 00 00 jmp 800fe0 <vprintfmt+0x3d5> printfmt(putch, putdat, "error %d", err); 800d46: 50 push %eax 800d47: 68 bb 34 80 00 push $0x8034bb 800d4c: 53 push %ebx 800d4d: 56 push %esi 800d4e: e8 9b fe ff ff call 800bee <printfmt> 800d53: 83 c4 10 add $0x10,%esp err = va_arg(ap, int); 800d56: 89 7d 14 mov %edi,0x14(%ebp) printfmt(putch, putdat, "error %d", err); 800d59: e9 82 02 00 00 jmp 800fe0 <vprintfmt+0x3d5> if ((p = va_arg(ap, char *)) == NULL) 800d5e: 8b 45 14 mov 0x14(%ebp),%eax 800d61: 83 c0 04 add $0x4,%eax 800d64: 89 45 cc mov %eax,-0x34(%ebp) 800d67: 8b 45 14 mov 0x14(%ebp),%eax 800d6a: 8b 38 mov (%eax),%edi p = "(null)"; 800d6c: 85 ff test %edi,%edi 800d6e: b8 b4 34 80 00 mov $0x8034b4,%eax 800d73: 0f 44 f8 cmove %eax,%edi if (width > 0 && padc != '-') 800d76: 83 7d e0 00 cmpl $0x0,-0x20(%ebp) 800d7a: 0f 8e bd 00 00 00 jle 800e3d <vprintfmt+0x232> 800d80: 80 7d d4 2d cmpb $0x2d,-0x2c(%ebp) 800d84: 75 0e jne 800d94 <vprintfmt+0x189> 800d86: 89 75 08 mov %esi,0x8(%ebp) 800d89: 8b 75 d0 mov -0x30(%ebp),%esi 800d8c: 89 5d 0c mov %ebx,0xc(%ebp) 800d8f: 8b 5d e0 mov -0x20(%ebp),%ebx 800d92: eb 6d jmp 800e01 <vprintfmt+0x1f6> for (width -= strnlen(p, precision); width > 0; width--) 800d94: 83 ec 08 sub $0x8,%esp 800d97: ff 75 d0 pushl -0x30(%ebp) 800d9a: 57 push %edi 800d9b: e8 5e 04 00 00 call 8011fe <strnlen> 800da0: 8b 4d e0 mov -0x20(%ebp),%ecx 800da3: 29 c1 sub %eax,%ecx 800da5: 89 4d c8 mov %ecx,-0x38(%ebp) 800da8: 83 c4 10 add $0x10,%esp putch(padc, putdat); 800dab: 0f be 45 d4 movsbl -0x2c(%ebp),%eax 800daf: 89 45 e0 mov %eax,-0x20(%ebp) 800db2: 89 7d d4 mov %edi,-0x2c(%ebp) 800db5: 89 cf mov %ecx,%edi for (width -= strnlen(p, precision); width > 0; width--) 800db7: eb 0f jmp 800dc8 <vprintfmt+0x1bd> putch(padc, putdat); 800db9: 83 ec 08 sub $0x8,%esp 800dbc: 53 push %ebx 800dbd: ff 75 e0 pushl -0x20(%ebp) 800dc0: ff d6 call *%esi for (width -= strnlen(p, precision); width > 0; width--) 800dc2: 83 ef 01 sub $0x1,%edi 800dc5: 83 c4 10 add $0x10,%esp 800dc8: 85 ff test %edi,%edi 800dca: 7f ed jg 800db9 <vprintfmt+0x1ae> 800dcc: 8b 7d d4 mov -0x2c(%ebp),%edi 800dcf: 8b 4d c8 mov -0x38(%ebp),%ecx 800dd2: 85 c9 test %ecx,%ecx 800dd4: b8 00 00 00 00 mov $0x0,%eax 800dd9: 0f 49 c1 cmovns %ecx,%eax 800ddc: 29 c1 sub %eax,%ecx 800dde: 89 75 08 mov %esi,0x8(%ebp) 800de1: 8b 75 d0 mov -0x30(%ebp),%esi 800de4: 89 5d 0c mov %ebx,0xc(%ebp) 800de7: 89 cb mov %ecx,%ebx 800de9: eb 16 jmp 800e01 <vprintfmt+0x1f6> if (altflag && (ch < ' ' || ch > '~')) 800deb: 83 7d d8 00 cmpl $0x0,-0x28(%ebp) 800def: 75 31 jne 800e22 <vprintfmt+0x217> putch(ch, putdat); 800df1: 83 ec 08 sub $0x8,%esp 800df4: ff 75 0c pushl 0xc(%ebp) 800df7: 50 push %eax 800df8: ff 55 08 call *0x8(%ebp) 800dfb: 83 c4 10 add $0x10,%esp for (; (ch = *p++) != '\0' && (precision < 0 || --precision >= 0); width--) 800dfe: 83 eb 01 sub $0x1,%ebx 800e01: 83 c7 01 add $0x1,%edi 800e04: 0f b6 57 ff movzbl -0x1(%edi),%edx 800e08: 0f be c2 movsbl %dl,%eax 800e0b: 85 c0 test %eax,%eax 800e0d: 74 59 je 800e68 <vprintfmt+0x25d> 800e0f: 85 f6 test %esi,%esi 800e11: 78 d8 js 800deb <vprintfmt+0x1e0> 800e13: 83 ee 01 sub $0x1,%esi 800e16: 79 d3 jns 800deb <vprintfmt+0x1e0> 800e18: 89 df mov %ebx,%edi 800e1a: 8b 75 08 mov 0x8(%ebp),%esi 800e1d: 8b 5d 0c mov 0xc(%ebp),%ebx 800e20: eb 37 jmp 800e59 <vprintfmt+0x24e> if (altflag && (ch < ' ' || ch > '~')) 800e22: 0f be d2 movsbl %dl,%edx 800e25: 83 ea 20 sub $0x20,%edx 800e28: 83 fa 5e cmp $0x5e,%edx 800e2b: 76 c4 jbe 800df1 <vprintfmt+0x1e6> putch('?', putdat); 800e2d: 83 ec 08 sub $0x8,%esp 800e30: ff 75 0c pushl 0xc(%ebp) 800e33: 6a 3f push $0x3f 800e35: ff 55 08 call *0x8(%ebp) 800e38: 83 c4 10 add $0x10,%esp 800e3b: eb c1 jmp 800dfe <vprintfmt+0x1f3> 800e3d: 89 75 08 mov %esi,0x8(%ebp) 800e40: 8b 75 d0 mov -0x30(%ebp),%esi 800e43: 89 5d 0c mov %ebx,0xc(%ebp) 800e46: 8b 5d e0 mov -0x20(%ebp),%ebx 800e49: eb b6 jmp 800e01 <vprintfmt+0x1f6> putch(' ', putdat); 800e4b: 83 ec 08 sub $0x8,%esp 800e4e: 53 push %ebx 800e4f: 6a 20 push $0x20 800e51: ff d6 call *%esi for (; width > 0; width--) 800e53: 83 ef 01 sub $0x1,%edi 800e56: 83 c4 10 add $0x10,%esp 800e59: 85 ff test %edi,%edi 800e5b: 7f ee jg 800e4b <vprintfmt+0x240> if ((p = va_arg(ap, char *)) == NULL) 800e5d: 8b 45 cc mov -0x34(%ebp),%eax 800e60: 89 45 14 mov %eax,0x14(%ebp) 800e63: e9 78 01 00 00 jmp 800fe0 <vprintfmt+0x3d5> 800e68: 89 df mov %ebx,%edi 800e6a: 8b 75 08 mov 0x8(%ebp),%esi 800e6d: 8b 5d 0c mov 0xc(%ebp),%ebx 800e70: eb e7 jmp 800e59 <vprintfmt+0x24e> if (lflag >= 2) 800e72: 83 f9 01 cmp $0x1,%ecx 800e75: 7e 3f jle 800eb6 <vprintfmt+0x2ab> return va_arg(*ap, long long); 800e77: 8b 45 14 mov 0x14(%ebp),%eax 800e7a: 8b 50 04 mov 0x4(%eax),%edx 800e7d: 8b 00 mov (%eax),%eax 800e7f: 89 45 d8 mov %eax,-0x28(%ebp) 800e82: 89 55 dc mov %edx,-0x24(%ebp) 800e85: 8b 45 14 mov 0x14(%ebp),%eax 800e88: 8d 40 08 lea 0x8(%eax),%eax 800e8b: 89 45 14 mov %eax,0x14(%ebp) if ((long long) num < 0) { 800e8e: 83 7d dc 00 cmpl $0x0,-0x24(%ebp) 800e92: 79 5c jns 800ef0 <vprintfmt+0x2e5> putch('-', putdat); 800e94: 83 ec 08 sub $0x8,%esp 800e97: 53 push %ebx 800e98: 6a 2d push $0x2d 800e9a: ff d6 call *%esi num = -(long long) num; 800e9c: 8b 55 d8 mov -0x28(%ebp),%edx 800e9f: 8b 4d dc mov -0x24(%ebp),%ecx 800ea2: f7 da neg %edx 800ea4: 83 d1 00 adc $0x0,%ecx 800ea7: f7 d9 neg %ecx 800ea9: 83 c4 10 add $0x10,%esp base = 10; 800eac: b8 0a 00 00 00 mov $0xa,%eax 800eb1: e9 10 01 00 00 jmp 800fc6 <vprintfmt+0x3bb> else if (lflag) 800eb6: 85 c9 test %ecx,%ecx 800eb8: 75 1b jne 800ed5 <vprintfmt+0x2ca> return va_arg(*ap, int); 800eba: 8b 45 14 mov 0x14(%ebp),%eax 800ebd: 8b 00 mov (%eax),%eax 800ebf: 89 45 d8 mov %eax,-0x28(%ebp) 800ec2: 89 c1 mov %eax,%ecx 800ec4: c1 f9 1f sar $0x1f,%ecx 800ec7: 89 4d dc mov %ecx,-0x24(%ebp) 800eca: 8b 45 14 mov 0x14(%ebp),%eax 800ecd: 8d 40 04 lea 0x4(%eax),%eax 800ed0: 89 45 14 mov %eax,0x14(%ebp) 800ed3: eb b9 jmp 800e8e <vprintfmt+0x283> return va_arg(*ap, long); 800ed5: 8b 45 14 mov 0x14(%ebp),%eax 800ed8: 8b 00 mov (%eax),%eax 800eda: 89 45 d8 mov %eax,-0x28(%ebp) 800edd: 89 c1 mov %eax,%ecx 800edf: c1 f9 1f sar $0x1f,%ecx 800ee2: 89 4d dc mov %ecx,-0x24(%ebp) 800ee5: 8b 45 14 mov 0x14(%ebp),%eax 800ee8: 8d 40 04 lea 0x4(%eax),%eax 800eeb: 89 45 14 mov %eax,0x14(%ebp) 800eee: eb 9e jmp 800e8e <vprintfmt+0x283> num = getint(&ap, lflag); 800ef0: 8b 55 d8 mov -0x28(%ebp),%edx 800ef3: 8b 4d dc mov -0x24(%ebp),%ecx base = 10; 800ef6: b8 0a 00 00 00 mov $0xa,%eax 800efb: e9 c6 00 00 00 jmp 800fc6 <vprintfmt+0x3bb> if (lflag >= 2) 800f00: 83 f9 01 cmp $0x1,%ecx 800f03: 7e 18 jle 800f1d <vprintfmt+0x312> return va_arg(*ap, unsigned long long); 800f05: 8b 45 14 mov 0x14(%ebp),%eax 800f08: 8b 10 mov (%eax),%edx 800f0a: 8b 48 04 mov 0x4(%eax),%ecx 800f0d: 8d 40 08 lea 0x8(%eax),%eax 800f10: 89 45 14 mov %eax,0x14(%ebp) base = 10; 800f13: b8 0a 00 00 00 mov $0xa,%eax 800f18: e9 a9 00 00 00 jmp 800fc6 <vprintfmt+0x3bb> else if (lflag) 800f1d: 85 c9 test %ecx,%ecx 800f1f: 75 1a jne 800f3b <vprintfmt+0x330> return va_arg(*ap, unsigned int); 800f21: 8b 45 14 mov 0x14(%ebp),%eax 800f24: 8b 10 mov (%eax),%edx 800f26: b9 00 00 00 00 mov $0x0,%ecx 800f2b: 8d 40 04 lea 0x4(%eax),%eax 800f2e: 89 45 14 mov %eax,0x14(%ebp) base = 10; 800f31: b8 0a 00 00 00 mov $0xa,%eax 800f36: e9 8b 00 00 00 jmp 800fc6 <vprintfmt+0x3bb> return va_arg(*ap, unsigned long); 800f3b: 8b 45 14 mov 0x14(%ebp),%eax 800f3e: 8b 10 mov (%eax),%edx 800f40: b9 00 00 00 00 mov $0x0,%ecx 800f45: 8d 40 04 lea 0x4(%eax),%eax 800f48: 89 45 14 mov %eax,0x14(%ebp) base = 10; 800f4b: b8 0a 00 00 00 mov $0xa,%eax 800f50: eb 74 jmp 800fc6 <vprintfmt+0x3bb> if (lflag >= 2) 800f52: 83 f9 01 cmp $0x1,%ecx 800f55: 7e 15 jle 800f6c <vprintfmt+0x361> return va_arg(*ap, unsigned long long); 800f57: 8b 45 14 mov 0x14(%ebp),%eax 800f5a: 8b 10 mov (%eax),%edx 800f5c: 8b 48 04 mov 0x4(%eax),%ecx 800f5f: 8d 40 08 lea 0x8(%eax),%eax 800f62: 89 45 14 mov %eax,0x14(%ebp) base = 8; 800f65: b8 08 00 00 00 mov $0x8,%eax 800f6a: eb 5a jmp 800fc6 <vprintfmt+0x3bb> else if (lflag) 800f6c: 85 c9 test %ecx,%ecx 800f6e: 75 17 jne 800f87 <vprintfmt+0x37c> return va_arg(*ap, unsigned int); 800f70: 8b 45 14 mov 0x14(%ebp),%eax 800f73: 8b 10 mov (%eax),%edx 800f75: b9 00 00 00 00 mov $0x0,%ecx 800f7a: 8d 40 04 lea 0x4(%eax),%eax 800f7d: 89 45 14 mov %eax,0x14(%ebp) base = 8; 800f80: b8 08 00 00 00 mov $0x8,%eax 800f85: eb 3f jmp 800fc6 <vprintfmt+0x3bb> return va_arg(*ap, unsigned long); 800f87: 8b 45 14 mov 0x14(%ebp),%eax 800f8a: 8b 10 mov (%eax),%edx 800f8c: b9 00 00 00 00 mov $0x0,%ecx 800f91: 8d 40 04 lea 0x4(%eax),%eax 800f94: 89 45 14 mov %eax,0x14(%ebp) base = 8; 800f97: b8 08 00 00 00 mov $0x8,%eax 800f9c: eb 28 jmp 800fc6 <vprintfmt+0x3bb> putch('0', putdat); 800f9e: 83 ec 08 sub $0x8,%esp 800fa1: 53 push %ebx 800fa2: 6a 30 push $0x30 800fa4: ff d6 call *%esi putch('x', putdat); 800fa6: 83 c4 08 add $0x8,%esp 800fa9: 53 push %ebx 800faa: 6a 78 push $0x78 800fac: ff d6 call *%esi num = (unsigned long long) 800fae: 8b 45 14 mov 0x14(%ebp),%eax 800fb1: 8b 10 mov (%eax),%edx 800fb3: b9 00 00 00 00 mov $0x0,%ecx goto number; 800fb8: 83 c4 10 add $0x10,%esp (uintptr_t) va_arg(ap, void *); 800fbb: 8d 40 04 lea 0x4(%eax),%eax 800fbe: 89 45 14 mov %eax,0x14(%ebp) base = 16; 800fc1: b8 10 00 00 00 mov $0x10,%eax printnum(putch, putdat, num, base, width, padc); 800fc6: 83 ec 0c sub $0xc,%esp 800fc9: 0f be 7d d4 movsbl -0x2c(%ebp),%edi 800fcd: 57 push %edi 800fce: ff 75 e0 pushl -0x20(%ebp) 800fd1: 50 push %eax 800fd2: 51 push %ecx 800fd3: 52 push %edx 800fd4: 89 da mov %ebx,%edx 800fd6: 89 f0 mov %esi,%eax 800fd8: e8 45 fb ff ff call 800b22 <printnum> break; 800fdd: 83 c4 20 add $0x20,%esp err = va_arg(ap, int); 800fe0: 8b 7d e4 mov -0x1c(%ebp),%edi while ((ch = *(unsigned char *) fmt++) != '%') { //先将非格式化字符输出到控制台。 800fe3: 83 c7 01 add $0x1,%edi 800fe6: 0f b6 47 ff movzbl -0x1(%edi),%eax 800fea: 83 f8 25 cmp $0x25,%eax 800fed: 0f 84 2f fc ff ff je 800c22 <vprintfmt+0x17> if (ch == '\0') //如果没有格式化字符直接返回 800ff3: 85 c0 test %eax,%eax 800ff5: 0f 84 8b 00 00 00 je 801086 <vprintfmt+0x47b> putch(ch, putdat); 800ffb: 83 ec 08 sub $0x8,%esp 800ffe: 53 push %ebx 800fff: 50 push %eax 801000: ff d6 call *%esi 801002: 83 c4 10 add $0x10,%esp 801005: eb dc jmp 800fe3 <vprintfmt+0x3d8> if (lflag >= 2) 801007: 83 f9 01 cmp $0x1,%ecx 80100a: 7e 15 jle 801021 <vprintfmt+0x416> return va_arg(*ap, unsigned long long); 80100c: 8b 45 14 mov 0x14(%ebp),%eax 80100f: 8b 10 mov (%eax),%edx 801011: 8b 48 04 mov 0x4(%eax),%ecx 801014: 8d 40 08 lea 0x8(%eax),%eax 801017: 89 45 14 mov %eax,0x14(%ebp) base = 16; 80101a: b8 10 00 00 00 mov $0x10,%eax 80101f: eb a5 jmp 800fc6 <vprintfmt+0x3bb> else if (lflag) 801021: 85 c9 test %ecx,%ecx 801023: 75 17 jne 80103c <vprintfmt+0x431> return va_arg(*ap, unsigned int); 801025: 8b 45 14 mov 0x14(%ebp),%eax 801028: 8b 10 mov (%eax),%edx 80102a: b9 00 00 00 00 mov $0x0,%ecx 80102f: 8d 40 04 lea 0x4(%eax),%eax 801032: 89 45 14 mov %eax,0x14(%ebp) base = 16; 801035: b8 10 00 00 00 mov $0x10,%eax 80103a: eb 8a jmp 800fc6 <vprintfmt+0x3bb> return va_arg(*ap, unsigned long); 80103c: 8b 45 14 mov 0x14(%ebp),%eax 80103f: 8b 10 mov (%eax),%edx 801041: b9 00 00 00 00 mov $0x0,%ecx 801046: 8d 40 04 lea 0x4(%eax),%eax 801049: 89 45 14 mov %eax,0x14(%ebp) base = 16; 80104c: b8 10 00 00 00 mov $0x10,%eax 801051: e9 70 ff ff ff jmp 800fc6 <vprintfmt+0x3bb> putch(ch, putdat); 801056: 83 ec 08 sub $0x8,%esp 801059: 53 push %ebx 80105a: 6a 25 push $0x25 80105c: ff d6 call *%esi break; 80105e: 83 c4 10 add $0x10,%esp 801061: e9 7a ff ff ff jmp 800fe0 <vprintfmt+0x3d5> putch('%', putdat); 801066: 83 ec 08 sub $0x8,%esp 801069: 53 push %ebx 80106a: 6a 25 push $0x25 80106c: ff d6 call *%esi for (fmt--; fmt[-1] != '%'; fmt--) 80106e: 83 c4 10 add $0x10,%esp 801071: 89 f8 mov %edi,%eax 801073: eb 03 jmp 801078 <vprintfmt+0x46d> 801075: 83 e8 01 sub $0x1,%eax 801078: 80 78 ff 25 cmpb $0x25,-0x1(%eax) 80107c: 75 f7 jne 801075 <vprintfmt+0x46a> 80107e: 89 45 e4 mov %eax,-0x1c(%ebp) 801081: e9 5a ff ff ff jmp 800fe0 <vprintfmt+0x3d5> } 801086: 8d 65 f4 lea -0xc(%ebp),%esp 801089: 5b pop %ebx 80108a: 5e pop %esi 80108b: 5f pop %edi 80108c: 5d pop %ebp 80108d: c3 ret 0080108e <vsnprintf>: int vsnprintf(char *buf, int n, const char *fmt, va_list ap) { 80108e: 55 push %ebp 80108f: 89 e5 mov %esp,%ebp 801091: 83 ec 18 sub $0x18,%esp 801094: 8b 45 08 mov 0x8(%ebp),%eax 801097: 8b 55 0c mov 0xc(%ebp),%edx struct sprintbuf b = {buf, buf+n-1, 0}; 80109a: 89 45 ec mov %eax,-0x14(%ebp) 80109d: 8d 4c 10 ff lea -0x1(%eax,%edx,1),%ecx 8010a1: 89 4d f0 mov %ecx,-0x10(%ebp) 8010a4: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) if (buf == NULL || n < 1) 8010ab: 85 c0 test %eax,%eax 8010ad: 74 26 je 8010d5 <vsnprintf+0x47> 8010af: 85 d2 test %edx,%edx 8010b1: 7e 22 jle 8010d5 <vsnprintf+0x47> return -E_INVAL; // print the string to the buffer vprintfmt((void*)sprintputch, &b, fmt, ap); 8010b3: ff 75 14 pushl 0x14(%ebp) 8010b6: ff 75 10 pushl 0x10(%ebp) 8010b9: 8d 45 ec lea -0x14(%ebp),%eax 8010bc: 50 push %eax 8010bd: 68 d1 0b 80 00 push $0x800bd1 8010c2: e8 44 fb ff ff call 800c0b <vprintfmt> // null terminate the buffer *b.buf = '\0'; 8010c7: 8b 45 ec mov -0x14(%ebp),%eax 8010ca: c6 00 00 movb $0x0,(%eax) return b.cnt; 8010cd: 8b 45 f4 mov -0xc(%ebp),%eax 8010d0: 83 c4 10 add $0x10,%esp } 8010d3: c9 leave 8010d4: c3 ret return -E_INVAL; 8010d5: b8 fd ff ff ff mov $0xfffffffd,%eax 8010da: eb f7 jmp 8010d3 <vsnprintf+0x45> 008010dc <snprintf>: int snprintf(char *buf, int n, const char *fmt, ...) { 8010dc: 55 push %ebp 8010dd: 89 e5 mov %esp,%ebp 8010df: 83 ec 08 sub $0x8,%esp va_list ap; int rc; va_start(ap, fmt); 8010e2: 8d 45 14 lea 0x14(%ebp),%eax rc = vsnprintf(buf, n, fmt, ap); 8010e5: 50 push %eax 8010e6: ff 75 10 pushl 0x10(%ebp) 8010e9: ff 75 0c pushl 0xc(%ebp) 8010ec: ff 75 08 pushl 0x8(%ebp) 8010ef: e8 9a ff ff ff call 80108e <vsnprintf> va_end(ap); return rc; } 8010f4: c9 leave 8010f5: c3 ret 008010f6 <readline>: #define BUFLEN 1024 static char buf[BUFLEN]; char * readline(const char *prompt) { 8010f6: 55 push %ebp 8010f7: 89 e5 mov %esp,%ebp 8010f9: 57 push %edi 8010fa: 56 push %esi 8010fb: 53 push %ebx 8010fc: 83 ec 0c sub $0xc,%esp 8010ff: 8b 45 08 mov 0x8(%ebp),%eax #if JOS_KERNEL if (prompt != NULL) cprintf("%s", prompt); #else if (prompt != NULL) 801102: 85 c0 test %eax,%eax 801104: 74 13 je 801119 <readline+0x23> fprintf(1, "%s", prompt); 801106: 83 ec 04 sub $0x4,%esp 801109: 50 push %eax 80110a: 68 c1 33 80 00 push $0x8033c1 80110f: 6a 01 push $0x1 801111: e8 23 14 00 00 call 802539 <fprintf> 801116: 83 c4 10 add $0x10,%esp #endif i = 0; echoing = iscons(0); 801119: 83 ec 0c sub $0xc,%esp 80111c: 6a 00 push $0x0 80111e: e8 3a f8 ff ff call 80095d <iscons> 801123: 89 c7 mov %eax,%edi 801125: 83 c4 10 add $0x10,%esp i = 0; 801128: be 00 00 00 00 mov $0x0,%esi 80112d: eb 4b jmp 80117a <readline+0x84> while (1) { c = getchar(); if (c < 0) { if (c != -E_EOF) cprintf("read error: %e\n", c); return NULL; 80112f: b8 00 00 00 00 mov $0x0,%eax if (c != -E_EOF) 801134: 83 fb f8 cmp $0xfffffff8,%ebx 801137: 75 08 jne 801141 <readline+0x4b> cputchar('\n'); buf[i] = 0; return buf; } } } 801139: 8d 65 f4 lea -0xc(%ebp),%esp 80113c: 5b pop %ebx 80113d: 5e pop %esi 80113e: 5f pop %edi 80113f: 5d pop %ebp 801140: c3 ret cprintf("read error: %e\n", c); 801141: 83 ec 08 sub $0x8,%esp 801144: 53 push %ebx 801145: 68 9f 37 80 00 push $0x80379f 80114a: e8 bf f9 ff ff call 800b0e <cprintf> 80114f: 83 c4 10 add $0x10,%esp return NULL; 801152: b8 00 00 00 00 mov $0x0,%eax 801157: eb e0 jmp 801139 <readline+0x43> if (echoing) 801159: 85 ff test %edi,%edi 80115b: 75 05 jne 801162 <readline+0x6c> i--; 80115d: 83 ee 01 sub $0x1,%esi 801160: eb 18 jmp 80117a <readline+0x84> cputchar('\b'); 801162: 83 ec 0c sub $0xc,%esp 801165: 6a 08 push $0x8 801167: e8 aa f7 ff ff call 800916 <cputchar> 80116c: 83 c4 10 add $0x10,%esp 80116f: eb ec jmp 80115d <readline+0x67> buf[i++] = c; 801171: 88 9e 20 50 80 00 mov %bl,0x805020(%esi) 801177: 8d 76 01 lea 0x1(%esi),%esi c = getchar(); 80117a: e8 b3 f7 ff ff call 800932 <getchar> 80117f: 89 c3 mov %eax,%ebx if (c < 0) { 801181: 85 c0 test %eax,%eax 801183: 78 aa js 80112f <readline+0x39> } else if ((c == '\b' || c == '\x7f') && i > 0) { 801185: 83 f8 08 cmp $0x8,%eax 801188: 0f 94 c2 sete %dl 80118b: 83 f8 7f cmp $0x7f,%eax 80118e: 0f 94 c0 sete %al 801191: 08 c2 or %al,%dl 801193: 74 04 je 801199 <readline+0xa3> 801195: 85 f6 test %esi,%esi 801197: 7f c0 jg 801159 <readline+0x63> } else if (c >= ' ' && i < BUFLEN-1) { 801199: 83 fb 1f cmp $0x1f,%ebx 80119c: 7e 1a jle 8011b8 <readline+0xc2> 80119e: 81 fe fe 03 00 00 cmp $0x3fe,%esi 8011a4: 7f 12 jg 8011b8 <readline+0xc2> if (echoing) 8011a6: 85 ff test %edi,%edi 8011a8: 74 c7 je 801171 <readline+0x7b> cputchar(c); 8011aa: 83 ec 0c sub $0xc,%esp 8011ad: 53 push %ebx 8011ae: e8 63 f7 ff ff call 800916 <cputchar> 8011b3: 83 c4 10 add $0x10,%esp 8011b6: eb b9 jmp 801171 <readline+0x7b> } else if (c == '\n' || c == '\r') { 8011b8: 83 fb 0a cmp $0xa,%ebx 8011bb: 74 05 je 8011c2 <readline+0xcc> 8011bd: 83 fb 0d cmp $0xd,%ebx 8011c0: 75 b8 jne 80117a <readline+0x84> if (echoing) 8011c2: 85 ff test %edi,%edi 8011c4: 75 11 jne 8011d7 <readline+0xe1> buf[i] = 0; 8011c6: c6 86 20 50 80 00 00 movb $0x0,0x805020(%esi) return buf; 8011cd: b8 20 50 80 00 mov $0x805020,%eax 8011d2: e9 62 ff ff ff jmp 801139 <readline+0x43> cputchar('\n'); 8011d7: 83 ec 0c sub $0xc,%esp 8011da: 6a 0a push $0xa 8011dc: e8 35 f7 ff ff call 800916 <cputchar> 8011e1: 83 c4 10 add $0x10,%esp 8011e4: eb e0 jmp 8011c6 <readline+0xd0> 008011e6 <strlen>: // Primespipe runs 3x faster this way. #define ASM 1 int strlen(const char *s) { 8011e6: 55 push %ebp 8011e7: 89 e5 mov %esp,%ebp 8011e9: 8b 55 08 mov 0x8(%ebp),%edx int n; for (n = 0; *s != '\0'; s++) 8011ec: b8 00 00 00 00 mov $0x0,%eax 8011f1: eb 03 jmp 8011f6 <strlen+0x10> n++; 8011f3: 83 c0 01 add $0x1,%eax for (n = 0; *s != '\0'; s++) 8011f6: 80 3c 02 00 cmpb $0x0,(%edx,%eax,1) 8011fa: 75 f7 jne 8011f3 <strlen+0xd> return n; } 8011fc: 5d pop %ebp 8011fd: c3 ret 008011fe <strnlen>: int strnlen(const char *s, size_t size) { 8011fe: 55 push %ebp 8011ff: 89 e5 mov %esp,%ebp 801201: 8b 4d 08 mov 0x8(%ebp),%ecx 801204: 8b 55 0c mov 0xc(%ebp),%edx int n; for (n = 0; size > 0 && *s != '\0'; s++, size--) 801207: b8 00 00 00 00 mov $0x0,%eax 80120c: eb 03 jmp 801211 <strnlen+0x13> n++; 80120e: 83 c0 01 add $0x1,%eax for (n = 0; size > 0 && *s != '\0'; s++, size--) 801211: 39 d0 cmp %edx,%eax 801213: 74 06 je 80121b <strnlen+0x1d> 801215: 80 3c 01 00 cmpb $0x0,(%ecx,%eax,1) 801219: 75 f3 jne 80120e <strnlen+0x10> return n; } 80121b: 5d pop %ebp 80121c: c3 ret 0080121d <strcpy>: char * strcpy(char *dst, const char *src) { 80121d: 55 push %ebp 80121e: 89 e5 mov %esp,%ebp 801220: 53 push %ebx 801221: 8b 45 08 mov 0x8(%ebp),%eax 801224: 8b 4d 0c mov 0xc(%ebp),%ecx char *ret; ret = dst; while ((*dst++ = *src++) != '\0') 801227: 89 c2 mov %eax,%edx 801229: 83 c1 01 add $0x1,%ecx 80122c: 83 c2 01 add $0x1,%edx 80122f: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 801233: 88 5a ff mov %bl,-0x1(%edx) 801236: 84 db test %bl,%bl 801238: 75 ef jne 801229 <strcpy+0xc> /* do nothing */; return ret; } 80123a: 5b pop %ebx 80123b: 5d pop %ebp 80123c: c3 ret 0080123d <strcat>: char * strcat(char *dst, const char *src) { 80123d: 55 push %ebp 80123e: 89 e5 mov %esp,%ebp 801240: 53 push %ebx 801241: 8b 5d 08 mov 0x8(%ebp),%ebx int len = strlen(dst); 801244: 53 push %ebx 801245: e8 9c ff ff ff call 8011e6 <strlen> 80124a: 83 c4 04 add $0x4,%esp strcpy(dst + len, src); 80124d: ff 75 0c pushl 0xc(%ebp) 801250: 01 d8 add %ebx,%eax 801252: 50 push %eax 801253: e8 c5 ff ff ff call 80121d <strcpy> return dst; } 801258: 89 d8 mov %ebx,%eax 80125a: 8b 5d fc mov -0x4(%ebp),%ebx 80125d: c9 leave 80125e: c3 ret 0080125f <strncpy>: char * strncpy(char *dst, const char *src, size_t size) { 80125f: 55 push %ebp 801260: 89 e5 mov %esp,%ebp 801262: 56 push %esi 801263: 53 push %ebx 801264: 8b 75 08 mov 0x8(%ebp),%esi 801267: 8b 4d 0c mov 0xc(%ebp),%ecx 80126a: 89 f3 mov %esi,%ebx 80126c: 03 5d 10 add 0x10(%ebp),%ebx size_t i; char *ret; ret = dst; for (i = 0; i < size; i++) { 80126f: 89 f2 mov %esi,%edx 801271: eb 0f jmp 801282 <strncpy+0x23> *dst++ = *src; 801273: 83 c2 01 add $0x1,%edx 801276: 0f b6 01 movzbl (%ecx),%eax 801279: 88 42 ff mov %al,-0x1(%edx) // If strlen(src) < size, null-pad 'dst' out to 'size' chars if (*src != '\0') src++; 80127c: 80 39 01 cmpb $0x1,(%ecx) 80127f: 83 d9 ff sbb $0xffffffff,%ecx for (i = 0; i < size; i++) { 801282: 39 da cmp %ebx,%edx 801284: 75 ed jne 801273 <strncpy+0x14> } return ret; } 801286: 89 f0 mov %esi,%eax 801288: 5b pop %ebx 801289: 5e pop %esi 80128a: 5d pop %ebp 80128b: c3 ret 0080128c <strlcpy>: size_t strlcpy(char *dst, const char *src, size_t size) { 80128c: 55 push %ebp 80128d: 89 e5 mov %esp,%ebp 80128f: 56 push %esi 801290: 53 push %ebx 801291: 8b 75 08 mov 0x8(%ebp),%esi 801294: 8b 55 0c mov 0xc(%ebp),%edx 801297: 8b 4d 10 mov 0x10(%ebp),%ecx 80129a: 89 f0 mov %esi,%eax 80129c: 8d 5c 0e ff lea -0x1(%esi,%ecx,1),%ebx char *dst_in; dst_in = dst; if (size > 0) { 8012a0: 85 c9 test %ecx,%ecx 8012a2: 75 0b jne 8012af <strlcpy+0x23> 8012a4: eb 17 jmp 8012bd <strlcpy+0x31> while (--size > 0 && *src != '\0') *dst++ = *src++; 8012a6: 83 c2 01 add $0x1,%edx 8012a9: 83 c0 01 add $0x1,%eax 8012ac: 88 48 ff mov %cl,-0x1(%eax) while (--size > 0 && *src != '\0') 8012af: 39 d8 cmp %ebx,%eax 8012b1: 74 07 je 8012ba <strlcpy+0x2e> 8012b3: 0f b6 0a movzbl (%edx),%ecx 8012b6: 84 c9 test %cl,%cl 8012b8: 75 ec jne 8012a6 <strlcpy+0x1a> *dst = '\0'; 8012ba: c6 00 00 movb $0x0,(%eax) } return dst - dst_in; 8012bd: 29 f0 sub %esi,%eax } 8012bf: 5b pop %ebx 8012c0: 5e pop %esi 8012c1: 5d pop %ebp 8012c2: c3 ret 008012c3 <strcmp>: int strcmp(const char *p, const char *q) { 8012c3: 55 push %ebp 8012c4: 89 e5 mov %esp,%ebp 8012c6: 8b 4d 08 mov 0x8(%ebp),%ecx 8012c9: 8b 55 0c mov 0xc(%ebp),%edx while (*p && *p == *q) 8012cc: eb 06 jmp 8012d4 <strcmp+0x11> p++, q++; 8012ce: 83 c1 01 add $0x1,%ecx 8012d1: 83 c2 01 add $0x1,%edx while (*p && *p == *q) 8012d4: 0f b6 01 movzbl (%ecx),%eax 8012d7: 84 c0 test %al,%al 8012d9: 74 04 je 8012df <strcmp+0x1c> 8012db: 3a 02 cmp (%edx),%al 8012dd: 74 ef je 8012ce <strcmp+0xb> return (int) ((unsigned char) *p - (unsigned char) *q); 8012df: 0f b6 c0 movzbl %al,%eax 8012e2: 0f b6 12 movzbl (%edx),%edx 8012e5: 29 d0 sub %edx,%eax } 8012e7: 5d pop %ebp 8012e8: c3 ret 008012e9 <strncmp>: int strncmp(const char *p, const char *q, size_t n) { 8012e9: 55 push %ebp 8012ea: 89 e5 mov %esp,%ebp 8012ec: 53 push %ebx 8012ed: 8b 45 08 mov 0x8(%ebp),%eax 8012f0: 8b 55 0c mov 0xc(%ebp),%edx 8012f3: 89 c3 mov %eax,%ebx 8012f5: 03 5d 10 add 0x10(%ebp),%ebx while (n > 0 && *p && *p == *q) 8012f8: eb 06 jmp 801300 <strncmp+0x17> n--, p++, q++; 8012fa: 83 c0 01 add $0x1,%eax 8012fd: 83 c2 01 add $0x1,%edx while (n > 0 && *p && *p == *q) 801300: 39 d8 cmp %ebx,%eax 801302: 74 16 je 80131a <strncmp+0x31> 801304: 0f b6 08 movzbl (%eax),%ecx 801307: 84 c9 test %cl,%cl 801309: 74 04 je 80130f <strncmp+0x26> 80130b: 3a 0a cmp (%edx),%cl 80130d: 74 eb je 8012fa <strncmp+0x11> if (n == 0) return 0; else return (int) ((unsigned char) *p - (unsigned char) *q); 80130f: 0f b6 00 movzbl (%eax),%eax 801312: 0f b6 12 movzbl (%edx),%edx 801315: 29 d0 sub %edx,%eax } 801317: 5b pop %ebx 801318: 5d pop %ebp 801319: c3 ret return 0; 80131a: b8 00 00 00 00 mov $0x0,%eax 80131f: eb f6 jmp 801317 <strncmp+0x2e> 00801321 <strchr>: // Return a pointer to the first occurrence of 'c' in 's', // or a null pointer if the string has no 'c'. char * strchr(const char *s, char c) { 801321: 55 push %ebp 801322: 89 e5 mov %esp,%ebp 801324: 8b 45 08 mov 0x8(%ebp),%eax 801327: 0f b6 4d 0c movzbl 0xc(%ebp),%ecx for (; *s; s++) 80132b: 0f b6 10 movzbl (%eax),%edx 80132e: 84 d2 test %dl,%dl 801330: 74 09 je 80133b <strchr+0x1a> if (*s == c) 801332: 38 ca cmp %cl,%dl 801334: 74 0a je 801340 <strchr+0x1f> for (; *s; s++) 801336: 83 c0 01 add $0x1,%eax 801339: eb f0 jmp 80132b <strchr+0xa> return (char *) s; return 0; 80133b: b8 00 00 00 00 mov $0x0,%eax } 801340: 5d pop %ebp 801341: c3 ret 00801342 <strfind>: // Return a pointer to the first occurrence of 'c' in 's', // or a pointer to the string-ending null character if the string has no 'c'. char * strfind(const char *s, char c) { 801342: 55 push %ebp 801343: 89 e5 mov %esp,%ebp 801345: 8b 45 08 mov 0x8(%ebp),%eax 801348: 0f b6 4d 0c movzbl 0xc(%ebp),%ecx for (; *s; s++) 80134c: eb 03 jmp 801351 <strfind+0xf> 80134e: 83 c0 01 add $0x1,%eax 801351: 0f b6 10 movzbl (%eax),%edx if (*s == c) 801354: 38 ca cmp %cl,%dl 801356: 74 04 je 80135c <strfind+0x1a> 801358: 84 d2 test %dl,%dl 80135a: 75 f2 jne 80134e <strfind+0xc> break; return (char *) s; } 80135c: 5d pop %ebp 80135d: c3 ret 0080135e <memset>: #if ASM void * memset(void *v, int c, size_t n) { 80135e: 55 push %ebp 80135f: 89 e5 mov %esp,%ebp 801361: 57 push %edi 801362: 56 push %esi 801363: 53 push %ebx 801364: 8b 7d 08 mov 0x8(%ebp),%edi 801367: 8b 4d 10 mov 0x10(%ebp),%ecx char *p; if (n == 0) 80136a: 85 c9 test %ecx,%ecx 80136c: 74 13 je 801381 <memset+0x23> return v; if ((int)v%4 == 0 && n%4 == 0) { 80136e: f7 c7 03 00 00 00 test $0x3,%edi 801374: 75 05 jne 80137b <memset+0x1d> 801376: f6 c1 03 test $0x3,%cl 801379: 74 0d je 801388 <memset+0x2a> c = (c<<24)|(c<<16)|(c<<8)|c; asm volatile("cld; rep stosl\n" :: "D" (v), "a" (c), "c" (n/4) : "cc", "memory"); } else asm volatile("cld; rep stosb\n" 80137b: 8b 45 0c mov 0xc(%ebp),%eax 80137e: fc cld 80137f: f3 aa rep stos %al,%es:(%edi) :: "D" (v), "a" (c), "c" (n) : "cc", "memory"); return v; } 801381: 89 f8 mov %edi,%eax 801383: 5b pop %ebx 801384: 5e pop %esi 801385: 5f pop %edi 801386: 5d pop %ebp 801387: c3 ret c &= 0xFF; 801388: 0f b6 55 0c movzbl 0xc(%ebp),%edx c = (c<<24)|(c<<16)|(c<<8)|c; 80138c: 89 d3 mov %edx,%ebx 80138e: c1 e3 08 shl $0x8,%ebx 801391: 89 d0 mov %edx,%eax 801393: c1 e0 18 shl $0x18,%eax 801396: 89 d6 mov %edx,%esi 801398: c1 e6 10 shl $0x10,%esi 80139b: 09 f0 or %esi,%eax 80139d: 09 c2 or %eax,%edx 80139f: 09 da or %ebx,%edx :: "D" (v), "a" (c), "c" (n/4) 8013a1: c1 e9 02 shr $0x2,%ecx asm volatile("cld; rep stosl\n" 8013a4: 89 d0 mov %edx,%eax 8013a6: fc cld 8013a7: f3 ab rep stos %eax,%es:(%edi) 8013a9: eb d6 jmp 801381 <memset+0x23> 008013ab <memmove>: void * memmove(void *dst, const void *src, size_t n) { 8013ab: 55 push %ebp 8013ac: 89 e5 mov %esp,%ebp 8013ae: 57 push %edi 8013af: 56 push %esi 8013b0: 8b 45 08 mov 0x8(%ebp),%eax 8013b3: 8b 75 0c mov 0xc(%ebp),%esi 8013b6: 8b 4d 10 mov 0x10(%ebp),%ecx const char *s; char *d; s = src; d = dst; if (s < d && s + n > d) { 8013b9: 39 c6 cmp %eax,%esi 8013bb: 73 35 jae 8013f2 <memmove+0x47> 8013bd: 8d 14 0e lea (%esi,%ecx,1),%edx 8013c0: 39 c2 cmp %eax,%edx 8013c2: 76 2e jbe 8013f2 <memmove+0x47> s += n; d += n; 8013c4: 8d 3c 08 lea (%eax,%ecx,1),%edi if ((int)s%4 == 0 && (int)d%4 == 0 && n%4 == 0) 8013c7: 89 d6 mov %edx,%esi 8013c9: 09 fe or %edi,%esi 8013cb: f7 c6 03 00 00 00 test $0x3,%esi 8013d1: 74 0c je 8013df <memmove+0x34> asm volatile("std; rep movsl\n" :: "D" (d-4), "S" (s-4), "c" (n/4) : "cc", "memory"); else asm volatile("std; rep movsb\n" :: "D" (d-1), "S" (s-1), "c" (n) : "cc", "memory"); 8013d3: 83 ef 01 sub $0x1,%edi 8013d6: 8d 72 ff lea -0x1(%edx),%esi asm volatile("std; rep movsb\n" 8013d9: fd std 8013da: f3 a4 rep movsb %ds:(%esi),%es:(%edi) // Some versions of GCC rely on DF being clear asm volatile("cld" ::: "cc"); 8013dc: fc cld 8013dd: eb 21 jmp 801400 <memmove+0x55> if ((int)s%4 == 0 && (int)d%4 == 0 && n%4 == 0) 8013df: f6 c1 03 test $0x3,%cl 8013e2: 75 ef jne 8013d3 <memmove+0x28> :: "D" (d-4), "S" (s-4), "c" (n/4) : "cc", "memory"); 8013e4: 83 ef 04 sub $0x4,%edi 8013e7: 8d 72 fc lea -0x4(%edx),%esi 8013ea: c1 e9 02 shr $0x2,%ecx asm volatile("std; rep movsl\n" 8013ed: fd std 8013ee: f3 a5 rep movsl %ds:(%esi),%es:(%edi) 8013f0: eb ea jmp 8013dc <memmove+0x31> } else { if ((int)s%4 == 0 && (int)d%4 == 0 && n%4 == 0) 8013f2: 89 f2 mov %esi,%edx 8013f4: 09 c2 or %eax,%edx 8013f6: f6 c2 03 test $0x3,%dl 8013f9: 74 09 je 801404 <memmove+0x59> asm volatile("cld; rep movsl\n" :: "D" (d), "S" (s), "c" (n/4) : "cc", "memory"); else asm volatile("cld; rep movsb\n" 8013fb: 89 c7 mov %eax,%edi 8013fd: fc cld 8013fe: f3 a4 rep movsb %ds:(%esi),%es:(%edi) :: "D" (d), "S" (s), "c" (n) : "cc", "memory"); } return dst; } 801400: 5e pop %esi 801401: 5f pop %edi 801402: 5d pop %ebp 801403: c3 ret if ((int)s%4 == 0 && (int)d%4 == 0 && n%4 == 0) 801404: f6 c1 03 test $0x3,%cl 801407: 75 f2 jne 8013fb <memmove+0x50> :: "D" (d), "S" (s), "c" (n/4) : "cc", "memory"); 801409: c1 e9 02 shr $0x2,%ecx asm volatile("cld; rep movsl\n" 80140c: 89 c7 mov %eax,%edi 80140e: fc cld 80140f: f3 a5 rep movsl %ds:(%esi),%es:(%edi) 801411: eb ed jmp 801400 <memmove+0x55> 00801413 <memcpy>: } #endif void * memcpy(void *dst, const void *src, size_t n) { 801413: 55 push %ebp 801414: 89 e5 mov %esp,%ebp return memmove(dst, src, n); 801416: ff 75 10 pushl 0x10(%ebp) 801419: ff 75 0c pushl 0xc(%ebp) 80141c: ff 75 08 pushl 0x8(%ebp) 80141f: e8 87 ff ff ff call 8013ab <memmove> } 801424: c9 leave 801425: c3 ret 00801426 <memcmp>: int memcmp(const void *v1, const void *v2, size_t n) { 801426: 55 push %ebp 801427: 89 e5 mov %esp,%ebp 801429: 56 push %esi 80142a: 53 push %ebx 80142b: 8b 45 08 mov 0x8(%ebp),%eax 80142e: 8b 55 0c mov 0xc(%ebp),%edx 801431: 89 c6 mov %eax,%esi 801433: 03 75 10 add 0x10(%ebp),%esi const uint8_t *s1 = (const uint8_t *) v1; const uint8_t *s2 = (const uint8_t *) v2; while (n-- > 0) { 801436: 39 f0 cmp %esi,%eax 801438: 74 1c je 801456 <memcmp+0x30> if (*s1 != *s2) 80143a: 0f b6 08 movzbl (%eax),%ecx 80143d: 0f b6 1a movzbl (%edx),%ebx 801440: 38 d9 cmp %bl,%cl 801442: 75 08 jne 80144c <memcmp+0x26> return (int) *s1 - (int) *s2; s1++, s2++; 801444: 83 c0 01 add $0x1,%eax 801447: 83 c2 01 add $0x1,%edx 80144a: eb ea jmp 801436 <memcmp+0x10> return (int) *s1 - (int) *s2; 80144c: 0f b6 c1 movzbl %cl,%eax 80144f: 0f b6 db movzbl %bl,%ebx 801452: 29 d8 sub %ebx,%eax 801454: eb 05 jmp 80145b <memcmp+0x35> } return 0; 801456: b8 00 00 00 00 mov $0x0,%eax } 80145b: 5b pop %ebx 80145c: 5e pop %esi 80145d: 5d pop %ebp 80145e: c3 ret 0080145f <memfind>: void * memfind(const void *s, int c, size_t n) { 80145f: 55 push %ebp 801460: 89 e5 mov %esp,%ebp 801462: 8b 45 08 mov 0x8(%ebp),%eax 801465: 8b 4d 0c mov 0xc(%ebp),%ecx const void *ends = (const char *) s + n; 801468: 89 c2 mov %eax,%edx 80146a: 03 55 10 add 0x10(%ebp),%edx for (; s < ends; s++) 80146d: 39 d0 cmp %edx,%eax 80146f: 73 09 jae 80147a <memfind+0x1b> if (*(const unsigned char *) s == (unsigned char) c) 801471: 38 08 cmp %cl,(%eax) 801473: 74 05 je 80147a <memfind+0x1b> for (; s < ends; s++) 801475: 83 c0 01 add $0x1,%eax 801478: eb f3 jmp 80146d <memfind+0xe> break; return (void *) s; } 80147a: 5d pop %ebp 80147b: c3 ret 0080147c <strtol>: long strtol(const char *s, char **endptr, int base) { 80147c: 55 push %ebp 80147d: 89 e5 mov %esp,%ebp 80147f: 57 push %edi 801480: 56 push %esi 801481: 53 push %ebx 801482: 8b 4d 08 mov 0x8(%ebp),%ecx 801485: 8b 5d 10 mov 0x10(%ebp),%ebx int neg = 0; long val = 0; // gobble initial whitespace while (*s == ' ' || *s == '\t') 801488: eb 03 jmp 80148d <strtol+0x11> s++; 80148a: 83 c1 01 add $0x1,%ecx while (*s == ' ' || *s == '\t') 80148d: 0f b6 01 movzbl (%ecx),%eax 801490: 3c 20 cmp $0x20,%al 801492: 74 f6 je 80148a <strtol+0xe> 801494: 3c 09 cmp $0x9,%al 801496: 74 f2 je 80148a <strtol+0xe> // plus/minus sign if (*s == '+') 801498: 3c 2b cmp $0x2b,%al 80149a: 74 2e je 8014ca <strtol+0x4e> int neg = 0; 80149c: bf 00 00 00 00 mov $0x0,%edi s++; else if (*s == '-') 8014a1: 3c 2d cmp $0x2d,%al 8014a3: 74 2f je 8014d4 <strtol+0x58> s++, neg = 1; // hex or octal base prefix if ((base == 0 || base == 16) && (s[0] == '0' && s[1] == 'x')) 8014a5: f7 c3 ef ff ff ff test $0xffffffef,%ebx 8014ab: 75 05 jne 8014b2 <strtol+0x36> 8014ad: 80 39 30 cmpb $0x30,(%ecx) 8014b0: 74 2c je 8014de <strtol+0x62> s += 2, base = 16; else if (base == 0 && s[0] == '0') 8014b2: 85 db test %ebx,%ebx 8014b4: 75 0a jne 8014c0 <strtol+0x44> s++, base = 8; else if (base == 0) base = 10; 8014b6: bb 0a 00 00 00 mov $0xa,%ebx else if (base == 0 && s[0] == '0') 8014bb: 80 39 30 cmpb $0x30,(%ecx) 8014be: 74 28 je 8014e8 <strtol+0x6c> base = 10; 8014c0: b8 00 00 00 00 mov $0x0,%eax 8014c5: 89 5d 10 mov %ebx,0x10(%ebp) 8014c8: eb 50 jmp 80151a <strtol+0x9e> s++; 8014ca: 83 c1 01 add $0x1,%ecx int neg = 0; 8014cd: bf 00 00 00 00 mov $0x0,%edi 8014d2: eb d1 jmp 8014a5 <strtol+0x29> s++, neg = 1; 8014d4: 83 c1 01 add $0x1,%ecx 8014d7: bf 01 00 00 00 mov $0x1,%edi 8014dc: eb c7 jmp 8014a5 <strtol+0x29> if ((base == 0 || base == 16) && (s[0] == '0' && s[1] == 'x')) 8014de: 80 79 01 78 cmpb $0x78,0x1(%ecx) 8014e2: 74 0e je 8014f2 <strtol+0x76> else if (base == 0 && s[0] == '0') 8014e4: 85 db test %ebx,%ebx 8014e6: 75 d8 jne 8014c0 <strtol+0x44> s++, base = 8; 8014e8: 83 c1 01 add $0x1,%ecx 8014eb: bb 08 00 00 00 mov $0x8,%ebx 8014f0: eb ce jmp 8014c0 <strtol+0x44> s += 2, base = 16; 8014f2: 83 c1 02 add $0x2,%ecx 8014f5: bb 10 00 00 00 mov $0x10,%ebx 8014fa: eb c4 jmp 8014c0 <strtol+0x44> while (1) { int dig; if (*s >= '0' && *s <= '9') dig = *s - '0'; else if (*s >= 'a' && *s <= 'z') 8014fc: 8d 72 9f lea -0x61(%edx),%esi 8014ff: 89 f3 mov %esi,%ebx 801501: 80 fb 19 cmp $0x19,%bl 801504: 77 29 ja 80152f <strtol+0xb3> dig = *s - 'a' + 10; 801506: 0f be d2 movsbl %dl,%edx 801509: 83 ea 57 sub $0x57,%edx else if (*s >= 'A' && *s <= 'Z') dig = *s - 'A' + 10; else break; if (dig >= base) 80150c: 3b 55 10 cmp 0x10(%ebp),%edx 80150f: 7d 30 jge 801541 <strtol+0xc5> break; s++, val = (val * base) + dig; 801511: 83 c1 01 add $0x1,%ecx 801514: 0f af 45 10 imul 0x10(%ebp),%eax 801518: 01 d0 add %edx,%eax if (*s >= '0' && *s <= '9') 80151a: 0f b6 11 movzbl (%ecx),%edx 80151d: 8d 72 d0 lea -0x30(%edx),%esi 801520: 89 f3 mov %esi,%ebx 801522: 80 fb 09 cmp $0x9,%bl 801525: 77 d5 ja 8014fc <strtol+0x80> dig = *s - '0'; 801527: 0f be d2 movsbl %dl,%edx 80152a: 83 ea 30 sub $0x30,%edx 80152d: eb dd jmp 80150c <strtol+0x90> else if (*s >= 'A' && *s <= 'Z') 80152f: 8d 72 bf lea -0x41(%edx),%esi 801532: 89 f3 mov %esi,%ebx 801534: 80 fb 19 cmp $0x19,%bl 801537: 77 08 ja 801541 <strtol+0xc5> dig = *s - 'A' + 10; 801539: 0f be d2 movsbl %dl,%edx 80153c: 83 ea 37 sub $0x37,%edx 80153f: eb cb jmp 80150c <strtol+0x90> // we don't properly detect overflow! } if (endptr) 801541: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 801545: 74 05 je 80154c <strtol+0xd0> *endptr = (char *) s; 801547: 8b 75 0c mov 0xc(%ebp),%esi 80154a: 89 0e mov %ecx,(%esi) return (neg ? -val : val); 80154c: 89 c2 mov %eax,%edx 80154e: f7 da neg %edx 801550: 85 ff test %edi,%edi 801552: 0f 45 c2 cmovne %edx,%eax } 801555: 5b pop %ebx 801556: 5e pop %esi 801557: 5f pop %edi 801558: 5d pop %ebp 801559: c3 ret 0080155a <sys_cputs>: return ret; } void sys_cputs(const char *s, size_t len) { 80155a: 55 push %ebp 80155b: 89 e5 mov %esp,%ebp 80155d: 57 push %edi 80155e: 56 push %esi 80155f: 53 push %ebx asm volatile("int %1\n" //执行int T_SYSCALL指令 801560: b8 00 00 00 00 mov $0x0,%eax 801565: 8b 55 08 mov 0x8(%ebp),%edx 801568: 8b 4d 0c mov 0xc(%ebp),%ecx 80156b: 89 c3 mov %eax,%ebx 80156d: 89 c7 mov %eax,%edi 80156f: 89 c6 mov %eax,%esi 801571: cd 30 int $0x30 syscall(SYS_cputs, 0, (uint32_t)s, len, 0, 0, 0); } 801573: 5b pop %ebx 801574: 5e pop %esi 801575: 5f pop %edi 801576: 5d pop %ebp 801577: c3 ret 00801578 <sys_cgetc>: int sys_cgetc(void) { 801578: 55 push %ebp 801579: 89 e5 mov %esp,%ebp 80157b: 57 push %edi 80157c: 56 push %esi 80157d: 53 push %ebx asm volatile("int %1\n" //执行int T_SYSCALL指令 80157e: ba 00 00 00 00 mov $0x0,%edx 801583: b8 01 00 00 00 mov $0x1,%eax 801588: 89 d1 mov %edx,%ecx 80158a: 89 d3 mov %edx,%ebx 80158c: 89 d7 mov %edx,%edi 80158e: 89 d6 mov %edx,%esi 801590: cd 30 int $0x30 return syscall(SYS_cgetc, 0, 0, 0, 0, 0, 0); } 801592: 5b pop %ebx 801593: 5e pop %esi 801594: 5f pop %edi 801595: 5d pop %ebp 801596: c3 ret 00801597 <sys_env_destroy>: int sys_env_destroy(envid_t envid) { 801597: 55 push %ebp 801598: 89 e5 mov %esp,%ebp 80159a: 57 push %edi 80159b: 56 push %esi 80159c: 53 push %ebx 80159d: 83 ec 0c sub $0xc,%esp asm volatile("int %1\n" //执行int T_SYSCALL指令 8015a0: b9 00 00 00 00 mov $0x0,%ecx 8015a5: 8b 55 08 mov 0x8(%ebp),%edx 8015a8: b8 03 00 00 00 mov $0x3,%eax 8015ad: 89 cb mov %ecx,%ebx 8015af: 89 cf mov %ecx,%edi 8015b1: 89 ce mov %ecx,%esi 8015b3: cd 30 int $0x30 if(check && ret > 0) 8015b5: 85 c0 test %eax,%eax 8015b7: 7f 08 jg 8015c1 <sys_env_destroy+0x2a> return syscall(SYS_env_destroy, 1, envid, 0, 0, 0, 0); } 8015b9: 8d 65 f4 lea -0xc(%ebp),%esp 8015bc: 5b pop %ebx 8015bd: 5e pop %esi 8015be: 5f pop %edi 8015bf: 5d pop %ebp 8015c0: c3 ret panic("syscall %d returned %d (> 0)", num, ret); 8015c1: 83 ec 0c sub $0xc,%esp 8015c4: 50 push %eax 8015c5: 6a 03 push $0x3 8015c7: 68 af 37 80 00 push $0x8037af 8015cc: 6a 23 push $0x23 8015ce: 68 cc 37 80 00 push $0x8037cc 8015d3: e8 5b f4 ff ff call 800a33 <_panic> 008015d8 <sys_getenvid>: envid_t sys_getenvid(void) { 8015d8: 55 push %ebp 8015d9: 89 e5 mov %esp,%ebp 8015db: 57 push %edi 8015dc: 56 push %esi 8015dd: 53 push %ebx asm volatile("int %1\n" //执行int T_SYSCALL指令 8015de: ba 00 00 00 00 mov $0x0,%edx 8015e3: b8 02 00 00 00 mov $0x2,%eax 8015e8: 89 d1 mov %edx,%ecx 8015ea: 89 d3 mov %edx,%ebx 8015ec: 89 d7 mov %edx,%edi 8015ee: 89 d6 mov %edx,%esi 8015f0: cd 30 int $0x30 return syscall(SYS_getenvid, 0, 0, 0, 0, 0, 0); } 8015f2: 5b pop %ebx 8015f3: 5e pop %esi 8015f4: 5f pop %edi 8015f5: 5d pop %ebp 8015f6: c3 ret 008015f7 <sys_yield>: void sys_yield(void) { 8015f7: 55 push %ebp 8015f8: 89 e5 mov %esp,%ebp 8015fa: 57 push %edi 8015fb: 56 push %esi 8015fc: 53 push %ebx asm volatile("int %1\n" //执行int T_SYSCALL指令 8015fd: ba 00 00 00 00 mov $0x0,%edx 801602: b8 0b 00 00 00 mov $0xb,%eax 801607: 89 d1 mov %edx,%ecx 801609: 89 d3 mov %edx,%ebx 80160b: 89 d7 mov %edx,%edi 80160d: 89 d6 mov %edx,%esi 80160f: cd 30 int $0x30 syscall(SYS_yield, 0, 0, 0, 0, 0, 0); } 801611: 5b pop %ebx 801612: 5e pop %esi 801613: 5f pop %edi 801614: 5d pop %ebp 801615: c3 ret 00801616 <sys_page_alloc>: int sys_page_alloc(envid_t envid, void *va, int perm) { 801616: 55 push %ebp 801617: 89 e5 mov %esp,%ebp 801619: 57 push %edi 80161a: 56 push %esi 80161b: 53 push %ebx 80161c: 83 ec 0c sub $0xc,%esp asm volatile("int %1\n" //执行int T_SYSCALL指令 80161f: be 00 00 00 00 mov $0x0,%esi 801624: 8b 55 08 mov 0x8(%ebp),%edx 801627: 8b 4d 0c mov 0xc(%ebp),%ecx 80162a: b8 04 00 00 00 mov $0x4,%eax 80162f: 8b 5d 10 mov 0x10(%ebp),%ebx 801632: 89 f7 mov %esi,%edi 801634: cd 30 int $0x30 if(check && ret > 0) 801636: 85 c0 test %eax,%eax 801638: 7f 08 jg 801642 <sys_page_alloc+0x2c> return syscall(SYS_page_alloc, 1, envid, (uint32_t) va, perm, 0, 0); } 80163a: 8d 65 f4 lea -0xc(%ebp),%esp 80163d: 5b pop %ebx 80163e: 5e pop %esi 80163f: 5f pop %edi 801640: 5d pop %ebp 801641: c3 ret panic("syscall %d returned %d (> 0)", num, ret); 801642: 83 ec 0c sub $0xc,%esp 801645: 50 push %eax 801646: 6a 04 push $0x4 801648: 68 af 37 80 00 push $0x8037af 80164d: 6a 23 push $0x23 80164f: 68 cc 37 80 00 push $0x8037cc 801654: e8 da f3 ff ff call 800a33 <_panic> 00801659 <sys_page_map>: int sys_page_map(envid_t srcenv, void *srcva, envid_t dstenv, void *dstva, int perm) { 801659: 55 push %ebp 80165a: 89 e5 mov %esp,%ebp 80165c: 57 push %edi 80165d: 56 push %esi 80165e: 53 push %ebx 80165f: 83 ec 0c sub $0xc,%esp asm volatile("int %1\n" //执行int T_SYSCALL指令 801662: 8b 55 08 mov 0x8(%ebp),%edx 801665: 8b 4d 0c mov 0xc(%ebp),%ecx 801668: b8 05 00 00 00 mov $0x5,%eax 80166d: 8b 5d 10 mov 0x10(%ebp),%ebx 801670: 8b 7d 14 mov 0x14(%ebp),%edi 801673: 8b 75 18 mov 0x18(%ebp),%esi 801676: cd 30 int $0x30 if(check && ret > 0) 801678: 85 c0 test %eax,%eax 80167a: 7f 08 jg 801684 <sys_page_map+0x2b> return syscall(SYS_page_map, 1, srcenv, (uint32_t) srcva, dstenv, (uint32_t) dstva, perm); } 80167c: 8d 65 f4 lea -0xc(%ebp),%esp 80167f: 5b pop %ebx 801680: 5e pop %esi 801681: 5f pop %edi 801682: 5d pop %ebp 801683: c3 ret panic("syscall %d returned %d (> 0)", num, ret); 801684: 83 ec 0c sub $0xc,%esp 801687: 50 push %eax 801688: 6a 05 push $0x5 80168a: 68 af 37 80 00 push $0x8037af 80168f: 6a 23 push $0x23 801691: 68 cc 37 80 00 push $0x8037cc 801696: e8 98 f3 ff ff call 800a33 <_panic> 0080169b <sys_page_unmap>: int sys_page_unmap(envid_t envid, void *va) { 80169b: 55 push %ebp 80169c: 89 e5 mov %esp,%ebp 80169e: 57 push %edi 80169f: 56 push %esi 8016a0: 53 push %ebx 8016a1: 83 ec 0c sub $0xc,%esp asm volatile("int %1\n" //执行int T_SYSCALL指令 8016a4: bb 00 00 00 00 mov $0x0,%ebx 8016a9: 8b 55 08 mov 0x8(%ebp),%edx 8016ac: 8b 4d 0c mov 0xc(%ebp),%ecx 8016af: b8 06 00 00 00 mov $0x6,%eax 8016b4: 89 df mov %ebx,%edi 8016b6: 89 de mov %ebx,%esi 8016b8: cd 30 int $0x30 if(check && ret > 0) 8016ba: 85 c0 test %eax,%eax 8016bc: 7f 08 jg 8016c6 <sys_page_unmap+0x2b> return syscall(SYS_page_unmap, 1, envid, (uint32_t) va, 0, 0, 0); } 8016be: 8d 65 f4 lea -0xc(%ebp),%esp 8016c1: 5b pop %ebx 8016c2: 5e pop %esi 8016c3: 5f pop %edi 8016c4: 5d pop %ebp 8016c5: c3 ret panic("syscall %d returned %d (> 0)", num, ret); 8016c6: 83 ec 0c sub $0xc,%esp 8016c9: 50 push %eax 8016ca: 6a 06 push $0x6 8016cc: 68 af 37 80 00 push $0x8037af 8016d1: 6a 23 push $0x23 8016d3: 68 cc 37 80 00 push $0x8037cc 8016d8: e8 56 f3 ff ff call 800a33 <_panic> 008016dd <sys_env_set_status>: // sys_exofork is inlined in lib.h int sys_env_set_status(envid_t envid, int status) { 8016dd: 55 push %ebp 8016de: 89 e5 mov %esp,%ebp 8016e0: 57 push %edi 8016e1: 56 push %esi 8016e2: 53 push %ebx 8016e3: 83 ec 0c sub $0xc,%esp asm volatile("int %1\n" //执行int T_SYSCALL指令 8016e6: bb 00 00 00 00 mov $0x0,%ebx 8016eb: 8b 55 08 mov 0x8(%ebp),%edx 8016ee: 8b 4d 0c mov 0xc(%ebp),%ecx 8016f1: b8 08 00 00 00 mov $0x8,%eax 8016f6: 89 df mov %ebx,%edi 8016f8: 89 de mov %ebx,%esi 8016fa: cd 30 int $0x30 if(check && ret > 0) 8016fc: 85 c0 test %eax,%eax 8016fe: 7f 08 jg 801708 <sys_env_set_status+0x2b> return syscall(SYS_env_set_status, 1, envid, status, 0, 0, 0); } 801700: 8d 65 f4 lea -0xc(%ebp),%esp 801703: 5b pop %ebx 801704: 5e pop %esi 801705: 5f pop %edi 801706: 5d pop %ebp 801707: c3 ret panic("syscall %d returned %d (> 0)", num, ret); 801708: 83 ec 0c sub $0xc,%esp 80170b: 50 push %eax 80170c: 6a 08 push $0x8 80170e: 68 af 37 80 00 push $0x8037af 801713: 6a 23 push $0x23 801715: 68 cc 37 80 00 push $0x8037cc 80171a: e8 14 f3 ff ff call 800a33 <_panic> 0080171f <sys_env_set_trapframe>: int sys_env_set_trapframe(envid_t envid, struct Trapframe *tf) { 80171f: 55 push %ebp 801720: 89 e5 mov %esp,%ebp 801722: 57 push %edi 801723: 56 push %esi 801724: 53 push %ebx 801725: 83 ec 0c sub $0xc,%esp asm volatile("int %1\n" //执行int T_SYSCALL指令 801728: bb 00 00 00 00 mov $0x0,%ebx 80172d: 8b 55 08 mov 0x8(%ebp),%edx 801730: 8b 4d 0c mov 0xc(%ebp),%ecx 801733: b8 09 00 00 00 mov $0x9,%eax 801738: 89 df mov %ebx,%edi 80173a: 89 de mov %ebx,%esi 80173c: cd 30 int $0x30 if(check && ret > 0) 80173e: 85 c0 test %eax,%eax 801740: 7f 08 jg 80174a <sys_env_set_trapframe+0x2b> return syscall(SYS_env_set_trapframe, 1, envid, (uint32_t) tf, 0, 0, 0); } 801742: 8d 65 f4 lea -0xc(%ebp),%esp 801745: 5b pop %ebx 801746: 5e pop %esi 801747: 5f pop %edi 801748: 5d pop %ebp 801749: c3 ret panic("syscall %d returned %d (> 0)", num, ret); 80174a: 83 ec 0c sub $0xc,%esp 80174d: 50 push %eax 80174e: 6a 09 push $0x9 801750: 68 af 37 80 00 push $0x8037af 801755: 6a 23 push $0x23 801757: 68 cc 37 80 00 push $0x8037cc 80175c: e8 d2 f2 ff ff call 800a33 <_panic> 00801761 <sys_env_set_pgfault_upcall>: int sys_env_set_pgfault_upcall(envid_t envid, void *upcall) { 801761: 55 push %ebp 801762: 89 e5 mov %esp,%ebp 801764: 57 push %edi 801765: 56 push %esi 801766: 53 push %ebx 801767: 83 ec 0c sub $0xc,%esp asm volatile("int %1\n" //执行int T_SYSCALL指令 80176a: bb 00 00 00 00 mov $0x0,%ebx 80176f: 8b 55 08 mov 0x8(%ebp),%edx 801772: 8b 4d 0c mov 0xc(%ebp),%ecx 801775: b8 0a 00 00 00 mov $0xa,%eax 80177a: 89 df mov %ebx,%edi 80177c: 89 de mov %ebx,%esi 80177e: cd 30 int $0x30 if(check && ret > 0) 801780: 85 c0 test %eax,%eax 801782: 7f 08 jg 80178c <sys_env_set_pgfault_upcall+0x2b> return syscall(SYS_env_set_pgfault_upcall, 1, envid, (uint32_t) upcall, 0, 0, 0); } 801784: 8d 65 f4 lea -0xc(%ebp),%esp 801787: 5b pop %ebx 801788: 5e pop %esi 801789: 5f pop %edi 80178a: 5d pop %ebp 80178b: c3 ret panic("syscall %d returned %d (> 0)", num, ret); 80178c: 83 ec 0c sub $0xc,%esp 80178f: 50 push %eax 801790: 6a 0a push $0xa 801792: 68 af 37 80 00 push $0x8037af 801797: 6a 23 push $0x23 801799: 68 cc 37 80 00 push $0x8037cc 80179e: e8 90 f2 ff ff call 800a33 <_panic> 008017a3 <sys_ipc_try_send>: int sys_ipc_try_send(envid_t envid, uint32_t value, void *srcva, int perm) { 8017a3: 55 push %ebp 8017a4: 89 e5 mov %esp,%ebp 8017a6: 57 push %edi 8017a7: 56 push %esi 8017a8: 53 push %ebx asm volatile("int %1\n" //执行int T_SYSCALL指令 8017a9: 8b 55 08 mov 0x8(%ebp),%edx 8017ac: 8b 4d 0c mov 0xc(%ebp),%ecx 8017af: b8 0c 00 00 00 mov $0xc,%eax 8017b4: be 00 00 00 00 mov $0x0,%esi 8017b9: 8b 5d 10 mov 0x10(%ebp),%ebx 8017bc: 8b 7d 14 mov 0x14(%ebp),%edi 8017bf: cd 30 int $0x30 return syscall(SYS_ipc_try_send, 0, envid, value, (uint32_t) srcva, perm, 0); } 8017c1: 5b pop %ebx 8017c2: 5e pop %esi 8017c3: 5f pop %edi 8017c4: 5d pop %ebp 8017c5: c3 ret 008017c6 <sys_ipc_recv>: int sys_ipc_recv(void *dstva) { 8017c6: 55 push %ebp 8017c7: 89 e5 mov %esp,%ebp 8017c9: 57 push %edi 8017ca: 56 push %esi 8017cb: 53 push %ebx 8017cc: 83 ec 0c sub $0xc,%esp asm volatile("int %1\n" //执行int T_SYSCALL指令 8017cf: b9 00 00 00 00 mov $0x0,%ecx 8017d4: 8b 55 08 mov 0x8(%ebp),%edx 8017d7: b8 0d 00 00 00 mov $0xd,%eax 8017dc: 89 cb mov %ecx,%ebx 8017de: 89 cf mov %ecx,%edi 8017e0: 89 ce mov %ecx,%esi 8017e2: cd 30 int $0x30 if(check && ret > 0) 8017e4: 85 c0 test %eax,%eax 8017e6: 7f 08 jg 8017f0 <sys_ipc_recv+0x2a> return syscall(SYS_ipc_recv, 1, (uint32_t)dstva, 0, 0, 0, 0); } 8017e8: 8d 65 f4 lea -0xc(%ebp),%esp 8017eb: 5b pop %ebx 8017ec: 5e pop %esi 8017ed: 5f pop %edi 8017ee: 5d pop %ebp 8017ef: c3 ret panic("syscall %d returned %d (> 0)", num, ret); 8017f0: 83 ec 0c sub $0xc,%esp 8017f3: 50 push %eax 8017f4: 6a 0d push $0xd 8017f6: 68 af 37 80 00 push $0x8037af 8017fb: 6a 23 push $0x23 8017fd: 68 cc 37 80 00 push $0x8037cc 801802: e8 2c f2 ff ff call 800a33 <_panic> 00801807 <pgfault>: // Custom page fault handler - if faulting page is copy-on-write, // map in our own private writable copy. // static void pgfault(struct UTrapframe *utf) { 801807: 55 push %ebp 801808: 89 e5 mov %esp,%ebp 80180a: 53 push %ebx 80180b: 83 ec 04 sub $0x4,%esp 80180e: 8b 45 08 mov 0x8(%ebp),%eax void *addr = (void *) utf->utf_fault_va; 801811: 8b 18 mov (%eax),%ebx // Hint: // Use the read-only page table mappings at uvpt // (see <inc/memlayout.h>). // LAB 4: Your code here. if (!((err & FEC_WR) && (uvpt[PGNUM(addr)] & PTE_COW))) { //只有因为写操作写时拷贝的地址这中情况,才可以抢救。否则一律panic 801813: f6 40 04 02 testb $0x2,0x4(%eax) 801817: 74 74 je 80188d <pgfault+0x86> 801819: 89 d8 mov %ebx,%eax 80181b: c1 e8 0c shr $0xc,%eax 80181e: 8b 04 85 00 00 40 ef mov -0x10c00000(,%eax,4),%eax 801825: f6 c4 08 test $0x8,%ah 801828: 74 63 je 80188d <pgfault+0x86> // page to the old page's address. // Hint: // You should make three system calls. // LAB 4: Your code here. addr = ROUNDDOWN(addr, PGSIZE); 80182a: 81 e3 00 f0 ff ff and $0xfffff000,%ebx if ((r = sys_page_map(0, addr, 0, PFTEMP, PTE_U|PTE_P)) < 0) //将当前进程PFTEMP也映射到当前进程addr指向的物理页 801830: 83 ec 0c sub $0xc,%esp 801833: 6a 05 push $0x5 801835: 68 00 f0 7f 00 push $0x7ff000 80183a: 6a 00 push $0x0 80183c: 53 push %ebx 80183d: 6a 00 push $0x0 80183f: e8 15 fe ff ff call 801659 <sys_page_map> 801844: 83 c4 20 add $0x20,%esp 801847: 85 c0 test %eax,%eax 801849: 78 56 js 8018a1 <pgfault+0x9a> panic("sys_page_map: %e", r); if ((r = sys_page_alloc(0, addr, PTE_P|PTE_U|PTE_W)) < 0) //令当前进程addr指向新分配的物理页 80184b: 83 ec 04 sub $0x4,%esp 80184e: 6a 07 push $0x7 801850: 53 push %ebx 801851: 6a 00 push $0x0 801853: e8 be fd ff ff call 801616 <sys_page_alloc> 801858: 83 c4 10 add $0x10,%esp 80185b: 85 c0 test %eax,%eax 80185d: 78 54 js 8018b3 <pgfault+0xac> panic("sys_page_alloc: %e", r); memmove(addr, PFTEMP, PGSIZE); //将PFTEMP指向的物理页拷贝到addr指向的物理页 80185f: 83 ec 04 sub $0x4,%esp 801862: 68 00 10 00 00 push $0x1000 801867: 68 00 f0 7f 00 push $0x7ff000 80186c: 53 push %ebx 80186d: e8 39 fb ff ff call 8013ab <memmove> if ((r = sys_page_unmap(0, PFTEMP)) < 0) //解除当前进程PFTEMP映射 801872: 83 c4 08 add $0x8,%esp 801875: 68 00 f0 7f 00 push $0x7ff000 80187a: 6a 00 push $0x0 80187c: e8 1a fe ff ff call 80169b <sys_page_unmap> 801881: 83 c4 10 add $0x10,%esp 801884: 85 c0 test %eax,%eax 801886: 78 3d js 8018c5 <pgfault+0xbe> panic("sys_page_unmap: %e", r); } 801888: 8b 5d fc mov -0x4(%ebp),%ebx 80188b: c9 leave 80188c: c3 ret panic("pgfault():not cow"); 80188d: 83 ec 04 sub $0x4,%esp 801890: 68 da 37 80 00 push $0x8037da 801895: 6a 1d push $0x1d 801897: 68 ec 37 80 00 push $0x8037ec 80189c: e8 92 f1 ff ff call 800a33 <_panic> panic("sys_page_map: %e", r); 8018a1: 50 push %eax 8018a2: 68 f7 37 80 00 push $0x8037f7 8018a7: 6a 2a push $0x2a 8018a9: 68 ec 37 80 00 push $0x8037ec 8018ae: e8 80 f1 ff ff call 800a33 <_panic> panic("sys_page_alloc: %e", r); 8018b3: 50 push %eax 8018b4: 68 08 38 80 00 push $0x803808 8018b9: 6a 2c push $0x2c 8018bb: 68 ec 37 80 00 push $0x8037ec 8018c0: e8 6e f1 ff ff call 800a33 <_panic> panic("sys_page_unmap: %e", r); 8018c5: 50 push %eax 8018c6: 68 1b 38 80 00 push $0x80381b 8018cb: 6a 2f push $0x2f 8018cd: 68 ec 37 80 00 push $0x8037ec 8018d2: e8 5c f1 ff ff call 800a33 <_panic> 008018d7 <fork>: // Neither user exception stack should ever be marked copy-on-write, // so you must allocate a new page for the child's user exception stack. // envid_t fork(void) { 8018d7: 55 push %ebp 8018d8: 89 e5 mov %esp,%ebp 8018da: 57 push %edi 8018db: 56 push %esi 8018dc: 53 push %ebx 8018dd: 83 ec 28 sub $0x28,%esp // LAB 4: Your code here. extern void _pgfault_upcall(void); set_pgfault_handler(pgfault); //设置缺页处理函数 8018e0: 68 07 18 80 00 push $0x801807 8018e5: e8 86 15 00 00 call 802e70 <set_pgfault_handler> // This must be inlined. Exercise for reader: why? static inline envid_t __attribute__((always_inline)) sys_exofork(void) { envid_t ret; asm volatile("int %2" 8018ea: b8 07 00 00 00 mov $0x7,%eax 8018ef: cd 30 int $0x30 8018f1: 89 45 e4 mov %eax,-0x1c(%ebp) envid_t envid = sys_exofork(); //系统调用,只是简单创建一个Env结构,复制当前用户环境寄存器状态,UTOP以下的页目录还没有建立 if (envid == 0) { //子进程将走这个逻辑 8018f4: 83 c4 10 add $0x10,%esp 8018f7: 85 c0 test %eax,%eax 8018f9: 74 12 je 80190d <fork+0x36> 8018fb: 89 c7 mov %eax,%edi thisenv = &envs[ENVX(sys_getenvid())]; return 0; } if (envid < 0) { 8018fd: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp) 801901: 78 26 js 801929 <fork+0x52> panic("sys_exofork: %e", envid); } uint32_t addr; for (addr = 0; addr < USTACKTOP; addr += PGSIZE) { 801903: bb 00 00 00 00 mov $0x0,%ebx 801908: e9 94 00 00 00 jmp 8019a1 <fork+0xca> thisenv = &envs[ENVX(sys_getenvid())]; 80190d: e8 c6 fc ff ff call 8015d8 <sys_getenvid> 801912: 25 ff 03 00 00 and $0x3ff,%eax 801917: 6b c0 7c imul $0x7c,%eax,%eax 80191a: 05 00 00 c0 ee add $0xeec00000,%eax 80191f: a3 24 54 80 00 mov %eax,0x805424 return 0; 801924: e9 51 01 00 00 jmp 801a7a <fork+0x1a3> panic("sys_exofork: %e", envid); 801929: ff 75 e4 pushl -0x1c(%ebp) 80192c: 68 2e 38 80 00 push $0x80382e 801931: 6a 6d push $0x6d 801933: 68 ec 37 80 00 push $0x8037ec 801938: e8 f6 f0 ff ff call 800a33 <_panic> sys_page_map(0, addr, envid, addr, PTE_SYSCALL); //对于表示为PTE_SHARE的页,拷贝映射关系,并且两个进程都有读写权限 80193d: 83 ec 0c sub $0xc,%esp 801940: 68 07 0e 00 00 push $0xe07 801945: 56 push %esi 801946: 57 push %edi 801947: 56 push %esi 801948: 6a 00 push $0x0 80194a: e8 0a fd ff ff call 801659 <sys_page_map> 80194f: 83 c4 20 add $0x20,%esp 801952: eb 3b jmp 80198f <fork+0xb8> if ((r = sys_page_map(0, addr, envid, addr, PTE_COW|PTE_U|PTE_P)) < 0) 801954: 83 ec 0c sub $0xc,%esp 801957: 68 05 08 00 00 push $0x805 80195c: 56 push %esi 80195d: 57 push %edi 80195e: 56 push %esi 80195f: 6a 00 push $0x0 801961: e8 f3 fc ff ff call 801659 <sys_page_map> 801966: 83 c4 20 add $0x20,%esp 801969: 85 c0 test %eax,%eax 80196b: 0f 88 a9 00 00 00 js 801a1a <fork+0x143> if ((r = sys_page_map(0, addr, 0, addr, PTE_COW|PTE_U|PTE_P)) < 0) 801971: 83 ec 0c sub $0xc,%esp 801974: 68 05 08 00 00 push $0x805 801979: 56 push %esi 80197a: 6a 00 push $0x0 80197c: 56 push %esi 80197d: 6a 00 push $0x0 80197f: e8 d5 fc ff ff call 801659 <sys_page_map> 801984: 83 c4 20 add $0x20,%esp 801987: 85 c0 test %eax,%eax 801989: 0f 88 9d 00 00 00 js 801a2c <fork+0x155> for (addr = 0; addr < USTACKTOP; addr += PGSIZE) { 80198f: 81 c3 00 10 00 00 add $0x1000,%ebx 801995: 81 fb 00 e0 bf ee cmp $0xeebfe000,%ebx 80199b: 0f 84 9d 00 00 00 je 801a3e <fork+0x167> if ((uvpd[PDX(addr)] & PTE_P) && (uvpt[PGNUM(addr)] & PTE_P) //为什么uvpt[pagenumber]能访问到第pagenumber项页表条目:https://pdos.csail.mit.edu/6.828/2018/labs/lab4/uvpt.html 8019a1: 89 d8 mov %ebx,%eax 8019a3: c1 e8 16 shr $0x16,%eax 8019a6: 8b 04 85 00 d0 7b ef mov -0x10843000(,%eax,4),%eax 8019ad: a8 01 test $0x1,%al 8019af: 74 de je 80198f <fork+0xb8> 8019b1: 89 d8 mov %ebx,%eax 8019b3: c1 e8 0c shr $0xc,%eax 8019b6: 8b 14 85 00 00 40 ef mov -0x10c00000(,%eax,4),%edx 8019bd: f6 c2 01 test $0x1,%dl 8019c0: 74 cd je 80198f <fork+0xb8> && (uvpt[PGNUM(addr)] & PTE_U)) { 8019c2: 8b 14 85 00 00 40 ef mov -0x10c00000(,%eax,4),%edx 8019c9: f6 c2 04 test $0x4,%dl 8019cc: 74 c1 je 80198f <fork+0xb8> void *addr = (void*) (pn * PGSIZE); 8019ce: 89 c6 mov %eax,%esi 8019d0: c1 e6 0c shl $0xc,%esi if (uvpt[pn] & PTE_SHARE) { 8019d3: 8b 14 85 00 00 40 ef mov -0x10c00000(,%eax,4),%edx 8019da: f6 c6 04 test $0x4,%dh 8019dd: 0f 85 5a ff ff ff jne 80193d <fork+0x66> } else if ((uvpt[pn] & PTE_W) || (uvpt[pn] & PTE_COW)) { //对于UTOP以下的可写的或者写时拷贝的页,拷贝映射关系的同时,需要同时标记当前进程和子进程的页表项为PTE_COW 8019e3: 8b 14 85 00 00 40 ef mov -0x10c00000(,%eax,4),%edx 8019ea: f6 c2 02 test $0x2,%dl 8019ed: 0f 85 61 ff ff ff jne 801954 <fork+0x7d> 8019f3: 8b 04 85 00 00 40 ef mov -0x10c00000(,%eax,4),%eax 8019fa: f6 c4 08 test $0x8,%ah 8019fd: 0f 85 51 ff ff ff jne 801954 <fork+0x7d> sys_page_map(0, addr, envid, addr, PTE_U|PTE_P); //对于只读的页,只需要拷贝映射关系即可 801a03: 83 ec 0c sub $0xc,%esp 801a06: 6a 05 push $0x5 801a08: 56 push %esi 801a09: 57 push %edi 801a0a: 56 push %esi 801a0b: 6a 00 push $0x0 801a0d: e8 47 fc ff ff call 801659 <sys_page_map> 801a12: 83 c4 20 add $0x20,%esp 801a15: e9 75 ff ff ff jmp 80198f <fork+0xb8> panic("sys_page_map:%e", r); 801a1a: 50 push %eax 801a1b: 68 3e 38 80 00 push $0x80383e 801a20: 6a 48 push $0x48 801a22: 68 ec 37 80 00 push $0x8037ec 801a27: e8 07 f0 ff ff call 800a33 <_panic> panic("sys_page_map:%e", r); 801a2c: 50 push %eax 801a2d: 68 3e 38 80 00 push $0x80383e 801a32: 6a 4a push $0x4a 801a34: 68 ec 37 80 00 push $0x8037ec 801a39: e8 f5 ef ff ff call 800a33 <_panic> duppage(envid, PGNUM(addr)); //拷贝当前进程映射关系到子进程 } } int r; if ((r = sys_page_alloc(envid, (void *)(UXSTACKTOP-PGSIZE), PTE_P | PTE_W | PTE_U)) < 0) //为子进程分配异常栈 801a3e: 83 ec 04 sub $0x4,%esp 801a41: 6a 07 push $0x7 801a43: 68 00 f0 bf ee push $0xeebff000 801a48: ff 75 e4 pushl -0x1c(%ebp) 801a4b: e8 c6 fb ff ff call 801616 <sys_page_alloc> 801a50: 83 c4 10 add $0x10,%esp 801a53: 85 c0 test %eax,%eax 801a55: 78 2e js 801a85 <fork+0x1ae> panic("sys_page_alloc: %e", r); sys_env_set_pgfault_upcall(envid, _pgfault_upcall); //为子进程设置_pgfault_upcall 801a57: 83 ec 08 sub $0x8,%esp 801a5a: 68 c9 2e 80 00 push $0x802ec9 801a5f: 8b 7d e4 mov -0x1c(%ebp),%edi 801a62: 57 push %edi 801a63: e8 f9 fc ff ff call 801761 <sys_env_set_pgfault_upcall> if ((r = sys_env_set_status(envid, ENV_RUNNABLE)) < 0) //设置子进程为ENV_RUNNABLE状态 801a68: 83 c4 08 add $0x8,%esp 801a6b: 6a 02 push $0x2 801a6d: 57 push %edi 801a6e: e8 6a fc ff ff call 8016dd <sys_env_set_status> 801a73: 83 c4 10 add $0x10,%esp 801a76: 85 c0 test %eax,%eax 801a78: 78 1d js 801a97 <fork+0x1c0> panic("sys_env_set_status: %e", r); return envid; } 801a7a: 8b 45 e4 mov -0x1c(%ebp),%eax 801a7d: 8d 65 f4 lea -0xc(%ebp),%esp 801a80: 5b pop %ebx 801a81: 5e pop %esi 801a82: 5f pop %edi 801a83: 5d pop %ebp 801a84: c3 ret panic("sys_page_alloc: %e", r); 801a85: 50 push %eax 801a86: 68 08 38 80 00 push $0x803808 801a8b: 6a 79 push $0x79 801a8d: 68 ec 37 80 00 push $0x8037ec 801a92: e8 9c ef ff ff call 800a33 <_panic> panic("sys_env_set_status: %e", r); 801a97: 50 push %eax 801a98: 68 50 38 80 00 push $0x803850 801a9d: 6a 7d push $0x7d 801a9f: 68 ec 37 80 00 push $0x8037ec 801aa4: e8 8a ef ff ff call 800a33 <_panic> 00801aa9 <sfork>: // Challenge! int sfork(void) { 801aa9: 55 push %ebp 801aaa: 89 e5 mov %esp,%ebp 801aac: 83 ec 0c sub $0xc,%esp panic("sfork not implemented"); 801aaf: 68 67 38 80 00 push $0x803867 801ab4: 68 85 00 00 00 push $0x85 801ab9: 68 ec 37 80 00 push $0x8037ec 801abe: e8 70 ef ff ff call 800a33 <_panic> 00801ac3 <argstart>: #include <inc/args.h> #include <inc/string.h> void argstart(int *argc, char **argv, struct Argstate *args) { 801ac3: 55 push %ebp 801ac4: 89 e5 mov %esp,%ebp 801ac6: 8b 55 08 mov 0x8(%ebp),%edx 801ac9: 8b 4d 0c mov 0xc(%ebp),%ecx 801acc: 8b 45 10 mov 0x10(%ebp),%eax args->argc = argc; 801acf: 89 10 mov %edx,(%eax) args->argv = (const char **) argv; 801ad1: 89 48 04 mov %ecx,0x4(%eax) args->curarg = (*argc > 1 && argv ? "" : 0); 801ad4: 83 3a 01 cmpl $0x1,(%edx) 801ad7: 7e 09 jle 801ae2 <argstart+0x1f> 801ad9: ba 81 32 80 00 mov $0x803281,%edx 801ade: 85 c9 test %ecx,%ecx 801ae0: 75 05 jne 801ae7 <argstart+0x24> 801ae2: ba 00 00 00 00 mov $0x0,%edx 801ae7: 89 50 08 mov %edx,0x8(%eax) args->argvalue = 0; 801aea: c7 40 0c 00 00 00 00 movl $0x0,0xc(%eax) } 801af1: 5d pop %ebp 801af2: c3 ret 00801af3 <argnext>: int argnext(struct Argstate *args) { 801af3: 55 push %ebp 801af4: 89 e5 mov %esp,%ebp 801af6: 53 push %ebx 801af7: 83 ec 04 sub $0x4,%esp 801afa: 8b 5d 08 mov 0x8(%ebp),%ebx int arg; args->argvalue = 0; 801afd: c7 43 0c 00 00 00 00 movl $0x0,0xc(%ebx) // Done processing arguments if args->curarg == 0 if (args->curarg == 0) 801b04: 8b 43 08 mov 0x8(%ebx),%eax 801b07: 85 c0 test %eax,%eax 801b09: 74 72 je 801b7d <argnext+0x8a> return -1; if (!*args->curarg) { 801b0b: 80 38 00 cmpb $0x0,(%eax) 801b0e: 75 48 jne 801b58 <argnext+0x65> // Need to process the next argument // Check for end of argument list if (*args->argc == 1 801b10: 8b 0b mov (%ebx),%ecx 801b12: 83 39 01 cmpl $0x1,(%ecx) 801b15: 74 58 je 801b6f <argnext+0x7c> || args->argv[1][0] != '-' 801b17: 8b 53 04 mov 0x4(%ebx),%edx 801b1a: 8b 42 04 mov 0x4(%edx),%eax 801b1d: 80 38 2d cmpb $0x2d,(%eax) 801b20: 75 4d jne 801b6f <argnext+0x7c> || args->argv[1][1] == '\0') 801b22: 80 78 01 00 cmpb $0x0,0x1(%eax) 801b26: 74 47 je 801b6f <argnext+0x7c> goto endofargs; // Shift arguments down one args->curarg = args->argv[1] + 1; 801b28: 83 c0 01 add $0x1,%eax 801b2b: 89 43 08 mov %eax,0x8(%ebx) memmove(args->argv + 1, args->argv + 2, sizeof(const char *) * (*args->argc - 1)); 801b2e: 83 ec 04 sub $0x4,%esp 801b31: 8b 01 mov (%ecx),%eax 801b33: 8d 04 85 fc ff ff ff lea -0x4(,%eax,4),%eax 801b3a: 50 push %eax 801b3b: 8d 42 08 lea 0x8(%edx),%eax 801b3e: 50 push %eax 801b3f: 83 c2 04 add $0x4,%edx 801b42: 52 push %edx 801b43: e8 63 f8 ff ff call 8013ab <memmove> (*args->argc)--; 801b48: 8b 03 mov (%ebx),%eax 801b4a: 83 28 01 subl $0x1,(%eax) // Check for "--": end of argument list if (args->curarg[0] == '-' && args->curarg[1] == '\0') 801b4d: 8b 43 08 mov 0x8(%ebx),%eax 801b50: 83 c4 10 add $0x10,%esp 801b53: 80 38 2d cmpb $0x2d,(%eax) 801b56: 74 11 je 801b69 <argnext+0x76> goto endofargs; } arg = (unsigned char) *args->curarg; 801b58: 8b 53 08 mov 0x8(%ebx),%edx 801b5b: 0f b6 02 movzbl (%edx),%eax args->curarg++; 801b5e: 83 c2 01 add $0x1,%edx 801b61: 89 53 08 mov %edx,0x8(%ebx) return arg; endofargs: args->curarg = 0; return -1; } 801b64: 8b 5d fc mov -0x4(%ebp),%ebx 801b67: c9 leave 801b68: c3 ret if (args->curarg[0] == '-' && args->curarg[1] == '\0') 801b69: 80 78 01 00 cmpb $0x0,0x1(%eax) 801b6d: 75 e9 jne 801b58 <argnext+0x65> args->curarg = 0; 801b6f: c7 43 08 00 00 00 00 movl $0x0,0x8(%ebx) return -1; 801b76: b8 ff ff ff ff mov $0xffffffff,%eax 801b7b: eb e7 jmp 801b64 <argnext+0x71> return -1; 801b7d: b8 ff ff ff ff mov $0xffffffff,%eax 801b82: eb e0 jmp 801b64 <argnext+0x71> 00801b84 <argnextvalue>: return (char*) (args->argvalue ? args->argvalue : argnextvalue(args)); } char * argnextvalue(struct Argstate *args) { 801b84: 55 push %ebp 801b85: 89 e5 mov %esp,%ebp 801b87: 53 push %ebx 801b88: 83 ec 04 sub $0x4,%esp 801b8b: 8b 5d 08 mov 0x8(%ebp),%ebx if (!args->curarg) 801b8e: 8b 43 08 mov 0x8(%ebx),%eax 801b91: 85 c0 test %eax,%eax 801b93: 74 5b je 801bf0 <argnextvalue+0x6c> return 0; if (*args->curarg) { 801b95: 80 38 00 cmpb $0x0,(%eax) 801b98: 74 12 je 801bac <argnextvalue+0x28> args->argvalue = args->curarg; 801b9a: 89 43 0c mov %eax,0xc(%ebx) args->curarg = ""; 801b9d: c7 43 08 81 32 80 00 movl $0x803281,0x8(%ebx) (*args->argc)--; } else { args->argvalue = 0; args->curarg = 0; } return (char*) args->argvalue; 801ba4: 8b 43 0c mov 0xc(%ebx),%eax } 801ba7: 8b 5d fc mov -0x4(%ebp),%ebx 801baa: c9 leave 801bab: c3 ret } else if (*args->argc > 1) { 801bac: 8b 13 mov (%ebx),%edx 801bae: 83 3a 01 cmpl $0x1,(%edx) 801bb1: 7f 10 jg 801bc3 <argnextvalue+0x3f> args->argvalue = 0; 801bb3: c7 43 0c 00 00 00 00 movl $0x0,0xc(%ebx) args->curarg = 0; 801bba: c7 43 08 00 00 00 00 movl $0x0,0x8(%ebx) 801bc1: eb e1 jmp 801ba4 <argnextvalue+0x20> args->argvalue = args->argv[1]; 801bc3: 8b 43 04 mov 0x4(%ebx),%eax 801bc6: 8b 48 04 mov 0x4(%eax),%ecx 801bc9: 89 4b 0c mov %ecx,0xc(%ebx) memmove(args->argv + 1, args->argv + 2, sizeof(const char *) * (*args->argc - 1)); 801bcc: 83 ec 04 sub $0x4,%esp 801bcf: 8b 12 mov (%edx),%edx 801bd1: 8d 14 95 fc ff ff ff lea -0x4(,%edx,4),%edx 801bd8: 52 push %edx 801bd9: 8d 50 08 lea 0x8(%eax),%edx 801bdc: 52 push %edx 801bdd: 83 c0 04 add $0x4,%eax 801be0: 50 push %eax 801be1: e8 c5 f7 ff ff call 8013ab <memmove> (*args->argc)--; 801be6: 8b 03 mov (%ebx),%eax 801be8: 83 28 01 subl $0x1,(%eax) 801beb: 83 c4 10 add $0x10,%esp 801bee: eb b4 jmp 801ba4 <argnextvalue+0x20> return 0; 801bf0: b8 00 00 00 00 mov $0x0,%eax 801bf5: eb b0 jmp 801ba7 <argnextvalue+0x23> 00801bf7 <argvalue>: { 801bf7: 55 push %ebp 801bf8: 89 e5 mov %esp,%ebp 801bfa: 83 ec 08 sub $0x8,%esp 801bfd: 8b 55 08 mov 0x8(%ebp),%edx return (char*) (args->argvalue ? args->argvalue : argnextvalue(args)); 801c00: 8b 42 0c mov 0xc(%edx),%eax 801c03: 85 c0 test %eax,%eax 801c05: 74 02 je 801c09 <argvalue+0x12> } 801c07: c9 leave 801c08: c3 ret return (char*) (args->argvalue ? args->argvalue : argnextvalue(args)); 801c09: 83 ec 0c sub $0xc,%esp 801c0c: 52 push %edx 801c0d: e8 72 ff ff ff call 801b84 <argnextvalue> 801c12: 83 c4 10 add $0x10,%esp 801c15: eb f0 jmp 801c07 <argvalue+0x10> 00801c17 <fd2num>: // File descriptor manipulators // -------------------------------------------------------------- int fd2num(struct Fd *fd) { 801c17: 55 push %ebp 801c18: 89 e5 mov %esp,%ebp return ((uintptr_t) fd - FDTABLE) / PGSIZE; 801c1a: 8b 45 08 mov 0x8(%ebp),%eax 801c1d: 05 00 00 00 30 add $0x30000000,%eax 801c22: c1 e8 0c shr $0xc,%eax } 801c25: 5d pop %ebp 801c26: c3 ret 00801c27 <fd2data>: char* fd2data(struct Fd *fd) { 801c27: 55 push %ebp 801c28: 89 e5 mov %esp,%ebp return ((uintptr_t) fd - FDTABLE) / PGSIZE; 801c2a: 8b 45 08 mov 0x8(%ebp),%eax 801c2d: 05 00 00 00 30 add $0x30000000,%eax return INDEX2DATA(fd2num(fd)); 801c32: 25 00 f0 ff ff and $0xfffff000,%eax 801c37: 2d 00 00 fe 2f sub $0x2ffe0000,%eax } 801c3c: 5d pop %ebp 801c3d: c3 ret 00801c3e <fd_alloc>: // Returns 0 on success, < 0 on error. Errors are: // -E_MAX_FD: no more file descriptors // On error, *fd_store is set to 0. int fd_alloc(struct Fd **fd_store) { 801c3e: 55 push %ebp 801c3f: 89 e5 mov %esp,%ebp 801c41: 8b 4d 08 mov 0x8(%ebp),%ecx 801c44: b8 00 00 00 d0 mov $0xd0000000,%eax int i; struct Fd *fd; for (i = 0; i < MAXFD; i++) { fd = INDEX2FD(i); if ((uvpd[PDX(fd)] & PTE_P) == 0 || (uvpt[PGNUM(fd)] & PTE_P) == 0) { 801c49: 89 c2 mov %eax,%edx 801c4b: c1 ea 16 shr $0x16,%edx 801c4e: 8b 14 95 00 d0 7b ef mov -0x10843000(,%edx,4),%edx 801c55: f6 c2 01 test $0x1,%dl 801c58: 74 2a je 801c84 <fd_alloc+0x46> 801c5a: 89 c2 mov %eax,%edx 801c5c: c1 ea 0c shr $0xc,%edx 801c5f: 8b 14 95 00 00 40 ef mov -0x10c00000(,%edx,4),%edx 801c66: f6 c2 01 test $0x1,%dl 801c69: 74 19 je 801c84 <fd_alloc+0x46> 801c6b: 05 00 10 00 00 add $0x1000,%eax for (i = 0; i < MAXFD; i++) { 801c70: 3d 00 00 02 d0 cmp $0xd0020000,%eax 801c75: 75 d2 jne 801c49 <fd_alloc+0xb> *fd_store = fd; return 0; } } *fd_store = 0; 801c77: c7 01 00 00 00 00 movl $0x0,(%ecx) return -E_MAX_OPEN; 801c7d: b8 f6 ff ff ff mov $0xfffffff6,%eax 801c82: eb 07 jmp 801c8b <fd_alloc+0x4d> *fd_store = fd; 801c84: 89 01 mov %eax,(%ecx) return 0; 801c86: b8 00 00 00 00 mov $0x0,%eax } 801c8b: 5d pop %ebp 801c8c: c3 ret 00801c8d <fd_lookup>: // Returns 0 on success (the page is in range and mapped), < 0 on error. // Errors are: // -E_INVAL: fdnum was either not in range or not mapped. int fd_lookup(int fdnum, struct Fd **fd_store) { 801c8d: 55 push %ebp 801c8e: 89 e5 mov %esp,%ebp 801c90: 8b 45 08 mov 0x8(%ebp),%eax struct Fd *fd; if (fdnum < 0 || fdnum >= MAXFD) { 801c93: 83 f8 1f cmp $0x1f,%eax 801c96: 77 36 ja 801cce <fd_lookup+0x41> if (debug) cprintf("[%08x] bad fd %d\n", thisenv->env_id, fdnum); return -E_INVAL; } fd = INDEX2FD(fdnum); 801c98: c1 e0 0c shl $0xc,%eax 801c9b: 2d 00 00 00 30 sub $0x30000000,%eax if (!(uvpd[PDX(fd)] & PTE_P) || !(uvpt[PGNUM(fd)] & PTE_P)) { 801ca0: 89 c2 mov %eax,%edx 801ca2: c1 ea 16 shr $0x16,%edx 801ca5: 8b 14 95 00 d0 7b ef mov -0x10843000(,%edx,4),%edx 801cac: f6 c2 01 test $0x1,%dl 801caf: 74 24 je 801cd5 <fd_lookup+0x48> 801cb1: 89 c2 mov %eax,%edx 801cb3: c1 ea 0c shr $0xc,%edx 801cb6: 8b 14 95 00 00 40 ef mov -0x10c00000(,%edx,4),%edx 801cbd: f6 c2 01 test $0x1,%dl 801cc0: 74 1a je 801cdc <fd_lookup+0x4f> if (debug) cprintf("[%08x] closed fd %d\n", thisenv->env_id, fdnum); return -E_INVAL; } *fd_store = fd; 801cc2: 8b 55 0c mov 0xc(%ebp),%edx 801cc5: 89 02 mov %eax,(%edx) return 0; 801cc7: b8 00 00 00 00 mov $0x0,%eax } 801ccc: 5d pop %ebp 801ccd: c3 ret return -E_INVAL; 801cce: b8 fd ff ff ff mov $0xfffffffd,%eax 801cd3: eb f7 jmp 801ccc <fd_lookup+0x3f> return -E_INVAL; 801cd5: b8 fd ff ff ff mov $0xfffffffd,%eax 801cda: eb f0 jmp 801ccc <fd_lookup+0x3f> 801cdc: b8 fd ff ff ff mov $0xfffffffd,%eax 801ce1: eb e9 jmp 801ccc <fd_lookup+0x3f> 00801ce3 <dev_lookup>: 0 }; int dev_lookup(int dev_id, struct Dev **dev) { 801ce3: 55 push %ebp 801ce4: 89 e5 mov %esp,%ebp 801ce6: 83 ec 08 sub $0x8,%esp 801ce9: 8b 4d 08 mov 0x8(%ebp),%ecx 801cec: ba fc 38 80 00 mov $0x8038fc,%edx int i; for (i = 0; devtab[i]; i++) 801cf1: b8 20 40 80 00 mov $0x804020,%eax if (devtab[i]->dev_id == dev_id) { 801cf6: 39 08 cmp %ecx,(%eax) 801cf8: 74 33 je 801d2d <dev_lookup+0x4a> 801cfa: 83 c2 04 add $0x4,%edx for (i = 0; devtab[i]; i++) 801cfd: 8b 02 mov (%edx),%eax 801cff: 85 c0 test %eax,%eax 801d01: 75 f3 jne 801cf6 <dev_lookup+0x13> *dev = devtab[i]; return 0; } cprintf("[%08x] unknown device type %d\n", thisenv->env_id, dev_id); 801d03: a1 24 54 80 00 mov 0x805424,%eax 801d08: 8b 40 48 mov 0x48(%eax),%eax 801d0b: 83 ec 04 sub $0x4,%esp 801d0e: 51 push %ecx 801d0f: 50 push %eax 801d10: 68 80 38 80 00 push $0x803880 801d15: e8 f4 ed ff ff call 800b0e <cprintf> *dev = 0; 801d1a: 8b 45 0c mov 0xc(%ebp),%eax 801d1d: c7 00 00 00 00 00 movl $0x0,(%eax) return -E_INVAL; 801d23: 83 c4 10 add $0x10,%esp 801d26: b8 fd ff ff ff mov $0xfffffffd,%eax } 801d2b: c9 leave 801d2c: c3 ret *dev = devtab[i]; 801d2d: 8b 4d 0c mov 0xc(%ebp),%ecx 801d30: 89 01 mov %eax,(%ecx) return 0; 801d32: b8 00 00 00 00 mov $0x0,%eax 801d37: eb f2 jmp 801d2b <dev_lookup+0x48> 00801d39 <fd_close>: { 801d39: 55 push %ebp 801d3a: 89 e5 mov %esp,%ebp 801d3c: 57 push %edi 801d3d: 56 push %esi 801d3e: 53 push %ebx 801d3f: 83 ec 1c sub $0x1c,%esp 801d42: 8b 75 08 mov 0x8(%ebp),%esi 801d45: 8b 7d 0c mov 0xc(%ebp),%edi if ((r = fd_lookup(fd2num(fd), &fd2)) < 0 801d48: 8d 45 e4 lea -0x1c(%ebp),%eax 801d4b: 50 push %eax return ((uintptr_t) fd - FDTABLE) / PGSIZE; 801d4c: 8d 86 00 00 00 30 lea 0x30000000(%esi),%eax 801d52: c1 e8 0c shr $0xc,%eax if ((r = fd_lookup(fd2num(fd), &fd2)) < 0 801d55: 50 push %eax 801d56: e8 32 ff ff ff call 801c8d <fd_lookup> 801d5b: 89 c3 mov %eax,%ebx 801d5d: 83 c4 08 add $0x8,%esp 801d60: 85 c0 test %eax,%eax 801d62: 78 05 js 801d69 <fd_close+0x30> || fd != fd2) 801d64: 39 75 e4 cmp %esi,-0x1c(%ebp) 801d67: 74 16 je 801d7f <fd_close+0x46> return (must_exist ? r : 0); 801d69: 89 f8 mov %edi,%eax 801d6b: 84 c0 test %al,%al 801d6d: b8 00 00 00 00 mov $0x0,%eax 801d72: 0f 44 d8 cmove %eax,%ebx } 801d75: 89 d8 mov %ebx,%eax 801d77: 8d 65 f4 lea -0xc(%ebp),%esp 801d7a: 5b pop %ebx 801d7b: 5e pop %esi 801d7c: 5f pop %edi 801d7d: 5d pop %ebp 801d7e: c3 ret if ((r = dev_lookup(fd->fd_dev_id, &dev)) >= 0) { 801d7f: 83 ec 08 sub $0x8,%esp 801d82: 8d 45 e0 lea -0x20(%ebp),%eax 801d85: 50 push %eax 801d86: ff 36 pushl (%esi) 801d88: e8 56 ff ff ff call 801ce3 <dev_lookup> 801d8d: 89 c3 mov %eax,%ebx 801d8f: 83 c4 10 add $0x10,%esp 801d92: 85 c0 test %eax,%eax 801d94: 78 15 js 801dab <fd_close+0x72> if (dev->dev_close) 801d96: 8b 45 e0 mov -0x20(%ebp),%eax 801d99: 8b 40 10 mov 0x10(%eax),%eax 801d9c: 85 c0 test %eax,%eax 801d9e: 74 1b je 801dbb <fd_close+0x82> r = (*dev->dev_close)(fd); 801da0: 83 ec 0c sub $0xc,%esp 801da3: 56 push %esi 801da4: ff d0 call *%eax 801da6: 89 c3 mov %eax,%ebx 801da8: 83 c4 10 add $0x10,%esp (void) sys_page_unmap(0, fd); 801dab: 83 ec 08 sub $0x8,%esp 801dae: 56 push %esi 801daf: 6a 00 push $0x0 801db1: e8 e5 f8 ff ff call 80169b <sys_page_unmap> return r; 801db6: 83 c4 10 add $0x10,%esp 801db9: eb ba jmp 801d75 <fd_close+0x3c> r = 0; 801dbb: bb 00 00 00 00 mov $0x0,%ebx 801dc0: eb e9 jmp 801dab <fd_close+0x72> 00801dc2 <close>: int close(int fdnum) { 801dc2: 55 push %ebp 801dc3: 89 e5 mov %esp,%ebp 801dc5: 83 ec 18 sub $0x18,%esp struct Fd *fd; int r; if ((r = fd_lookup(fdnum, &fd)) < 0) 801dc8: 8d 45 f4 lea -0xc(%ebp),%eax 801dcb: 50 push %eax 801dcc: ff 75 08 pushl 0x8(%ebp) 801dcf: e8 b9 fe ff ff call 801c8d <fd_lookup> 801dd4: 83 c4 08 add $0x8,%esp 801dd7: 85 c0 test %eax,%eax 801dd9: 78 10 js 801deb <close+0x29> return r; else return fd_close(fd, 1); 801ddb: 83 ec 08 sub $0x8,%esp 801dde: 6a 01 push $0x1 801de0: ff 75 f4 pushl -0xc(%ebp) 801de3: e8 51 ff ff ff call 801d39 <fd_close> 801de8: 83 c4 10 add $0x10,%esp } 801deb: c9 leave 801dec: c3 ret 00801ded <close_all>: void close_all(void) { 801ded: 55 push %ebp 801dee: 89 e5 mov %esp,%ebp 801df0: 53 push %ebx 801df1: 83 ec 04 sub $0x4,%esp int i; for (i = 0; i < MAXFD; i++) 801df4: bb 00 00 00 00 mov $0x0,%ebx close(i); 801df9: 83 ec 0c sub $0xc,%esp 801dfc: 53 push %ebx 801dfd: e8 c0 ff ff ff call 801dc2 <close> for (i = 0; i < MAXFD; i++) 801e02: 83 c3 01 add $0x1,%ebx 801e05: 83 c4 10 add $0x10,%esp 801e08: 83 fb 20 cmp $0x20,%ebx 801e0b: 75 ec jne 801df9 <close_all+0xc> } 801e0d: 8b 5d fc mov -0x4(%ebp),%ebx 801e10: c9 leave 801e11: c3 ret 00801e12 <dup>: // file and the file offset of the other. // Closes any previously open file descriptor at 'newfdnum'. // This is implemented using virtual memory tricks (of course!). int dup(int oldfdnum, int newfdnum) { 801e12: 55 push %ebp 801e13: 89 e5 mov %esp,%ebp 801e15: 57 push %edi 801e16: 56 push %esi 801e17: 53 push %ebx 801e18: 83 ec 1c sub $0x1c,%esp int r; char *ova, *nva; pte_t pte; struct Fd *oldfd, *newfd; if ((r = fd_lookup(oldfdnum, &oldfd)) < 0) 801e1b: 8d 45 e4 lea -0x1c(%ebp),%eax 801e1e: 50 push %eax 801e1f: ff 75 08 pushl 0x8(%ebp) 801e22: e8 66 fe ff ff call 801c8d <fd_lookup> 801e27: 89 c3 mov %eax,%ebx 801e29: 83 c4 08 add $0x8,%esp 801e2c: 85 c0 test %eax,%eax 801e2e: 0f 88 81 00 00 00 js 801eb5 <dup+0xa3> return r; close(newfdnum); 801e34: 83 ec 0c sub $0xc,%esp 801e37: ff 75 0c pushl 0xc(%ebp) 801e3a: e8 83 ff ff ff call 801dc2 <close> newfd = INDEX2FD(newfdnum); 801e3f: 8b 75 0c mov 0xc(%ebp),%esi 801e42: c1 e6 0c shl $0xc,%esi 801e45: 81 ee 00 00 00 30 sub $0x30000000,%esi ova = fd2data(oldfd); 801e4b: 83 c4 04 add $0x4,%esp 801e4e: ff 75 e4 pushl -0x1c(%ebp) 801e51: e8 d1 fd ff ff call 801c27 <fd2data> 801e56: 89 c3 mov %eax,%ebx nva = fd2data(newfd); 801e58: 89 34 24 mov %esi,(%esp) 801e5b: e8 c7 fd ff ff call 801c27 <fd2data> 801e60: 83 c4 10 add $0x10,%esp 801e63: 89 c7 mov %eax,%edi if ((uvpd[PDX(ova)] & PTE_P) && (uvpt[PGNUM(ova)] & PTE_P)) 801e65: 89 d8 mov %ebx,%eax 801e67: c1 e8 16 shr $0x16,%eax 801e6a: 8b 04 85 00 d0 7b ef mov -0x10843000(,%eax,4),%eax 801e71: a8 01 test $0x1,%al 801e73: 74 11 je 801e86 <dup+0x74> 801e75: 89 d8 mov %ebx,%eax 801e77: c1 e8 0c shr $0xc,%eax 801e7a: 8b 14 85 00 00 40 ef mov -0x10c00000(,%eax,4),%edx 801e81: f6 c2 01 test $0x1,%dl 801e84: 75 39 jne 801ebf <dup+0xad> if ((r = sys_page_map(0, ova, 0, nva, uvpt[PGNUM(ova)] & PTE_SYSCALL)) < 0) goto err; if ((r = sys_page_map(0, oldfd, 0, newfd, uvpt[PGNUM(oldfd)] & PTE_SYSCALL)) < 0) 801e86: 8b 55 e4 mov -0x1c(%ebp),%edx 801e89: 89 d0 mov %edx,%eax 801e8b: c1 e8 0c shr $0xc,%eax 801e8e: 8b 04 85 00 00 40 ef mov -0x10c00000(,%eax,4),%eax 801e95: 83 ec 0c sub $0xc,%esp 801e98: 25 07 0e 00 00 and $0xe07,%eax 801e9d: 50 push %eax 801e9e: 56 push %esi 801e9f: 6a 00 push $0x0 801ea1: 52 push %edx 801ea2: 6a 00 push $0x0 801ea4: e8 b0 f7 ff ff call 801659 <sys_page_map> 801ea9: 89 c3 mov %eax,%ebx 801eab: 83 c4 20 add $0x20,%esp 801eae: 85 c0 test %eax,%eax 801eb0: 78 31 js 801ee3 <dup+0xd1> goto err; return newfdnum; 801eb2: 8b 5d 0c mov 0xc(%ebp),%ebx err: sys_page_unmap(0, newfd); sys_page_unmap(0, nva); return r; } 801eb5: 89 d8 mov %ebx,%eax 801eb7: 8d 65 f4 lea -0xc(%ebp),%esp 801eba: 5b pop %ebx 801ebb: 5e pop %esi 801ebc: 5f pop %edi 801ebd: 5d pop %ebp 801ebe: c3 ret if ((r = sys_page_map(0, ova, 0, nva, uvpt[PGNUM(ova)] & PTE_SYSCALL)) < 0) 801ebf: 8b 04 85 00 00 40 ef mov -0x10c00000(,%eax,4),%eax 801ec6: 83 ec 0c sub $0xc,%esp 801ec9: 25 07 0e 00 00 and $0xe07,%eax 801ece: 50 push %eax 801ecf: 57 push %edi 801ed0: 6a 00 push $0x0 801ed2: 53 push %ebx 801ed3: 6a 00 push $0x0 801ed5: e8 7f f7 ff ff call 801659 <sys_page_map> 801eda: 89 c3 mov %eax,%ebx 801edc: 83 c4 20 add $0x20,%esp 801edf: 85 c0 test %eax,%eax 801ee1: 79 a3 jns 801e86 <dup+0x74> sys_page_unmap(0, newfd); 801ee3: 83 ec 08 sub $0x8,%esp 801ee6: 56 push %esi 801ee7: 6a 00 push $0x0 801ee9: e8 ad f7 ff ff call 80169b <sys_page_unmap> sys_page_unmap(0, nva); 801eee: 83 c4 08 add $0x8,%esp 801ef1: 57 push %edi 801ef2: 6a 00 push $0x0 801ef4: e8 a2 f7 ff ff call 80169b <sys_page_unmap> return r; 801ef9: 83 c4 10 add $0x10,%esp 801efc: eb b7 jmp 801eb5 <dup+0xa3> 00801efe <read>: ssize_t read(int fdnum, void *buf, size_t n) { 801efe: 55 push %ebp 801eff: 89 e5 mov %esp,%ebp 801f01: 53 push %ebx 801f02: 83 ec 14 sub $0x14,%esp 801f05: 8b 5d 08 mov 0x8(%ebp),%ebx int r; struct Dev *dev; struct Fd *fd; if ((r = fd_lookup(fdnum, &fd)) < 0 801f08: 8d 45 f0 lea -0x10(%ebp),%eax 801f0b: 50 push %eax 801f0c: 53 push %ebx 801f0d: e8 7b fd ff ff call 801c8d <fd_lookup> 801f12: 83 c4 08 add $0x8,%esp 801f15: 85 c0 test %eax,%eax 801f17: 78 3f js 801f58 <read+0x5a> || (r = dev_lookup(fd->fd_dev_id, &dev)) < 0) 801f19: 83 ec 08 sub $0x8,%esp 801f1c: 8d 45 f4 lea -0xc(%ebp),%eax 801f1f: 50 push %eax 801f20: 8b 45 f0 mov -0x10(%ebp),%eax 801f23: ff 30 pushl (%eax) 801f25: e8 b9 fd ff ff call 801ce3 <dev_lookup> 801f2a: 83 c4 10 add $0x10,%esp 801f2d: 85 c0 test %eax,%eax 801f2f: 78 27 js 801f58 <read+0x5a> return r; if ((fd->fd_omode & O_ACCMODE) == O_WRONLY) { 801f31: 8b 55 f0 mov -0x10(%ebp),%edx 801f34: 8b 42 08 mov 0x8(%edx),%eax 801f37: 83 e0 03 and $0x3,%eax 801f3a: 83 f8 01 cmp $0x1,%eax 801f3d: 74 1e je 801f5d <read+0x5f> cprintf("[%08x] read %d -- bad mode\n", thisenv->env_id, fdnum); return -E_INVAL; } if (!dev->dev_read) 801f3f: 8b 45 f4 mov -0xc(%ebp),%eax 801f42: 8b 40 08 mov 0x8(%eax),%eax 801f45: 85 c0 test %eax,%eax 801f47: 74 35 je 801f7e <read+0x80> return -E_NOT_SUPP; return (*dev->dev_read)(fd, buf, n); 801f49: 83 ec 04 sub $0x4,%esp 801f4c: ff 75 10 pushl 0x10(%ebp) 801f4f: ff 75 0c pushl 0xc(%ebp) 801f52: 52 push %edx 801f53: ff d0 call *%eax 801f55: 83 c4 10 add $0x10,%esp } 801f58: 8b 5d fc mov -0x4(%ebp),%ebx 801f5b: c9 leave 801f5c: c3 ret cprintf("[%08x] read %d -- bad mode\n", thisenv->env_id, fdnum); 801f5d: a1 24 54 80 00 mov 0x805424,%eax 801f62: 8b 40 48 mov 0x48(%eax),%eax 801f65: 83 ec 04 sub $0x4,%esp 801f68: 53 push %ebx 801f69: 50 push %eax 801f6a: 68 c1 38 80 00 push $0x8038c1 801f6f: e8 9a eb ff ff call 800b0e <cprintf> return -E_INVAL; 801f74: 83 c4 10 add $0x10,%esp 801f77: b8 fd ff ff ff mov $0xfffffffd,%eax 801f7c: eb da jmp 801f58 <read+0x5a> return -E_NOT_SUPP; 801f7e: b8 f1 ff ff ff mov $0xfffffff1,%eax 801f83: eb d3 jmp 801f58 <read+0x5a> 00801f85 <readn>: ssize_t readn(int fdnum, void *buf, size_t n) { 801f85: 55 push %ebp 801f86: 89 e5 mov %esp,%ebp 801f88: 57 push %edi 801f89: 56 push %esi 801f8a: 53 push %ebx 801f8b: 83 ec 0c sub $0xc,%esp 801f8e: 8b 7d 08 mov 0x8(%ebp),%edi 801f91: 8b 75 10 mov 0x10(%ebp),%esi int m, tot; for (tot = 0; tot < n; tot += m) { 801f94: bb 00 00 00 00 mov $0x0,%ebx 801f99: 39 f3 cmp %esi,%ebx 801f9b: 73 25 jae 801fc2 <readn+0x3d> m = read(fdnum, (char*)buf + tot, n - tot); 801f9d: 83 ec 04 sub $0x4,%esp 801fa0: 89 f0 mov %esi,%eax 801fa2: 29 d8 sub %ebx,%eax 801fa4: 50 push %eax 801fa5: 89 d8 mov %ebx,%eax 801fa7: 03 45 0c add 0xc(%ebp),%eax 801faa: 50 push %eax 801fab: 57 push %edi 801fac: e8 4d ff ff ff call 801efe <read> if (m < 0) 801fb1: 83 c4 10 add $0x10,%esp 801fb4: 85 c0 test %eax,%eax 801fb6: 78 08 js 801fc0 <readn+0x3b> return m; if (m == 0) 801fb8: 85 c0 test %eax,%eax 801fba: 74 06 je 801fc2 <readn+0x3d> for (tot = 0; tot < n; tot += m) { 801fbc: 01 c3 add %eax,%ebx 801fbe: eb d9 jmp 801f99 <readn+0x14> m = read(fdnum, (char*)buf + tot, n - tot); 801fc0: 89 c3 mov %eax,%ebx break; } return tot; } 801fc2: 89 d8 mov %ebx,%eax 801fc4: 8d 65 f4 lea -0xc(%ebp),%esp 801fc7: 5b pop %ebx 801fc8: 5e pop %esi 801fc9: 5f pop %edi 801fca: 5d pop %ebp 801fcb: c3 ret 00801fcc <write>: ssize_t write(int fdnum, const void *buf, size_t n) { 801fcc: 55 push %ebp 801fcd: 89 e5 mov %esp,%ebp 801fcf: 53 push %ebx 801fd0: 83 ec 14 sub $0x14,%esp 801fd3: 8b 5d 08 mov 0x8(%ebp),%ebx int r; struct Dev *dev; struct Fd *fd; if ((r = fd_lookup(fdnum, &fd)) < 0 801fd6: 8d 45 f0 lea -0x10(%ebp),%eax 801fd9: 50 push %eax 801fda: 53 push %ebx 801fdb: e8 ad fc ff ff call 801c8d <fd_lookup> 801fe0: 83 c4 08 add $0x8,%esp 801fe3: 85 c0 test %eax,%eax 801fe5: 78 3a js 802021 <write+0x55> || (r = dev_lookup(fd->fd_dev_id, &dev)) < 0) 801fe7: 83 ec 08 sub $0x8,%esp 801fea: 8d 45 f4 lea -0xc(%ebp),%eax 801fed: 50 push %eax 801fee: 8b 45 f0 mov -0x10(%ebp),%eax 801ff1: ff 30 pushl (%eax) 801ff3: e8 eb fc ff ff call 801ce3 <dev_lookup> 801ff8: 83 c4 10 add $0x10,%esp 801ffb: 85 c0 test %eax,%eax 801ffd: 78 22 js 802021 <write+0x55> return r; if ((fd->fd_omode & O_ACCMODE) == O_RDONLY) { 801fff: 8b 45 f0 mov -0x10(%ebp),%eax 802002: f6 40 08 03 testb $0x3,0x8(%eax) 802006: 74 1e je 802026 <write+0x5a> return -E_INVAL; } if (debug) cprintf("write %d %p %d via dev %s\n", fdnum, buf, n, dev->dev_name); if (!dev->dev_write) 802008: 8b 55 f4 mov -0xc(%ebp),%edx 80200b: 8b 52 0c mov 0xc(%edx),%edx 80200e: 85 d2 test %edx,%edx 802010: 74 35 je 802047 <write+0x7b> return -E_NOT_SUPP; return (*dev->dev_write)(fd, buf, n); 802012: 83 ec 04 sub $0x4,%esp 802015: ff 75 10 pushl 0x10(%ebp) 802018: ff 75 0c pushl 0xc(%ebp) 80201b: 50 push %eax 80201c: ff d2 call *%edx 80201e: 83 c4 10 add $0x10,%esp } 802021: 8b 5d fc mov -0x4(%ebp),%ebx 802024: c9 leave 802025: c3 ret cprintf("[%08x] write %d -- bad mode\n", thisenv->env_id, fdnum); 802026: a1 24 54 80 00 mov 0x805424,%eax 80202b: 8b 40 48 mov 0x48(%eax),%eax 80202e: 83 ec 04 sub $0x4,%esp 802031: 53 push %ebx 802032: 50 push %eax 802033: 68 dd 38 80 00 push $0x8038dd 802038: e8 d1 ea ff ff call 800b0e <cprintf> return -E_INVAL; 80203d: 83 c4 10 add $0x10,%esp 802040: b8 fd ff ff ff mov $0xfffffffd,%eax 802045: eb da jmp 802021 <write+0x55> return -E_NOT_SUPP; 802047: b8 f1 ff ff ff mov $0xfffffff1,%eax 80204c: eb d3 jmp 802021 <write+0x55> 0080204e <seek>: int seek(int fdnum, off_t offset) { 80204e: 55 push %ebp 80204f: 89 e5 mov %esp,%ebp 802051: 83 ec 10 sub $0x10,%esp int r; struct Fd *fd; if ((r = fd_lookup(fdnum, &fd)) < 0) 802054: 8d 45 fc lea -0x4(%ebp),%eax 802057: 50 push %eax 802058: ff 75 08 pushl 0x8(%ebp) 80205b: e8 2d fc ff ff call 801c8d <fd_lookup> 802060: 83 c4 08 add $0x8,%esp 802063: 85 c0 test %eax,%eax 802065: 78 0e js 802075 <seek+0x27> return r; fd->fd_offset = offset; 802067: 8b 55 0c mov 0xc(%ebp),%edx 80206a: 8b 45 fc mov -0x4(%ebp),%eax 80206d: 89 50 04 mov %edx,0x4(%eax) return 0; 802070: b8 00 00 00 00 mov $0x0,%eax } 802075: c9 leave 802076: c3 ret 00802077 <ftruncate>: int ftruncate(int fdnum, off_t newsize) { 802077: 55 push %ebp 802078: 89 e5 mov %esp,%ebp 80207a: 53 push %ebx 80207b: 83 ec 14 sub $0x14,%esp 80207e: 8b 5d 08 mov 0x8(%ebp),%ebx int r; struct Dev *dev; struct Fd *fd; if ((r = fd_lookup(fdnum, &fd)) < 0 802081: 8d 45 f0 lea -0x10(%ebp),%eax 802084: 50 push %eax 802085: 53 push %ebx 802086: e8 02 fc ff ff call 801c8d <fd_lookup> 80208b: 83 c4 08 add $0x8,%esp 80208e: 85 c0 test %eax,%eax 802090: 78 37 js 8020c9 <ftruncate+0x52> || (r = dev_lookup(fd->fd_dev_id, &dev)) < 0) 802092: 83 ec 08 sub $0x8,%esp 802095: 8d 45 f4 lea -0xc(%ebp),%eax 802098: 50 push %eax 802099: 8b 45 f0 mov -0x10(%ebp),%eax 80209c: ff 30 pushl (%eax) 80209e: e8 40 fc ff ff call 801ce3 <dev_lookup> 8020a3: 83 c4 10 add $0x10,%esp 8020a6: 85 c0 test %eax,%eax 8020a8: 78 1f js 8020c9 <ftruncate+0x52> return r; if ((fd->fd_omode & O_ACCMODE) == O_RDONLY) { 8020aa: 8b 45 f0 mov -0x10(%ebp),%eax 8020ad: f6 40 08 03 testb $0x3,0x8(%eax) 8020b1: 74 1b je 8020ce <ftruncate+0x57> cprintf("[%08x] ftruncate %d -- bad mode\n", thisenv->env_id, fdnum); return -E_INVAL; } if (!dev->dev_trunc) 8020b3: 8b 55 f4 mov -0xc(%ebp),%edx 8020b6: 8b 52 18 mov 0x18(%edx),%edx 8020b9: 85 d2 test %edx,%edx 8020bb: 74 32 je 8020ef <ftruncate+0x78> return -E_NOT_SUPP; return (*dev->dev_trunc)(fd, newsize); 8020bd: 83 ec 08 sub $0x8,%esp 8020c0: ff 75 0c pushl 0xc(%ebp) 8020c3: 50 push %eax 8020c4: ff d2 call *%edx 8020c6: 83 c4 10 add $0x10,%esp } 8020c9: 8b 5d fc mov -0x4(%ebp),%ebx 8020cc: c9 leave 8020cd: c3 ret thisenv->env_id, fdnum); 8020ce: a1 24 54 80 00 mov 0x805424,%eax cprintf("[%08x] ftruncate %d -- bad mode\n", 8020d3: 8b 40 48 mov 0x48(%eax),%eax 8020d6: 83 ec 04 sub $0x4,%esp 8020d9: 53 push %ebx 8020da: 50 push %eax 8020db: 68 a0 38 80 00 push $0x8038a0 8020e0: e8 29 ea ff ff call 800b0e <cprintf> return -E_INVAL; 8020e5: 83 c4 10 add $0x10,%esp 8020e8: b8 fd ff ff ff mov $0xfffffffd,%eax 8020ed: eb da jmp 8020c9 <ftruncate+0x52> return -E_NOT_SUPP; 8020ef: b8 f1 ff ff ff mov $0xfffffff1,%eax 8020f4: eb d3 jmp 8020c9 <ftruncate+0x52> 008020f6 <fstat>: int fstat(int fdnum, struct Stat *stat) { 8020f6: 55 push %ebp 8020f7: 89 e5 mov %esp,%ebp 8020f9: 53 push %ebx 8020fa: 83 ec 14 sub $0x14,%esp 8020fd: 8b 5d 0c mov 0xc(%ebp),%ebx int r; struct Dev *dev; struct Fd *fd; if ((r = fd_lookup(fdnum, &fd)) < 0 802100: 8d 45 f0 lea -0x10(%ebp),%eax 802103: 50 push %eax 802104: ff 75 08 pushl 0x8(%ebp) 802107: e8 81 fb ff ff call 801c8d <fd_lookup> 80210c: 83 c4 08 add $0x8,%esp 80210f: 85 c0 test %eax,%eax 802111: 78 4b js 80215e <fstat+0x68> || (r = dev_lookup(fd->fd_dev_id, &dev)) < 0) 802113: 83 ec 08 sub $0x8,%esp 802116: 8d 45 f4 lea -0xc(%ebp),%eax 802119: 50 push %eax 80211a: 8b 45 f0 mov -0x10(%ebp),%eax 80211d: ff 30 pushl (%eax) 80211f: e8 bf fb ff ff call 801ce3 <dev_lookup> 802124: 83 c4 10 add $0x10,%esp 802127: 85 c0 test %eax,%eax 802129: 78 33 js 80215e <fstat+0x68> return r; if (!dev->dev_stat) 80212b: 8b 45 f4 mov -0xc(%ebp),%eax 80212e: 83 78 14 00 cmpl $0x0,0x14(%eax) 802132: 74 2f je 802163 <fstat+0x6d> return -E_NOT_SUPP; stat->st_name[0] = 0; 802134: c6 03 00 movb $0x0,(%ebx) stat->st_size = 0; 802137: c7 83 80 00 00 00 00 movl $0x0,0x80(%ebx) 80213e: 00 00 00 stat->st_isdir = 0; 802141: c7 83 84 00 00 00 00 movl $0x0,0x84(%ebx) 802148: 00 00 00 stat->st_dev = dev; 80214b: 89 83 88 00 00 00 mov %eax,0x88(%ebx) return (*dev->dev_stat)(fd, stat); 802151: 83 ec 08 sub $0x8,%esp 802154: 53 push %ebx 802155: ff 75 f0 pushl -0x10(%ebp) 802158: ff 50 14 call *0x14(%eax) 80215b: 83 c4 10 add $0x10,%esp } 80215e: 8b 5d fc mov -0x4(%ebp),%ebx 802161: c9 leave 802162: c3 ret return -E_NOT_SUPP; 802163: b8 f1 ff ff ff mov $0xfffffff1,%eax 802168: eb f4 jmp 80215e <fstat+0x68> 0080216a <stat>: int stat(const char *path, struct Stat *stat) { 80216a: 55 push %ebp 80216b: 89 e5 mov %esp,%ebp 80216d: 56 push %esi 80216e: 53 push %ebx int fd, r; if ((fd = open(path, O_RDONLY)) < 0) 80216f: 83 ec 08 sub $0x8,%esp 802172: 6a 00 push $0x0 802174: ff 75 08 pushl 0x8(%ebp) 802177: e8 30 02 00 00 call 8023ac <open> 80217c: 89 c3 mov %eax,%ebx 80217e: 83 c4 10 add $0x10,%esp 802181: 85 c0 test %eax,%eax 802183: 78 1b js 8021a0 <stat+0x36> return fd; r = fstat(fd, stat); 802185: 83 ec 08 sub $0x8,%esp 802188: ff 75 0c pushl 0xc(%ebp) 80218b: 50 push %eax 80218c: e8 65 ff ff ff call 8020f6 <fstat> 802191: 89 c6 mov %eax,%esi close(fd); 802193: 89 1c 24 mov %ebx,(%esp) 802196: e8 27 fc ff ff call 801dc2 <close> return r; 80219b: 83 c4 10 add $0x10,%esp 80219e: 89 f3 mov %esi,%ebx } 8021a0: 89 d8 mov %ebx,%eax 8021a2: 8d 65 f8 lea -0x8(%ebp),%esp 8021a5: 5b pop %ebx 8021a6: 5e pop %esi 8021a7: 5d pop %ebp 8021a8: c3 ret 008021a9 <fsipc>: // type: request code, passed as the simple integer IPC value. // dstva: virtual address at which to receive reply page, 0 if none. // Returns result from the file server. static int fsipc(unsigned type, void *dstva) { 8021a9: 55 push %ebp 8021aa: 89 e5 mov %esp,%ebp 8021ac: 56 push %esi 8021ad: 53 push %ebx 8021ae: 89 c6 mov %eax,%esi 8021b0: 89 d3 mov %edx,%ebx static envid_t fsenv; if (fsenv == 0) 8021b2: 83 3d 20 54 80 00 00 cmpl $0x0,0x805420 8021b9: 74 27 je 8021e2 <fsipc+0x39> static_assert(sizeof(fsipcbuf) == PGSIZE); if (debug) cprintf("[%08x] fsipc %d %08x\n", thisenv->env_id, type, *(uint32_t *)&fsipcbuf); ipc_send(fsenv, type, &fsipcbuf, PTE_P | PTE_W | PTE_U); 8021bb: 6a 07 push $0x7 8021bd: 68 00 60 80 00 push $0x806000 8021c2: 56 push %esi 8021c3: ff 35 20 54 80 00 pushl 0x805420 8021c9: e8 88 0d 00 00 call 802f56 <ipc_send> return ipc_recv(NULL, dstva, NULL); 8021ce: 83 c4 0c add $0xc,%esp 8021d1: 6a 00 push $0x0 8021d3: 53 push %ebx 8021d4: 6a 00 push $0x0 8021d6: e8 12 0d 00 00 call 802eed <ipc_recv> } 8021db: 8d 65 f8 lea -0x8(%ebp),%esp 8021de: 5b pop %ebx 8021df: 5e pop %esi 8021e0: 5d pop %ebp 8021e1: c3 ret fsenv = ipc_find_env(ENV_TYPE_FS); 8021e2: 83 ec 0c sub $0xc,%esp 8021e5: 6a 01 push $0x1 8021e7: e8 be 0d 00 00 call 802faa <ipc_find_env> 8021ec: a3 20 54 80 00 mov %eax,0x805420 8021f1: 83 c4 10 add $0x10,%esp 8021f4: eb c5 jmp 8021bb <fsipc+0x12> 008021f6 <devfile_trunc>: } // Truncate or extend an open file to 'size' bytes static int devfile_trunc(struct Fd *fd, off_t newsize) { 8021f6: 55 push %ebp 8021f7: 89 e5 mov %esp,%ebp 8021f9: 83 ec 08 sub $0x8,%esp fsipcbuf.set_size.req_fileid = fd->fd_file.id; 8021fc: 8b 45 08 mov 0x8(%ebp),%eax 8021ff: 8b 40 0c mov 0xc(%eax),%eax 802202: a3 00 60 80 00 mov %eax,0x806000 fsipcbuf.set_size.req_size = newsize; 802207: 8b 45 0c mov 0xc(%ebp),%eax 80220a: a3 04 60 80 00 mov %eax,0x806004 return fsipc(FSREQ_SET_SIZE, NULL); 80220f: ba 00 00 00 00 mov $0x0,%edx 802214: b8 02 00 00 00 mov $0x2,%eax 802219: e8 8b ff ff ff call 8021a9 <fsipc> } 80221e: c9 leave 80221f: c3 ret 00802220 <devfile_flush>: { 802220: 55 push %ebp 802221: 89 e5 mov %esp,%ebp 802223: 83 ec 08 sub $0x8,%esp fsipcbuf.flush.req_fileid = fd->fd_file.id; 802226: 8b 45 08 mov 0x8(%ebp),%eax 802229: 8b 40 0c mov 0xc(%eax),%eax 80222c: a3 00 60 80 00 mov %eax,0x806000 return fsipc(FSREQ_FLUSH, NULL); 802231: ba 00 00 00 00 mov $0x0,%edx 802236: b8 06 00 00 00 mov $0x6,%eax 80223b: e8 69 ff ff ff call 8021a9 <fsipc> } 802240: c9 leave 802241: c3 ret 00802242 <devfile_stat>: { 802242: 55 push %ebp 802243: 89 e5 mov %esp,%ebp 802245: 53 push %ebx 802246: 83 ec 04 sub $0x4,%esp 802249: 8b 5d 0c mov 0xc(%ebp),%ebx fsipcbuf.stat.req_fileid = fd->fd_file.id; 80224c: 8b 45 08 mov 0x8(%ebp),%eax 80224f: 8b 40 0c mov 0xc(%eax),%eax 802252: a3 00 60 80 00 mov %eax,0x806000 if ((r = fsipc(FSREQ_STAT, NULL)) < 0) 802257: ba 00 00 00 00 mov $0x0,%edx 80225c: b8 05 00 00 00 mov $0x5,%eax 802261: e8 43 ff ff ff call 8021a9 <fsipc> 802266: 85 c0 test %eax,%eax 802268: 78 2c js 802296 <devfile_stat+0x54> strcpy(st->st_name, fsipcbuf.statRet.ret_name); 80226a: 83 ec 08 sub $0x8,%esp 80226d: 68 00 60 80 00 push $0x806000 802272: 53 push %ebx 802273: e8 a5 ef ff ff call 80121d <strcpy> st->st_size = fsipcbuf.statRet.ret_size; 802278: a1 80 60 80 00 mov 0x806080,%eax 80227d: 89 83 80 00 00 00 mov %eax,0x80(%ebx) st->st_isdir = fsipcbuf.statRet.ret_isdir; 802283: a1 84 60 80 00 mov 0x806084,%eax 802288: 89 83 84 00 00 00 mov %eax,0x84(%ebx) return 0; 80228e: 83 c4 10 add $0x10,%esp 802291: b8 00 00 00 00 mov $0x0,%eax } 802296: 8b 5d fc mov -0x4(%ebp),%ebx 802299: c9 leave 80229a: c3 ret 0080229b <devfile_write>: { 80229b: 55 push %ebp 80229c: 89 e5 mov %esp,%ebp 80229e: 53 push %ebx 80229f: 83 ec 08 sub $0x8,%esp 8022a2: 8b 5d 10 mov 0x10(%ebp),%ebx n = sizeof(fsipcbuf.write.req_buf) > n ? n : sizeof(fsipcbuf.write.req_buf); 8022a5: 81 fb f8 0f 00 00 cmp $0xff8,%ebx 8022ab: b8 f8 0f 00 00 mov $0xff8,%eax 8022b0: 0f 47 d8 cmova %eax,%ebx fsipcbuf.write.req_fileid = fd->fd_file.id; 8022b3: 8b 45 08 mov 0x8(%ebp),%eax 8022b6: 8b 40 0c mov 0xc(%eax),%eax 8022b9: a3 00 60 80 00 mov %eax,0x806000 fsipcbuf.write.req_n = n; 8022be: 89 1d 04 60 80 00 mov %ebx,0x806004 memmove(fsipcbuf.write.req_buf, buf, n); 8022c4: 53 push %ebx 8022c5: ff 75 0c pushl 0xc(%ebp) 8022c8: 68 08 60 80 00 push $0x806008 8022cd: e8 d9 f0 ff ff call 8013ab <memmove> if ((r = fsipc(FSREQ_WRITE, NULL)) < 0) 8022d2: ba 00 00 00 00 mov $0x0,%edx 8022d7: b8 04 00 00 00 mov $0x4,%eax 8022dc: e8 c8 fe ff ff call 8021a9 <fsipc> 8022e1: 83 c4 10 add $0x10,%esp 8022e4: 85 c0 test %eax,%eax 8022e6: 78 0b js 8022f3 <devfile_write+0x58> assert(r <= n); 8022e8: 39 d8 cmp %ebx,%eax 8022ea: 77 0c ja 8022f8 <devfile_write+0x5d> assert(r <= PGSIZE); 8022ec: 3d 00 10 00 00 cmp $0x1000,%eax 8022f1: 7f 1e jg 802311 <devfile_write+0x76> } 8022f3: 8b 5d fc mov -0x4(%ebp),%ebx 8022f6: c9 leave 8022f7: c3 ret assert(r <= n); 8022f8: 68 0c 39 80 00 push $0x80390c 8022fd: 68 af 33 80 00 push $0x8033af 802302: 68 98 00 00 00 push $0x98 802307: 68 13 39 80 00 push $0x803913 80230c: e8 22 e7 ff ff call 800a33 <_panic> assert(r <= PGSIZE); 802311: 68 1e 39 80 00 push $0x80391e 802316: 68 af 33 80 00 push $0x8033af 80231b: 68 99 00 00 00 push $0x99 802320: 68 13 39 80 00 push $0x803913 802325: e8 09 e7 ff ff call 800a33 <_panic> 0080232a <devfile_read>: { 80232a: 55 push %ebp 80232b: 89 e5 mov %esp,%ebp 80232d: 56 push %esi 80232e: 53 push %ebx 80232f: 8b 75 10 mov 0x10(%ebp),%esi fsipcbuf.read.req_fileid = fd->fd_file.id; 802332: 8b 45 08 mov 0x8(%ebp),%eax 802335: 8b 40 0c mov 0xc(%eax),%eax 802338: a3 00 60 80 00 mov %eax,0x806000 fsipcbuf.read.req_n = n; 80233d: 89 35 04 60 80 00 mov %esi,0x806004 if ((r = fsipc(FSREQ_READ, NULL)) < 0) 802343: ba 00 00 00 00 mov $0x0,%edx 802348: b8 03 00 00 00 mov $0x3,%eax 80234d: e8 57 fe ff ff call 8021a9 <fsipc> 802352: 89 c3 mov %eax,%ebx 802354: 85 c0 test %eax,%eax 802356: 78 1f js 802377 <devfile_read+0x4d> assert(r <= n); 802358: 39 f0 cmp %esi,%eax 80235a: 77 24 ja 802380 <devfile_read+0x56> assert(r <= PGSIZE); 80235c: 3d 00 10 00 00 cmp $0x1000,%eax 802361: 7f 33 jg 802396 <devfile_read+0x6c> memmove(buf, fsipcbuf.readRet.ret_buf, r); 802363: 83 ec 04 sub $0x4,%esp 802366: 50 push %eax 802367: 68 00 60 80 00 push $0x806000 80236c: ff 75 0c pushl 0xc(%ebp) 80236f: e8 37 f0 ff ff call 8013ab <memmove> return r; 802374: 83 c4 10 add $0x10,%esp } 802377: 89 d8 mov %ebx,%eax 802379: 8d 65 f8 lea -0x8(%ebp),%esp 80237c: 5b pop %ebx 80237d: 5e pop %esi 80237e: 5d pop %ebp 80237f: c3 ret assert(r <= n); 802380: 68 0c 39 80 00 push $0x80390c 802385: 68 af 33 80 00 push $0x8033af 80238a: 6a 7c push $0x7c 80238c: 68 13 39 80 00 push $0x803913 802391: e8 9d e6 ff ff call 800a33 <_panic> assert(r <= PGSIZE); 802396: 68 1e 39 80 00 push $0x80391e 80239b: 68 af 33 80 00 push $0x8033af 8023a0: 6a 7d push $0x7d 8023a2: 68 13 39 80 00 push $0x803913 8023a7: e8 87 e6 ff ff call 800a33 <_panic> 008023ac <open>: { 8023ac: 55 push %ebp 8023ad: 89 e5 mov %esp,%ebp 8023af: 56 push %esi 8023b0: 53 push %ebx 8023b1: 83 ec 1c sub $0x1c,%esp 8023b4: 8b 75 08 mov 0x8(%ebp),%esi if (strlen(path) >= MAXPATHLEN) 8023b7: 56 push %esi 8023b8: e8 29 ee ff ff call 8011e6 <strlen> 8023bd: 83 c4 10 add $0x10,%esp 8023c0: 3d ff 03 00 00 cmp $0x3ff,%eax 8023c5: 7f 6c jg 802433 <open+0x87> if ((r = fd_alloc(&fd)) < 0) 8023c7: 83 ec 0c sub $0xc,%esp 8023ca: 8d 45 f4 lea -0xc(%ebp),%eax 8023cd: 50 push %eax 8023ce: e8 6b f8 ff ff call 801c3e <fd_alloc> 8023d3: 89 c3 mov %eax,%ebx 8023d5: 83 c4 10 add $0x10,%esp 8023d8: 85 c0 test %eax,%eax 8023da: 78 3c js 802418 <open+0x6c> strcpy(fsipcbuf.open.req_path, path); 8023dc: 83 ec 08 sub $0x8,%esp 8023df: 56 push %esi 8023e0: 68 00 60 80 00 push $0x806000 8023e5: e8 33 ee ff ff call 80121d <strcpy> fsipcbuf.open.req_omode = mode; 8023ea: 8b 45 0c mov 0xc(%ebp),%eax 8023ed: a3 00 64 80 00 mov %eax,0x806400 if ((r = fsipc(FSREQ_OPEN, fd)) < 0) { 8023f2: 8b 55 f4 mov -0xc(%ebp),%edx 8023f5: b8 01 00 00 00 mov $0x1,%eax 8023fa: e8 aa fd ff ff call 8021a9 <fsipc> 8023ff: 89 c3 mov %eax,%ebx 802401: 83 c4 10 add $0x10,%esp 802404: 85 c0 test %eax,%eax 802406: 78 19 js 802421 <open+0x75> return fd2num(fd); 802408: 83 ec 0c sub $0xc,%esp 80240b: ff 75 f4 pushl -0xc(%ebp) 80240e: e8 04 f8 ff ff call 801c17 <fd2num> 802413: 89 c3 mov %eax,%ebx 802415: 83 c4 10 add $0x10,%esp } 802418: 89 d8 mov %ebx,%eax 80241a: 8d 65 f8 lea -0x8(%ebp),%esp 80241d: 5b pop %ebx 80241e: 5e pop %esi 80241f: 5d pop %ebp 802420: c3 ret fd_close(fd, 0); 802421: 83 ec 08 sub $0x8,%esp 802424: 6a 00 push $0x0 802426: ff 75 f4 pushl -0xc(%ebp) 802429: e8 0b f9 ff ff call 801d39 <fd_close> return r; 80242e: 83 c4 10 add $0x10,%esp 802431: eb e5 jmp 802418 <open+0x6c> return -E_BAD_PATH; 802433: bb f4 ff ff ff mov $0xfffffff4,%ebx 802438: eb de jmp 802418 <open+0x6c> 0080243a <sync>: // Synchronize disk with buffer cache int sync(void) { 80243a: 55 push %ebp 80243b: 89 e5 mov %esp,%ebp 80243d: 83 ec 08 sub $0x8,%esp // Ask the file server to update the disk // by writing any dirty blocks in the buffer cache. return fsipc(FSREQ_SYNC, NULL); 802440: ba 00 00 00 00 mov $0x0,%edx 802445: b8 08 00 00 00 mov $0x8,%eax 80244a: e8 5a fd ff ff call 8021a9 <fsipc> } 80244f: c9 leave 802450: c3 ret 00802451 <writebuf>: static void writebuf(struct printbuf *b) { if (b->error > 0) { 802451: 83 78 0c 00 cmpl $0x0,0xc(%eax) 802455: 7e 38 jle 80248f <writebuf+0x3e> { 802457: 55 push %ebp 802458: 89 e5 mov %esp,%ebp 80245a: 53 push %ebx 80245b: 83 ec 08 sub $0x8,%esp 80245e: 89 c3 mov %eax,%ebx ssize_t result = write(b->fd, b->buf, b->idx); 802460: ff 70 04 pushl 0x4(%eax) 802463: 8d 40 10 lea 0x10(%eax),%eax 802466: 50 push %eax 802467: ff 33 pushl (%ebx) 802469: e8 5e fb ff ff call 801fcc <write> if (result > 0) 80246e: 83 c4 10 add $0x10,%esp 802471: 85 c0 test %eax,%eax 802473: 7e 03 jle 802478 <writebuf+0x27> b->result += result; 802475: 01 43 08 add %eax,0x8(%ebx) if (result != b->idx) // error, or wrote less than supplied 802478: 39 43 04 cmp %eax,0x4(%ebx) 80247b: 74 0d je 80248a <writebuf+0x39> b->error = (result < 0 ? result : 0); 80247d: 85 c0 test %eax,%eax 80247f: ba 00 00 00 00 mov $0x0,%edx 802484: 0f 4f c2 cmovg %edx,%eax 802487: 89 43 0c mov %eax,0xc(%ebx) } } 80248a: 8b 5d fc mov -0x4(%ebp),%ebx 80248d: c9 leave 80248e: c3 ret 80248f: f3 c3 repz ret 00802491 <putch>: static void putch(int ch, void *thunk) { 802491: 55 push %ebp 802492: 89 e5 mov %esp,%ebp 802494: 53 push %ebx 802495: 83 ec 04 sub $0x4,%esp 802498: 8b 5d 0c mov 0xc(%ebp),%ebx struct printbuf *b = (struct printbuf *) thunk; b->buf[b->idx++] = ch; 80249b: 8b 53 04 mov 0x4(%ebx),%edx 80249e: 8d 42 01 lea 0x1(%edx),%eax 8024a1: 89 43 04 mov %eax,0x4(%ebx) 8024a4: 8b 4d 08 mov 0x8(%ebp),%ecx 8024a7: 88 4c 13 10 mov %cl,0x10(%ebx,%edx,1) if (b->idx == 256) { 8024ab: 3d 00 01 00 00 cmp $0x100,%eax 8024b0: 74 06 je 8024b8 <putch+0x27> writebuf(b); b->idx = 0; } } 8024b2: 83 c4 04 add $0x4,%esp 8024b5: 5b pop %ebx 8024b6: 5d pop %ebp 8024b7: c3 ret writebuf(b); 8024b8: 89 d8 mov %ebx,%eax 8024ba: e8 92 ff ff ff call 802451 <writebuf> b->idx = 0; 8024bf: c7 43 04 00 00 00 00 movl $0x0,0x4(%ebx) } 8024c6: eb ea jmp 8024b2 <putch+0x21> 008024c8 <vfprintf>: int vfprintf(int fd, const char *fmt, va_list ap) { 8024c8: 55 push %ebp 8024c9: 89 e5 mov %esp,%ebp 8024cb: 81 ec 18 01 00 00 sub $0x118,%esp struct printbuf b; b.fd = fd; 8024d1: 8b 45 08 mov 0x8(%ebp),%eax 8024d4: 89 85 e8 fe ff ff mov %eax,-0x118(%ebp) b.idx = 0; 8024da: c7 85 ec fe ff ff 00 movl $0x0,-0x114(%ebp) 8024e1: 00 00 00 b.result = 0; 8024e4: c7 85 f0 fe ff ff 00 movl $0x0,-0x110(%ebp) 8024eb: 00 00 00 b.error = 1; 8024ee: c7 85 f4 fe ff ff 01 movl $0x1,-0x10c(%ebp) 8024f5: 00 00 00 vprintfmt(putch, &b, fmt, ap); 8024f8: ff 75 10 pushl 0x10(%ebp) 8024fb: ff 75 0c pushl 0xc(%ebp) 8024fe: 8d 85 e8 fe ff ff lea -0x118(%ebp),%eax 802504: 50 push %eax 802505: 68 91 24 80 00 push $0x802491 80250a: e8 fc e6 ff ff call 800c0b <vprintfmt> if (b.idx > 0) 80250f: 83 c4 10 add $0x10,%esp 802512: 83 bd ec fe ff ff 00 cmpl $0x0,-0x114(%ebp) 802519: 7f 11 jg 80252c <vfprintf+0x64> writebuf(&b); return (b.result ? b.result : b.error); 80251b: 8b 85 f0 fe ff ff mov -0x110(%ebp),%eax 802521: 85 c0 test %eax,%eax 802523: 0f 44 85 f4 fe ff ff cmove -0x10c(%ebp),%eax } 80252a: c9 leave 80252b: c3 ret writebuf(&b); 80252c: 8d 85 e8 fe ff ff lea -0x118(%ebp),%eax 802532: e8 1a ff ff ff call 802451 <writebuf> 802537: eb e2 jmp 80251b <vfprintf+0x53> 00802539 <fprintf>: int fprintf(int fd, const char *fmt, ...) { 802539: 55 push %ebp 80253a: 89 e5 mov %esp,%ebp 80253c: 83 ec 0c sub $0xc,%esp va_list ap; int cnt; va_start(ap, fmt); 80253f: 8d 45 10 lea 0x10(%ebp),%eax cnt = vfprintf(fd, fmt, ap); 802542: 50 push %eax 802543: ff 75 0c pushl 0xc(%ebp) 802546: ff 75 08 pushl 0x8(%ebp) 802549: e8 7a ff ff ff call 8024c8 <vfprintf> va_end(ap); return cnt; } 80254e: c9 leave 80254f: c3 ret 00802550 <printf>: int printf(const char *fmt, ...) { 802550: 55 push %ebp 802551: 89 e5 mov %esp,%ebp 802553: 83 ec 0c sub $0xc,%esp va_list ap; int cnt; va_start(ap, fmt); 802556: 8d 45 0c lea 0xc(%ebp),%eax cnt = vfprintf(1, fmt, ap); 802559: 50 push %eax 80255a: ff 75 08 pushl 0x8(%ebp) 80255d: 6a 01 push $0x1 80255f: e8 64 ff ff ff call 8024c8 <vfprintf> va_end(ap); return cnt; } 802564: c9 leave 802565: c3 ret 00802566 <spawn>: // argv: pointer to null-terminated array of pointers to strings, // which will be passed to the child as its command-line arguments. // Returns child envid on success, < 0 on failure. int spawn(const char *prog, const char **argv) { 802566: 55 push %ebp 802567: 89 e5 mov %esp,%ebp 802569: 57 push %edi 80256a: 56 push %esi 80256b: 53 push %ebx 80256c: 81 ec 94 02 00 00 sub $0x294,%esp // - Call sys_env_set_trapframe(child, &child_tf) to set up the // correct initial eip and esp values in the child. // // - Start the child process running with sys_env_set_status(). if ((r = open(prog, O_RDONLY)) < 0) 802572: 6a 00 push $0x0 802574: ff 75 08 pushl 0x8(%ebp) 802577: e8 30 fe ff ff call 8023ac <open> 80257c: 89 85 90 fd ff ff mov %eax,-0x270(%ebp) 802582: 83 c4 10 add $0x10,%esp 802585: 85 c0 test %eax,%eax 802587: 0f 88 40 03 00 00 js 8028cd <spawn+0x367> 80258d: 89 c2 mov %eax,%edx return r; fd = r; // Read elf header elf = (struct Elf*) elf_buf; if (readn(fd, elf_buf, sizeof(elf_buf)) != sizeof(elf_buf) 80258f: 83 ec 04 sub $0x4,%esp 802592: 68 00 02 00 00 push $0x200 802597: 8d 85 e8 fd ff ff lea -0x218(%ebp),%eax 80259d: 50 push %eax 80259e: 52 push %edx 80259f: e8 e1 f9 ff ff call 801f85 <readn> 8025a4: 83 c4 10 add $0x10,%esp 8025a7: 3d 00 02 00 00 cmp $0x200,%eax 8025ac: 75 5d jne 80260b <spawn+0xa5> || elf->e_magic != ELF_MAGIC) { 8025ae: 81 bd e8 fd ff ff 7f cmpl $0x464c457f,-0x218(%ebp) 8025b5: 45 4c 46 8025b8: 75 51 jne 80260b <spawn+0xa5> 8025ba: b8 07 00 00 00 mov $0x7,%eax 8025bf: cd 30 int $0x30 8025c1: 89 85 74 fd ff ff mov %eax,-0x28c(%ebp) 8025c7: 89 85 84 fd ff ff mov %eax,-0x27c(%ebp) cprintf("elf magic %08x want %08x\n", elf->e_magic, ELF_MAGIC); return -E_NOT_EXEC; } // Create new child environment if ((r = sys_exofork()) < 0) 8025cd: 85 c0 test %eax,%eax 8025cf: 0f 88 2f 04 00 00 js 802a04 <spawn+0x49e> return r; child = r; // Set up trap frame, including initial stack. child_tf = envs[ENVX(child)].env_tf; 8025d5: 25 ff 03 00 00 and $0x3ff,%eax 8025da: 6b f0 7c imul $0x7c,%eax,%esi 8025dd: 81 c6 00 00 c0 ee add $0xeec00000,%esi 8025e3: 8d bd a4 fd ff ff lea -0x25c(%ebp),%edi 8025e9: b9 11 00 00 00 mov $0x11,%ecx 8025ee: f3 a5 rep movsl %ds:(%esi),%es:(%edi) child_tf.tf_eip = elf->e_entry; 8025f0: 8b 85 00 fe ff ff mov -0x200(%ebp),%eax 8025f6: 89 85 d4 fd ff ff mov %eax,-0x22c(%ebp) uintptr_t *argv_store; // Count the number of arguments (argc) // and the total amount of space needed for strings (string_size). string_size = 0; for (argc = 0; argv[argc] != 0; argc++) 8025fc: bb 00 00 00 00 mov $0x0,%ebx string_size = 0; 802601: be 00 00 00 00 mov $0x0,%esi 802606: 8b 7d 0c mov 0xc(%ebp),%edi 802609: eb 4b jmp 802656 <spawn+0xf0> close(fd); 80260b: 83 ec 0c sub $0xc,%esp 80260e: ff b5 90 fd ff ff pushl -0x270(%ebp) 802614: e8 a9 f7 ff ff call 801dc2 <close> cprintf("elf magic %08x want %08x\n", elf->e_magic, ELF_MAGIC); 802619: 83 c4 0c add $0xc,%esp 80261c: 68 7f 45 4c 46 push $0x464c457f 802621: ff b5 e8 fd ff ff pushl -0x218(%ebp) 802627: 68 2a 39 80 00 push $0x80392a 80262c: e8 dd e4 ff ff call 800b0e <cprintf> return -E_NOT_EXEC; 802631: 83 c4 10 add $0x10,%esp 802634: c7 85 90 fd ff ff f2 movl $0xfffffff2,-0x270(%ebp) 80263b: ff ff ff 80263e: e9 8a 02 00 00 jmp 8028cd <spawn+0x367> string_size += strlen(argv[argc]) + 1; 802643: 83 ec 0c sub $0xc,%esp 802646: 50 push %eax 802647: e8 9a eb ff ff call 8011e6 <strlen> 80264c: 8d 74 30 01 lea 0x1(%eax,%esi,1),%esi for (argc = 0; argv[argc] != 0; argc++) 802650: 83 c3 01 add $0x1,%ebx 802653: 83 c4 10 add $0x10,%esp 802656: 8d 0c 9d 00 00 00 00 lea 0x0(,%ebx,4),%ecx 80265d: 8b 04 9f mov (%edi,%ebx,4),%eax 802660: 85 c0 test %eax,%eax 802662: 75 df jne 802643 <spawn+0xdd> 802664: 89 9d 88 fd ff ff mov %ebx,-0x278(%ebp) 80266a: 89 8d 80 fd ff ff mov %ecx,-0x280(%ebp) // Determine where to place the strings and the argv array. // Set up pointers into the temporary page 'UTEMP'; we'll map a page // there later, then remap that page into the child environment // at (USTACKTOP - PGSIZE). // strings is the topmost thing on the stack. string_store = (char*) UTEMP + PGSIZE - string_size; 802670: bf 00 10 40 00 mov $0x401000,%edi 802675: 29 f7 sub %esi,%edi // argv is below that. There's one argument pointer per argument, plus // a null pointer. argv_store = (uintptr_t*) (ROUNDDOWN(string_store, 4) - 4 * (argc + 1)); 802677: 89 fa mov %edi,%edx 802679: 83 e2 fc and $0xfffffffc,%edx 80267c: 8d 04 9d 04 00 00 00 lea 0x4(,%ebx,4),%eax 802683: 29 c2 sub %eax,%edx 802685: 89 95 94 fd ff ff mov %edx,-0x26c(%ebp) // Make sure that argv, strings, and the 2 words that hold 'argc' // and 'argv' themselves will all fit in a single stack page. if ((void*) (argv_store - 2) < (void*) UTEMP) 80268b: 8d 42 f8 lea -0x8(%edx),%eax 80268e: 3d ff ff 3f 00 cmp $0x3fffff,%eax 802693: 0f 86 7c 03 00 00 jbe 802a15 <spawn+0x4af> return -E_NO_MEM; // Allocate the single stack page at UTEMP. if ((r = sys_page_alloc(0, (void*) UTEMP, PTE_P|PTE_U|PTE_W)) < 0) 802699: 83 ec 04 sub $0x4,%esp 80269c: 6a 07 push $0x7 80269e: 68 00 00 40 00 push $0x400000 8026a3: 6a 00 push $0x0 8026a5: e8 6c ef ff ff call 801616 <sys_page_alloc> 8026aa: 83 c4 10 add $0x10,%esp 8026ad: 85 c0 test %eax,%eax 8026af: 0f 88 65 03 00 00 js 802a1a <spawn+0x4b4> // (Again, argv should use an address valid in the child's // environment.) // // * Set *init_esp to the initial stack pointer for the child, // (Again, use an address valid in the child's environment.) for (i = 0; i < argc; i++) { 8026b5: be 00 00 00 00 mov $0x0,%esi 8026ba: 89 9d 8c fd ff ff mov %ebx,-0x274(%ebp) 8026c0: 8b 5d 0c mov 0xc(%ebp),%ebx 8026c3: eb 30 jmp 8026f5 <spawn+0x18f> argv_store[i] = UTEMP2USTACK(string_store); 8026c5: 8d 87 00 d0 7f ee lea -0x11803000(%edi),%eax 8026cb: 8b 95 94 fd ff ff mov -0x26c(%ebp),%edx 8026d1: 89 04 b2 mov %eax,(%edx,%esi,4) strcpy(string_store, argv[i]); 8026d4: 83 ec 08 sub $0x8,%esp 8026d7: ff 34 b3 pushl (%ebx,%esi,4) 8026da: 57 push %edi 8026db: e8 3d eb ff ff call 80121d <strcpy> string_store += strlen(argv[i]) + 1; 8026e0: 83 c4 04 add $0x4,%esp 8026e3: ff 34 b3 pushl (%ebx,%esi,4) 8026e6: e8 fb ea ff ff call 8011e6 <strlen> 8026eb: 8d 7c 07 01 lea 0x1(%edi,%eax,1),%edi for (i = 0; i < argc; i++) { 8026ef: 83 c6 01 add $0x1,%esi 8026f2: 83 c4 10 add $0x10,%esp 8026f5: 39 b5 8c fd ff ff cmp %esi,-0x274(%ebp) 8026fb: 7f c8 jg 8026c5 <spawn+0x15f> } argv_store[argc] = 0; 8026fd: 8b 85 94 fd ff ff mov -0x26c(%ebp),%eax 802703: 8b 8d 80 fd ff ff mov -0x280(%ebp),%ecx 802709: c7 04 08 00 00 00 00 movl $0x0,(%eax,%ecx,1) assert(string_store == (char*)UTEMP + PGSIZE); 802710: 81 ff 00 10 40 00 cmp $0x401000,%edi 802716: 0f 85 8c 00 00 00 jne 8027a8 <spawn+0x242> argv_store[-1] = UTEMP2USTACK(argv_store); 80271c: 8b bd 94 fd ff ff mov -0x26c(%ebp),%edi 802722: 8d 87 00 d0 7f ee lea -0x11803000(%edi),%eax 802728: 89 47 fc mov %eax,-0x4(%edi) argv_store[-2] = argc; 80272b: 89 f8 mov %edi,%eax 80272d: 8b 8d 88 fd ff ff mov -0x278(%ebp),%ecx 802733: 89 4f f8 mov %ecx,-0x8(%edi) *init_esp = UTEMP2USTACK(&argv_store[-2]); 802736: 2d 08 30 80 11 sub $0x11803008,%eax 80273b: 89 85 e0 fd ff ff mov %eax,-0x220(%ebp) // After completing the stack, map it into the child's address space // and unmap it from ours! if ((r = sys_page_map(0, UTEMP, child, (void*) (USTACKTOP - PGSIZE), PTE_P | PTE_U | PTE_W)) < 0) 802741: 83 ec 0c sub $0xc,%esp 802744: 6a 07 push $0x7 802746: 68 00 d0 bf ee push $0xeebfd000 80274b: ff b5 74 fd ff ff pushl -0x28c(%ebp) 802751: 68 00 00 40 00 push $0x400000 802756: 6a 00 push $0x0 802758: e8 fc ee ff ff call 801659 <sys_page_map> 80275d: 89 c3 mov %eax,%ebx 80275f: 83 c4 20 add $0x20,%esp 802762: 85 c0 test %eax,%eax 802764: 0f 88 d0 02 00 00 js 802a3a <spawn+0x4d4> goto error; if ((r = sys_page_unmap(0, UTEMP)) < 0) 80276a: 83 ec 08 sub $0x8,%esp 80276d: 68 00 00 40 00 push $0x400000 802772: 6a 00 push $0x0 802774: e8 22 ef ff ff call 80169b <sys_page_unmap> 802779: 89 c3 mov %eax,%ebx 80277b: 83 c4 10 add $0x10,%esp 80277e: 85 c0 test %eax,%eax 802780: 0f 88 b4 02 00 00 js 802a3a <spawn+0x4d4> ph = (struct Proghdr*) (elf_buf + elf->e_phoff); 802786: 8b 85 04 fe ff ff mov -0x1fc(%ebp),%eax 80278c: 8d 84 05 e8 fd ff ff lea -0x218(%ebp,%eax,1),%eax 802793: 89 85 78 fd ff ff mov %eax,-0x288(%ebp) for (i = 0; i < elf->e_phnum; i++, ph++) { 802799: c7 85 7c fd ff ff 00 movl $0x0,-0x284(%ebp) 8027a0: 00 00 00 8027a3: e9 56 01 00 00 jmp 8028fe <spawn+0x398> assert(string_store == (char*)UTEMP + PGSIZE); 8027a8: 68 88 39 80 00 push $0x803988 8027ad: 68 af 33 80 00 push $0x8033af 8027b2: 68 f2 00 00 00 push $0xf2 8027b7: 68 44 39 80 00 push $0x803944 8027bc: e8 72 e2 ff ff call 800a33 <_panic> // allocate a blank page if ((r = sys_page_alloc(child, (void*) (va + i), perm)) < 0) return r; } else { // from file if ((r = sys_page_alloc(0, UTEMP, PTE_P|PTE_U|PTE_W)) < 0) 8027c1: 83 ec 04 sub $0x4,%esp 8027c4: 6a 07 push $0x7 8027c6: 68 00 00 40 00 push $0x400000 8027cb: 6a 00 push $0x0 8027cd: e8 44 ee ff ff call 801616 <sys_page_alloc> 8027d2: 83 c4 10 add $0x10,%esp 8027d5: 85 c0 test %eax,%eax 8027d7: 0f 88 48 02 00 00 js 802a25 <spawn+0x4bf> return r; if ((r = seek(fd, fileoffset + i)) < 0) 8027dd: 83 ec 08 sub $0x8,%esp 8027e0: 8b 85 80 fd ff ff mov -0x280(%ebp),%eax 8027e6: 01 f0 add %esi,%eax 8027e8: 50 push %eax 8027e9: ff b5 90 fd ff ff pushl -0x270(%ebp) 8027ef: e8 5a f8 ff ff call 80204e <seek> 8027f4: 83 c4 10 add $0x10,%esp 8027f7: 85 c0 test %eax,%eax 8027f9: 0f 88 2d 02 00 00 js 802a2c <spawn+0x4c6> return r; if ((r = readn(fd, UTEMP, MIN(PGSIZE, filesz-i))) < 0) 8027ff: 83 ec 04 sub $0x4,%esp 802802: 8b 85 94 fd ff ff mov -0x26c(%ebp),%eax 802808: 29 f0 sub %esi,%eax 80280a: 3d 00 10 00 00 cmp $0x1000,%eax 80280f: ba 00 10 00 00 mov $0x1000,%edx 802814: 0f 47 c2 cmova %edx,%eax 802817: 50 push %eax 802818: 68 00 00 40 00 push $0x400000 80281d: ff b5 90 fd ff ff pushl -0x270(%ebp) 802823: e8 5d f7 ff ff call 801f85 <readn> 802828: 83 c4 10 add $0x10,%esp 80282b: 85 c0 test %eax,%eax 80282d: 0f 88 00 02 00 00 js 802a33 <spawn+0x4cd> return r; if ((r = sys_page_map(0, UTEMP, child, (void*) (va + i), perm)) < 0) 802833: 83 ec 0c sub $0xc,%esp 802836: 57 push %edi 802837: 03 b5 88 fd ff ff add -0x278(%ebp),%esi 80283d: 56 push %esi 80283e: ff b5 84 fd ff ff pushl -0x27c(%ebp) 802844: 68 00 00 40 00 push $0x400000 802849: 6a 00 push $0x0 80284b: e8 09 ee ff ff call 801659 <sys_page_map> 802850: 83 c4 20 add $0x20,%esp 802853: 85 c0 test %eax,%eax 802855: 0f 88 80 00 00 00 js 8028db <spawn+0x375> panic("spawn: sys_page_map data: %e", r); sys_page_unmap(0, UTEMP); 80285b: 83 ec 08 sub $0x8,%esp 80285e: 68 00 00 40 00 push $0x400000 802863: 6a 00 push $0x0 802865: e8 31 ee ff ff call 80169b <sys_page_unmap> 80286a: 83 c4 10 add $0x10,%esp for (i = 0; i < memsz; i += PGSIZE) { 80286d: 81 c3 00 10 00 00 add $0x1000,%ebx 802873: 89 de mov %ebx,%esi 802875: 39 9d 8c fd ff ff cmp %ebx,-0x274(%ebp) 80287b: 76 73 jbe 8028f0 <spawn+0x38a> if (i >= filesz) { 80287d: 39 9d 94 fd ff ff cmp %ebx,-0x26c(%ebp) 802883: 0f 87 38 ff ff ff ja 8027c1 <spawn+0x25b> if ((r = sys_page_alloc(child, (void*) (va + i), perm)) < 0) 802889: 83 ec 04 sub $0x4,%esp 80288c: 57 push %edi 80288d: 03 b5 88 fd ff ff add -0x278(%ebp),%esi 802893: 56 push %esi 802894: ff b5 84 fd ff ff pushl -0x27c(%ebp) 80289a: e8 77 ed ff ff call 801616 <sys_page_alloc> 80289f: 83 c4 10 add $0x10,%esp 8028a2: 85 c0 test %eax,%eax 8028a4: 79 c7 jns 80286d <spawn+0x307> 8028a6: 89 c7 mov %eax,%edi sys_env_destroy(child); 8028a8: 83 ec 0c sub $0xc,%esp 8028ab: ff b5 74 fd ff ff pushl -0x28c(%ebp) 8028b1: e8 e1 ec ff ff call 801597 <sys_env_destroy> close(fd); 8028b6: 83 c4 04 add $0x4,%esp 8028b9: ff b5 90 fd ff ff pushl -0x270(%ebp) 8028bf: e8 fe f4 ff ff call 801dc2 <close> return r; 8028c4: 83 c4 10 add $0x10,%esp 8028c7: 89 bd 90 fd ff ff mov %edi,-0x270(%ebp) } 8028cd: 8b 85 90 fd ff ff mov -0x270(%ebp),%eax 8028d3: 8d 65 f4 lea -0xc(%ebp),%esp 8028d6: 5b pop %ebx 8028d7: 5e pop %esi 8028d8: 5f pop %edi 8028d9: 5d pop %ebp 8028da: c3 ret panic("spawn: sys_page_map data: %e", r); 8028db: 50 push %eax 8028dc: 68 50 39 80 00 push $0x803950 8028e1: 68 25 01 00 00 push $0x125 8028e6: 68 44 39 80 00 push $0x803944 8028eb: e8 43 e1 ff ff call 800a33 <_panic> for (i = 0; i < elf->e_phnum; i++, ph++) { 8028f0: 83 85 7c fd ff ff 01 addl $0x1,-0x284(%ebp) 8028f7: 83 85 78 fd ff ff 20 addl $0x20,-0x288(%ebp) 8028fe: 0f b7 85 14 fe ff ff movzwl -0x1ec(%ebp),%eax 802905: 3b 85 7c fd ff ff cmp -0x284(%ebp),%eax 80290b: 7e 71 jle 80297e <spawn+0x418> if (ph->p_type != ELF_PROG_LOAD) 80290d: 8b 8d 78 fd ff ff mov -0x288(%ebp),%ecx 802913: 83 39 01 cmpl $0x1,(%ecx) 802916: 75 d8 jne 8028f0 <spawn+0x38a> if (ph->p_flags & ELF_PROG_FLAG_WRITE) 802918: 8b 41 18 mov 0x18(%ecx),%eax 80291b: 83 e0 02 and $0x2,%eax perm |= PTE_W; 80291e: 83 f8 01 cmp $0x1,%eax 802921: 19 ff sbb %edi,%edi 802923: 83 e7 fe and $0xfffffffe,%edi 802926: 83 c7 07 add $0x7,%edi if ((r = map_segment(child, ph->p_va, ph->p_memsz, 802929: 8b 59 04 mov 0x4(%ecx),%ebx 80292c: 89 9d 80 fd ff ff mov %ebx,-0x280(%ebp) 802932: 8b 71 10 mov 0x10(%ecx),%esi 802935: 89 b5 94 fd ff ff mov %esi,-0x26c(%ebp) 80293b: 8b 41 14 mov 0x14(%ecx),%eax 80293e: 89 85 8c fd ff ff mov %eax,-0x274(%ebp) 802944: 8b 51 08 mov 0x8(%ecx),%edx 802947: 89 95 88 fd ff ff mov %edx,-0x278(%ebp) if ((i = PGOFF(va))) { 80294d: 89 d0 mov %edx,%eax 80294f: 25 ff 0f 00 00 and $0xfff,%eax 802954: 74 1e je 802974 <spawn+0x40e> va -= i; 802956: 29 c2 sub %eax,%edx 802958: 89 95 88 fd ff ff mov %edx,-0x278(%ebp) memsz += i; 80295e: 01 85 8c fd ff ff add %eax,-0x274(%ebp) filesz += i; 802964: 01 c6 add %eax,%esi 802966: 89 b5 94 fd ff ff mov %esi,-0x26c(%ebp) fileoffset -= i; 80296c: 29 c3 sub %eax,%ebx 80296e: 89 9d 80 fd ff ff mov %ebx,-0x280(%ebp) for (i = 0; i < memsz; i += PGSIZE) { 802974: bb 00 00 00 00 mov $0x0,%ebx 802979: e9 f5 fe ff ff jmp 802873 <spawn+0x30d> close(fd); 80297e: 83 ec 0c sub $0xc,%esp 802981: ff b5 90 fd ff ff pushl -0x270(%ebp) 802987: e8 36 f4 ff ff call 801dc2 <close> child_tf.tf_eflags |= FL_IOPL_3; // devious: see user/faultio.c 80298c: 81 8d dc fd ff ff 00 orl $0x3000,-0x224(%ebp) 802993: 30 00 00 if ((r = sys_env_set_trapframe(child, &child_tf)) < 0) 802996: 83 c4 08 add $0x8,%esp 802999: 8d 85 a4 fd ff ff lea -0x25c(%ebp),%eax 80299f: 50 push %eax 8029a0: ff b5 74 fd ff ff pushl -0x28c(%ebp) 8029a6: e8 74 ed ff ff call 80171f <sys_env_set_trapframe> 8029ab: 83 c4 10 add $0x10,%esp 8029ae: 85 c0 test %eax,%eax 8029b0: 78 28 js 8029da <spawn+0x474> if ((r = sys_env_set_status(child, ENV_RUNNABLE)) < 0) 8029b2: 83 ec 08 sub $0x8,%esp 8029b5: 6a 02 push $0x2 8029b7: ff b5 74 fd ff ff pushl -0x28c(%ebp) 8029bd: e8 1b ed ff ff call 8016dd <sys_env_set_status> 8029c2: 83 c4 10 add $0x10,%esp 8029c5: 85 c0 test %eax,%eax 8029c7: 78 26 js 8029ef <spawn+0x489> return child; 8029c9: 8b 85 74 fd ff ff mov -0x28c(%ebp),%eax 8029cf: 89 85 90 fd ff ff mov %eax,-0x270(%ebp) 8029d5: e9 f3 fe ff ff jmp 8028cd <spawn+0x367> panic("sys_env_set_trapframe: %e", r); 8029da: 50 push %eax 8029db: 68 6d 39 80 00 push $0x80396d 8029e0: 68 86 00 00 00 push $0x86 8029e5: 68 44 39 80 00 push $0x803944 8029ea: e8 44 e0 ff ff call 800a33 <_panic> panic("sys_env_set_status: %e", r); 8029ef: 50 push %eax 8029f0: 68 50 38 80 00 push $0x803850 8029f5: 68 89 00 00 00 push $0x89 8029fa: 68 44 39 80 00 push $0x803944 8029ff: e8 2f e0 ff ff call 800a33 <_panic> return r; 802a04: 8b 85 74 fd ff ff mov -0x28c(%ebp),%eax 802a0a: 89 85 90 fd ff ff mov %eax,-0x270(%ebp) 802a10: e9 b8 fe ff ff jmp 8028cd <spawn+0x367> return -E_NO_MEM; 802a15: b8 fc ff ff ff mov $0xfffffffc,%eax return r; 802a1a: 89 85 90 fd ff ff mov %eax,-0x270(%ebp) 802a20: e9 a8 fe ff ff jmp 8028cd <spawn+0x367> 802a25: 89 c7 mov %eax,%edi 802a27: e9 7c fe ff ff jmp 8028a8 <spawn+0x342> 802a2c: 89 c7 mov %eax,%edi 802a2e: e9 75 fe ff ff jmp 8028a8 <spawn+0x342> 802a33: 89 c7 mov %eax,%edi 802a35: e9 6e fe ff ff jmp 8028a8 <spawn+0x342> sys_page_unmap(0, UTEMP); 802a3a: 83 ec 08 sub $0x8,%esp 802a3d: 68 00 00 40 00 push $0x400000 802a42: 6a 00 push $0x0 802a44: e8 52 ec ff ff call 80169b <sys_page_unmap> 802a49: 83 c4 10 add $0x10,%esp 802a4c: 89 9d 90 fd ff ff mov %ebx,-0x270(%ebp) 802a52: e9 76 fe ff ff jmp 8028cd <spawn+0x367> 00802a57 <spawnl>: { 802a57: 55 push %ebp 802a58: 89 e5 mov %esp,%ebp 802a5a: 57 push %edi 802a5b: 56 push %esi 802a5c: 53 push %ebx 802a5d: 83 ec 0c sub $0xc,%esp va_start(vl, arg0); 802a60: 8d 55 10 lea 0x10(%ebp),%edx int argc=0; 802a63: b8 00 00 00 00 mov $0x0,%eax while(va_arg(vl, void *) != NULL) 802a68: eb 05 jmp 802a6f <spawnl+0x18> argc++; 802a6a: 83 c0 01 add $0x1,%eax while(va_arg(vl, void *) != NULL) 802a6d: 89 ca mov %ecx,%edx 802a6f: 8d 4a 04 lea 0x4(%edx),%ecx 802a72: 83 3a 00 cmpl $0x0,(%edx) 802a75: 75 f3 jne 802a6a <spawnl+0x13> const char *argv[argc+2]; 802a77: 8d 14 85 1a 00 00 00 lea 0x1a(,%eax,4),%edx 802a7e: 83 e2 f0 and $0xfffffff0,%edx 802a81: 29 d4 sub %edx,%esp 802a83: 8d 54 24 03 lea 0x3(%esp),%edx 802a87: c1 ea 02 shr $0x2,%edx 802a8a: 8d 34 95 00 00 00 00 lea 0x0(,%edx,4),%esi 802a91: 89 f3 mov %esi,%ebx argv[0] = arg0; 802a93: 8b 4d 0c mov 0xc(%ebp),%ecx 802a96: 89 0c 95 00 00 00 00 mov %ecx,0x0(,%edx,4) argv[argc+1] = NULL; 802a9d: c7 44 86 04 00 00 00 movl $0x0,0x4(%esi,%eax,4) 802aa4: 00 va_start(vl, arg0); 802aa5: 8d 4d 10 lea 0x10(%ebp),%ecx 802aa8: 89 c2 mov %eax,%edx for(i=0;i<argc;i++) 802aaa: b8 00 00 00 00 mov $0x0,%eax 802aaf: eb 0b jmp 802abc <spawnl+0x65> argv[i+1] = va_arg(vl, const char *); 802ab1: 83 c0 01 add $0x1,%eax 802ab4: 8b 39 mov (%ecx),%edi 802ab6: 89 3c 83 mov %edi,(%ebx,%eax,4) 802ab9: 8d 49 04 lea 0x4(%ecx),%ecx for(i=0;i<argc;i++) 802abc: 39 d0 cmp %edx,%eax 802abe: 75 f1 jne 802ab1 <spawnl+0x5a> return spawn(prog, argv); 802ac0: 83 ec 08 sub $0x8,%esp 802ac3: 56 push %esi 802ac4: ff 75 08 pushl 0x8(%ebp) 802ac7: e8 9a fa ff ff call 802566 <spawn> } 802acc: 8d 65 f4 lea -0xc(%ebp),%esp 802acf: 5b pop %ebx 802ad0: 5e pop %esi 802ad1: 5f pop %edi 802ad2: 5d pop %ebp 802ad3: c3 ret 00802ad4 <devpipe_stat>: return i; } static int devpipe_stat(struct Fd *fd, struct Stat *stat) { 802ad4: 55 push %ebp 802ad5: 89 e5 mov %esp,%ebp 802ad7: 56 push %esi 802ad8: 53 push %ebx 802ad9: 8b 5d 0c mov 0xc(%ebp),%ebx struct Pipe *p = (struct Pipe*) fd2data(fd); 802adc: 83 ec 0c sub $0xc,%esp 802adf: ff 75 08 pushl 0x8(%ebp) 802ae2: e8 40 f1 ff ff call 801c27 <fd2data> 802ae7: 89 c6 mov %eax,%esi strcpy(stat->st_name, "<pipe>"); 802ae9: 83 c4 08 add $0x8,%esp 802aec: 68 ae 39 80 00 push $0x8039ae 802af1: 53 push %ebx 802af2: e8 26 e7 ff ff call 80121d <strcpy> stat->st_size = p->p_wpos - p->p_rpos; 802af7: 8b 46 04 mov 0x4(%esi),%eax 802afa: 2b 06 sub (%esi),%eax 802afc: 89 83 80 00 00 00 mov %eax,0x80(%ebx) stat->st_isdir = 0; 802b02: c7 83 84 00 00 00 00 movl $0x0,0x84(%ebx) 802b09: 00 00 00 stat->st_dev = &devpipe; 802b0c: c7 83 88 00 00 00 3c movl $0x80403c,0x88(%ebx) 802b13: 40 80 00 return 0; } 802b16: b8 00 00 00 00 mov $0x0,%eax 802b1b: 8d 65 f8 lea -0x8(%ebp),%esp 802b1e: 5b pop %ebx 802b1f: 5e pop %esi 802b20: 5d pop %ebp 802b21: c3 ret 00802b22 <devpipe_close>: static int devpipe_close(struct Fd *fd) { 802b22: 55 push %ebp 802b23: 89 e5 mov %esp,%ebp 802b25: 53 push %ebx 802b26: 83 ec 0c sub $0xc,%esp 802b29: 8b 5d 08 mov 0x8(%ebp),%ebx (void) sys_page_unmap(0, fd); 802b2c: 53 push %ebx 802b2d: 6a 00 push $0x0 802b2f: e8 67 eb ff ff call 80169b <sys_page_unmap> return sys_page_unmap(0, fd2data(fd)); 802b34: 89 1c 24 mov %ebx,(%esp) 802b37: e8 eb f0 ff ff call 801c27 <fd2data> 802b3c: 83 c4 08 add $0x8,%esp 802b3f: 50 push %eax 802b40: 6a 00 push $0x0 802b42: e8 54 eb ff ff call 80169b <sys_page_unmap> } 802b47: 8b 5d fc mov -0x4(%ebp),%ebx 802b4a: c9 leave 802b4b: c3 ret 00802b4c <_pipeisclosed>: { 802b4c: 55 push %ebp 802b4d: 89 e5 mov %esp,%ebp 802b4f: 57 push %edi 802b50: 56 push %esi 802b51: 53 push %ebx 802b52: 83 ec 1c sub $0x1c,%esp 802b55: 89 c7 mov %eax,%edi 802b57: 89 d6 mov %edx,%esi n = thisenv->env_runs; 802b59: a1 24 54 80 00 mov 0x805424,%eax 802b5e: 8b 58 58 mov 0x58(%eax),%ebx ret = pageref(fd) == pageref(p); 802b61: 83 ec 0c sub $0xc,%esp 802b64: 57 push %edi 802b65: e8 79 04 00 00 call 802fe3 <pageref> 802b6a: 89 45 e4 mov %eax,-0x1c(%ebp) 802b6d: 89 34 24 mov %esi,(%esp) 802b70: e8 6e 04 00 00 call 802fe3 <pageref> nn = thisenv->env_runs; 802b75: 8b 15 24 54 80 00 mov 0x805424,%edx 802b7b: 8b 4a 58 mov 0x58(%edx),%ecx if (n == nn) 802b7e: 83 c4 10 add $0x10,%esp 802b81: 39 cb cmp %ecx,%ebx 802b83: 74 1b je 802ba0 <_pipeisclosed+0x54> if (n != nn && ret == 1) 802b85: 39 45 e4 cmp %eax,-0x1c(%ebp) 802b88: 75 cf jne 802b59 <_pipeisclosed+0xd> cprintf("pipe race avoided\n", n, thisenv->env_runs, ret); 802b8a: 8b 42 58 mov 0x58(%edx),%eax 802b8d: 6a 01 push $0x1 802b8f: 50 push %eax 802b90: 53 push %ebx 802b91: 68 b5 39 80 00 push $0x8039b5 802b96: e8 73 df ff ff call 800b0e <cprintf> 802b9b: 83 c4 10 add $0x10,%esp 802b9e: eb b9 jmp 802b59 <_pipeisclosed+0xd> ret = pageref(fd) == pageref(p); 802ba0: 39 45 e4 cmp %eax,-0x1c(%ebp) 802ba3: 0f 94 c0 sete %al 802ba6: 0f b6 c0 movzbl %al,%eax } 802ba9: 8d 65 f4 lea -0xc(%ebp),%esp 802bac: 5b pop %ebx 802bad: 5e pop %esi 802bae: 5f pop %edi 802baf: 5d pop %ebp 802bb0: c3 ret 00802bb1 <devpipe_write>: { 802bb1: 55 push %ebp 802bb2: 89 e5 mov %esp,%ebp 802bb4: 57 push %edi 802bb5: 56 push %esi 802bb6: 53 push %ebx 802bb7: 83 ec 28 sub $0x28,%esp 802bba: 8b 75 08 mov 0x8(%ebp),%esi p = (struct Pipe*) fd2data(fd); 802bbd: 56 push %esi 802bbe: e8 64 f0 ff ff call 801c27 <fd2data> 802bc3: 89 c3 mov %eax,%ebx for (i = 0; i < n; i++) { 802bc5: 83 c4 10 add $0x10,%esp 802bc8: bf 00 00 00 00 mov $0x0,%edi 802bcd: 3b 7d 10 cmp 0x10(%ebp),%edi 802bd0: 74 4f je 802c21 <devpipe_write+0x70> while (p->p_wpos >= p->p_rpos + sizeof(p->p_buf)) { 802bd2: 8b 43 04 mov 0x4(%ebx),%eax 802bd5: 8b 0b mov (%ebx),%ecx 802bd7: 8d 51 20 lea 0x20(%ecx),%edx 802bda: 39 d0 cmp %edx,%eax 802bdc: 72 14 jb 802bf2 <devpipe_write+0x41> if (_pipeisclosed(fd, p)) 802bde: 89 da mov %ebx,%edx 802be0: 89 f0 mov %esi,%eax 802be2: e8 65 ff ff ff call 802b4c <_pipeisclosed> 802be7: 85 c0 test %eax,%eax 802be9: 75 3a jne 802c25 <devpipe_write+0x74> sys_yield(); 802beb: e8 07 ea ff ff call 8015f7 <sys_yield> 802bf0: eb e0 jmp 802bd2 <devpipe_write+0x21> p->p_buf[p->p_wpos % PIPEBUFSIZ] = buf[i]; 802bf2: 8b 4d 0c mov 0xc(%ebp),%ecx 802bf5: 0f b6 0c 39 movzbl (%ecx,%edi,1),%ecx 802bf9: 88 4d e7 mov %cl,-0x19(%ebp) 802bfc: 89 c2 mov %eax,%edx 802bfe: c1 fa 1f sar $0x1f,%edx 802c01: 89 d1 mov %edx,%ecx 802c03: c1 e9 1b shr $0x1b,%ecx 802c06: 8d 14 08 lea (%eax,%ecx,1),%edx 802c09: 83 e2 1f and $0x1f,%edx 802c0c: 29 ca sub %ecx,%edx 802c0e: 0f b6 4d e7 movzbl -0x19(%ebp),%ecx 802c12: 88 4c 13 08 mov %cl,0x8(%ebx,%edx,1) p->p_wpos++; 802c16: 83 c0 01 add $0x1,%eax 802c19: 89 43 04 mov %eax,0x4(%ebx) for (i = 0; i < n; i++) { 802c1c: 83 c7 01 add $0x1,%edi 802c1f: eb ac jmp 802bcd <devpipe_write+0x1c> return i; 802c21: 89 f8 mov %edi,%eax 802c23: eb 05 jmp 802c2a <devpipe_write+0x79> return 0; 802c25: b8 00 00 00 00 mov $0x0,%eax } 802c2a: 8d 65 f4 lea -0xc(%ebp),%esp 802c2d: 5b pop %ebx 802c2e: 5e pop %esi 802c2f: 5f pop %edi 802c30: 5d pop %ebp 802c31: c3 ret 00802c32 <devpipe_read>: { 802c32: 55 push %ebp 802c33: 89 e5 mov %esp,%ebp 802c35: 57 push %edi 802c36: 56 push %esi 802c37: 53 push %ebx 802c38: 83 ec 18 sub $0x18,%esp 802c3b: 8b 7d 08 mov 0x8(%ebp),%edi p = (struct Pipe*)fd2data(fd); 802c3e: 57 push %edi 802c3f: e8 e3 ef ff ff call 801c27 <fd2data> 802c44: 89 c3 mov %eax,%ebx for (i = 0; i < n; i++) { 802c46: 83 c4 10 add $0x10,%esp 802c49: be 00 00 00 00 mov $0x0,%esi 802c4e: 3b 75 10 cmp 0x10(%ebp),%esi 802c51: 74 47 je 802c9a <devpipe_read+0x68> while (p->p_rpos == p->p_wpos) { 802c53: 8b 03 mov (%ebx),%eax 802c55: 3b 43 04 cmp 0x4(%ebx),%eax 802c58: 75 22 jne 802c7c <devpipe_read+0x4a> if (i > 0) 802c5a: 85 f6 test %esi,%esi 802c5c: 75 14 jne 802c72 <devpipe_read+0x40> if (_pipeisclosed(fd, p)) 802c5e: 89 da mov %ebx,%edx 802c60: 89 f8 mov %edi,%eax 802c62: e8 e5 fe ff ff call 802b4c <_pipeisclosed> 802c67: 85 c0 test %eax,%eax 802c69: 75 33 jne 802c9e <devpipe_read+0x6c> sys_yield(); 802c6b: e8 87 e9 ff ff call 8015f7 <sys_yield> 802c70: eb e1 jmp 802c53 <devpipe_read+0x21> return i; 802c72: 89 f0 mov %esi,%eax } 802c74: 8d 65 f4 lea -0xc(%ebp),%esp 802c77: 5b pop %ebx 802c78: 5e pop %esi 802c79: 5f pop %edi 802c7a: 5d pop %ebp 802c7b: c3 ret buf[i] = p->p_buf[p->p_rpos % PIPEBUFSIZ]; 802c7c: 99 cltd 802c7d: c1 ea 1b shr $0x1b,%edx 802c80: 01 d0 add %edx,%eax 802c82: 83 e0 1f and $0x1f,%eax 802c85: 29 d0 sub %edx,%eax 802c87: 0f b6 44 03 08 movzbl 0x8(%ebx,%eax,1),%eax 802c8c: 8b 4d 0c mov 0xc(%ebp),%ecx 802c8f: 88 04 31 mov %al,(%ecx,%esi,1) p->p_rpos++; 802c92: 83 03 01 addl $0x1,(%ebx) for (i = 0; i < n; i++) { 802c95: 83 c6 01 add $0x1,%esi 802c98: eb b4 jmp 802c4e <devpipe_read+0x1c> return i; 802c9a: 89 f0 mov %esi,%eax 802c9c: eb d6 jmp 802c74 <devpipe_read+0x42> return 0; 802c9e: b8 00 00 00 00 mov $0x0,%eax 802ca3: eb cf jmp 802c74 <devpipe_read+0x42> 00802ca5 <pipe>: { 802ca5: 55 push %ebp 802ca6: 89 e5 mov %esp,%ebp 802ca8: 56 push %esi 802ca9: 53 push %ebx 802caa: 83 ec 1c sub $0x1c,%esp if ((r = fd_alloc(&fd0)) < 0 802cad: 8d 45 f4 lea -0xc(%ebp),%eax 802cb0: 50 push %eax 802cb1: e8 88 ef ff ff call 801c3e <fd_alloc> 802cb6: 89 c3 mov %eax,%ebx 802cb8: 83 c4 10 add $0x10,%esp 802cbb: 85 c0 test %eax,%eax 802cbd: 78 5b js 802d1a <pipe+0x75> || (r = sys_page_alloc(0, fd0, PTE_P|PTE_W|PTE_U|PTE_SHARE)) < 0) 802cbf: 83 ec 04 sub $0x4,%esp 802cc2: 68 07 04 00 00 push $0x407 802cc7: ff 75 f4 pushl -0xc(%ebp) 802cca: 6a 00 push $0x0 802ccc: e8 45 e9 ff ff call 801616 <sys_page_alloc> 802cd1: 89 c3 mov %eax,%ebx 802cd3: 83 c4 10 add $0x10,%esp 802cd6: 85 c0 test %eax,%eax 802cd8: 78 40 js 802d1a <pipe+0x75> if ((r = fd_alloc(&fd1)) < 0 802cda: 83 ec 0c sub $0xc,%esp 802cdd: 8d 45 f0 lea -0x10(%ebp),%eax 802ce0: 50 push %eax 802ce1: e8 58 ef ff ff call 801c3e <fd_alloc> 802ce6: 89 c3 mov %eax,%ebx 802ce8: 83 c4 10 add $0x10,%esp 802ceb: 85 c0 test %eax,%eax 802ced: 78 1b js 802d0a <pipe+0x65> || (r = sys_page_alloc(0, fd1, PTE_P|PTE_W|PTE_U|PTE_SHARE)) < 0) 802cef: 83 ec 04 sub $0x4,%esp 802cf2: 68 07 04 00 00 push $0x407 802cf7: ff 75 f0 pushl -0x10(%ebp) 802cfa: 6a 00 push $0x0 802cfc: e8 15 e9 ff ff call 801616 <sys_page_alloc> 802d01: 89 c3 mov %eax,%ebx 802d03: 83 c4 10 add $0x10,%esp 802d06: 85 c0 test %eax,%eax 802d08: 79 19 jns 802d23 <pipe+0x7e> sys_page_unmap(0, fd0); 802d0a: 83 ec 08 sub $0x8,%esp 802d0d: ff 75 f4 pushl -0xc(%ebp) 802d10: 6a 00 push $0x0 802d12: e8 84 e9 ff ff call 80169b <sys_page_unmap> 802d17: 83 c4 10 add $0x10,%esp } 802d1a: 89 d8 mov %ebx,%eax 802d1c: 8d 65 f8 lea -0x8(%ebp),%esp 802d1f: 5b pop %ebx 802d20: 5e pop %esi 802d21: 5d pop %ebp 802d22: c3 ret va = fd2data(fd0); 802d23: 83 ec 0c sub $0xc,%esp 802d26: ff 75 f4 pushl -0xc(%ebp) 802d29: e8 f9 ee ff ff call 801c27 <fd2data> 802d2e: 89 c6 mov %eax,%esi if ((r = sys_page_alloc(0, va, PTE_P|PTE_W|PTE_U|PTE_SHARE)) < 0) 802d30: 83 c4 0c add $0xc,%esp 802d33: 68 07 04 00 00 push $0x407 802d38: 50 push %eax 802d39: 6a 00 push $0x0 802d3b: e8 d6 e8 ff ff call 801616 <sys_page_alloc> 802d40: 89 c3 mov %eax,%ebx 802d42: 83 c4 10 add $0x10,%esp 802d45: 85 c0 test %eax,%eax 802d47: 0f 88 8c 00 00 00 js 802dd9 <pipe+0x134> if ((r = sys_page_map(0, va, 0, fd2data(fd1), PTE_P|PTE_W|PTE_U|PTE_SHARE)) < 0) 802d4d: 83 ec 0c sub $0xc,%esp 802d50: ff 75 f0 pushl -0x10(%ebp) 802d53: e8 cf ee ff ff call 801c27 <fd2data> 802d58: c7 04 24 07 04 00 00 movl $0x407,(%esp) 802d5f: 50 push %eax 802d60: 6a 00 push $0x0 802d62: 56 push %esi 802d63: 6a 00 push $0x0 802d65: e8 ef e8 ff ff call 801659 <sys_page_map> 802d6a: 89 c3 mov %eax,%ebx 802d6c: 83 c4 20 add $0x20,%esp 802d6f: 85 c0 test %eax,%eax 802d71: 78 58 js 802dcb <pipe+0x126> fd0->fd_dev_id = devpipe.dev_id; 802d73: 8b 45 f4 mov -0xc(%ebp),%eax 802d76: 8b 15 3c 40 80 00 mov 0x80403c,%edx 802d7c: 89 10 mov %edx,(%eax) fd0->fd_omode = O_RDONLY; 802d7e: 8b 45 f4 mov -0xc(%ebp),%eax 802d81: c7 40 08 00 00 00 00 movl $0x0,0x8(%eax) fd1->fd_dev_id = devpipe.dev_id; 802d88: 8b 45 f0 mov -0x10(%ebp),%eax 802d8b: 8b 15 3c 40 80 00 mov 0x80403c,%edx 802d91: 89 10 mov %edx,(%eax) fd1->fd_omode = O_WRONLY; 802d93: 8b 45 f0 mov -0x10(%ebp),%eax 802d96: c7 40 08 01 00 00 00 movl $0x1,0x8(%eax) pfd[0] = fd2num(fd0); 802d9d: 83 ec 0c sub $0xc,%esp 802da0: ff 75 f4 pushl -0xc(%ebp) 802da3: e8 6f ee ff ff call 801c17 <fd2num> 802da8: 8b 4d 08 mov 0x8(%ebp),%ecx 802dab: 89 01 mov %eax,(%ecx) pfd[1] = fd2num(fd1); 802dad: 83 c4 04 add $0x4,%esp 802db0: ff 75 f0 pushl -0x10(%ebp) 802db3: e8 5f ee ff ff call 801c17 <fd2num> 802db8: 8b 4d 08 mov 0x8(%ebp),%ecx 802dbb: 89 41 04 mov %eax,0x4(%ecx) return 0; 802dbe: 83 c4 10 add $0x10,%esp 802dc1: bb 00 00 00 00 mov $0x0,%ebx 802dc6: e9 4f ff ff ff jmp 802d1a <pipe+0x75> sys_page_unmap(0, va); 802dcb: 83 ec 08 sub $0x8,%esp 802dce: 56 push %esi 802dcf: 6a 00 push $0x0 802dd1: e8 c5 e8 ff ff call 80169b <sys_page_unmap> 802dd6: 83 c4 10 add $0x10,%esp sys_page_unmap(0, fd1); 802dd9: 83 ec 08 sub $0x8,%esp 802ddc: ff 75 f0 pushl -0x10(%ebp) 802ddf: 6a 00 push $0x0 802de1: e8 b5 e8 ff ff call 80169b <sys_page_unmap> 802de6: 83 c4 10 add $0x10,%esp 802de9: e9 1c ff ff ff jmp 802d0a <pipe+0x65> 00802dee <pipeisclosed>: { 802dee: 55 push %ebp 802def: 89 e5 mov %esp,%ebp 802df1: 83 ec 20 sub $0x20,%esp if ((r = fd_lookup(fdnum, &fd)) < 0) 802df4: 8d 45 f4 lea -0xc(%ebp),%eax 802df7: 50 push %eax 802df8: ff 75 08 pushl 0x8(%ebp) 802dfb: e8 8d ee ff ff call 801c8d <fd_lookup> 802e00: 83 c4 10 add $0x10,%esp 802e03: 85 c0 test %eax,%eax 802e05: 78 18 js 802e1f <pipeisclosed+0x31> p = (struct Pipe*) fd2data(fd); 802e07: 83 ec 0c sub $0xc,%esp 802e0a: ff 75 f4 pushl -0xc(%ebp) 802e0d: e8 15 ee ff ff call 801c27 <fd2data> return _pipeisclosed(fd, p); 802e12: 89 c2 mov %eax,%edx 802e14: 8b 45 f4 mov -0xc(%ebp),%eax 802e17: e8 30 fd ff ff call 802b4c <_pipeisclosed> 802e1c: 83 c4 10 add $0x10,%esp } 802e1f: c9 leave 802e20: c3 ret 00802e21 <wait>: #include <inc/lib.h> // Waits until 'envid' exits. void wait(envid_t envid) { 802e21: 55 push %ebp 802e22: 89 e5 mov %esp,%ebp 802e24: 56 push %esi 802e25: 53 push %ebx 802e26: 8b 75 08 mov 0x8(%ebp),%esi const volatile struct Env *e; assert(envid != 0); 802e29: 85 f6 test %esi,%esi 802e2b: 74 13 je 802e40 <wait+0x1f> e = &envs[ENVX(envid)]; 802e2d: 89 f3 mov %esi,%ebx 802e2f: 81 e3 ff 03 00 00 and $0x3ff,%ebx while (e->env_id == envid && e->env_status != ENV_FREE) 802e35: 6b db 7c imul $0x7c,%ebx,%ebx 802e38: 81 c3 00 00 c0 ee add $0xeec00000,%ebx 802e3e: eb 1b jmp 802e5b <wait+0x3a> assert(envid != 0); 802e40: 68 cd 39 80 00 push $0x8039cd 802e45: 68 af 33 80 00 push $0x8033af 802e4a: 6a 09 push $0x9 802e4c: 68 d8 39 80 00 push $0x8039d8 802e51: e8 dd db ff ff call 800a33 <_panic> sys_yield(); 802e56: e8 9c e7 ff ff call 8015f7 <sys_yield> while (e->env_id == envid && e->env_status != ENV_FREE) 802e5b: 8b 43 48 mov 0x48(%ebx),%eax 802e5e: 39 f0 cmp %esi,%eax 802e60: 75 07 jne 802e69 <wait+0x48> 802e62: 8b 43 54 mov 0x54(%ebx),%eax 802e65: 85 c0 test %eax,%eax 802e67: 75 ed jne 802e56 <wait+0x35> } 802e69: 8d 65 f8 lea -0x8(%ebp),%esp 802e6c: 5b pop %ebx 802e6d: 5e pop %esi 802e6e: 5d pop %ebp 802e6f: c3 ret 00802e70 <set_pgfault_handler>: // at UXSTACKTOP), and tell the kernel to call the assembly-language // _pgfault_upcall routine when a page fault occurs. // void set_pgfault_handler(void (*handler)(struct UTrapframe *utf)) { 802e70: 55 push %ebp 802e71: 89 e5 mov %esp,%ebp 802e73: 83 ec 08 sub $0x8,%esp int r; if (_pgfault_handler == 0) { 802e76: 83 3d 00 70 80 00 00 cmpl $0x0,0x807000 802e7d: 74 0a je 802e89 <set_pgfault_handler+0x19> } sys_env_set_pgfault_upcall(0, _pgfault_upcall); //系统调用,设置进程的env_pgfault_upcall属性 } // Save handler pointer for assembly to call. _pgfault_handler = handler; 802e7f: 8b 45 08 mov 0x8(%ebp),%eax 802e82: a3 00 70 80 00 mov %eax,0x807000 } 802e87: c9 leave 802e88: c3 ret int r = sys_page_alloc(0, (void *)(UXSTACKTOP-PGSIZE), PTE_W | PTE_U | PTE_P); //为当前进程分配异常栈 802e89: 83 ec 04 sub $0x4,%esp 802e8c: 6a 07 push $0x7 802e8e: 68 00 f0 bf ee push $0xeebff000 802e93: 6a 00 push $0x0 802e95: e8 7c e7 ff ff call 801616 <sys_page_alloc> if (r < 0) { 802e9a: 83 c4 10 add $0x10,%esp 802e9d: 85 c0 test %eax,%eax 802e9f: 78 14 js 802eb5 <set_pgfault_handler+0x45> sys_env_set_pgfault_upcall(0, _pgfault_upcall); //系统调用,设置进程的env_pgfault_upcall属性 802ea1: 83 ec 08 sub $0x8,%esp 802ea4: 68 c9 2e 80 00 push $0x802ec9 802ea9: 6a 00 push $0x0 802eab: e8 b1 e8 ff ff call 801761 <sys_env_set_pgfault_upcall> 802eb0: 83 c4 10 add $0x10,%esp 802eb3: eb ca jmp 802e7f <set_pgfault_handler+0xf> panic("set_pgfault_handler:sys_page_alloc failed");; 802eb5: 83 ec 04 sub $0x4,%esp 802eb8: 68 e4 39 80 00 push $0x8039e4 802ebd: 6a 22 push $0x22 802ebf: 68 10 3a 80 00 push $0x803a10 802ec4: e8 6a db ff ff call 800a33 <_panic> 00802ec9 <_pgfault_upcall>: .text .globl _pgfault_upcall _pgfault_upcall: // Call the C page fault handler. pushl %esp // function argument: pointer to UTF 802ec9: 54 push %esp movl _pgfault_handler, %eax 802eca: a1 00 70 80 00 mov 0x807000,%eax call *%eax //调用页处理函数 802ecf: ff d0 call *%eax addl $4, %esp // pop function argument 802ed1: 83 c4 04 add $0x4,%esp // LAB 4: Your code here. // Restore the trap-time registers. After you do this, you // can no longer modify any general-purpose registers. // LAB 4: Your code here. addl $8, %esp //跳过utf_fault_va和utf_err 802ed4: 83 c4 08 add $0x8,%esp movl 40(%esp), %eax //保存中断发生时的esp到eax 802ed7: 8b 44 24 28 mov 0x28(%esp),%eax movl 32(%esp), %ecx //保存终端发生时的eip到ecx 802edb: 8b 4c 24 20 mov 0x20(%esp),%ecx movl %ecx, -4(%eax) //将中断发生时的esp值亚入到到原来的栈中 802edf: 89 48 fc mov %ecx,-0x4(%eax) popal 802ee2: 61 popa addl $4, %esp //跳过eip 802ee3: 83 c4 04 add $0x4,%esp // Restore eflags from the stack. After you do this, you can // no longer use arithmetic operations or anything else that // modifies eflags. // LAB 4: Your code here. popfl 802ee6: 9d popf // Switch back to the adjusted trap-time stack. // LAB 4: Your code here. popl %esp 802ee7: 5c pop %esp // Return to re-execute the instruction that faulted. // LAB 4: Your code here. lea -4(%esp), %esp //因为之前压入了eip的值但是没有减esp的值,所以现在需要将esp寄存器中的值减4 802ee8: 8d 64 24 fc lea -0x4(%esp),%esp 802eec: c3 ret 00802eed <ipc_recv>: // If 'pg' is null, pass sys_ipc_recv a value that it will understand // as meaning "no page". (Zero is not the right value, since that's // a perfectly valid place to map a page.) int32_t ipc_recv(envid_t *from_env_store, void *pg, int *perm_store) { 802eed: 55 push %ebp 802eee: 89 e5 mov %esp,%ebp 802ef0: 56 push %esi 802ef1: 53 push %ebx 802ef2: 8b 75 08 mov 0x8(%ebp),%esi 802ef5: 8b 45 0c mov 0xc(%ebp),%eax 802ef8: 8b 5d 10 mov 0x10(%ebp),%ebx // LAB 4: Your code here. if (pg == NULL) { 802efb: 85 c0 test %eax,%eax pg = (void *)-1; 802efd: ba ff ff ff ff mov $0xffffffff,%edx 802f02: 0f 44 c2 cmove %edx,%eax } int r = sys_ipc_recv(pg); 802f05: 83 ec 0c sub $0xc,%esp 802f08: 50 push %eax 802f09: e8 b8 e8 ff ff call 8017c6 <sys_ipc_recv> if (r < 0) { //系统调用失败 802f0e: 83 c4 10 add $0x10,%esp 802f11: 85 c0 test %eax,%eax 802f13: 78 2b js 802f40 <ipc_recv+0x53> if (from_env_store) *from_env_store = 0; if (perm_store) *perm_store = 0; return r; } if (from_env_store) 802f15: 85 f6 test %esi,%esi 802f17: 74 0a je 802f23 <ipc_recv+0x36> *from_env_store = thisenv->env_ipc_from; 802f19: a1 24 54 80 00 mov 0x805424,%eax 802f1e: 8b 40 74 mov 0x74(%eax),%eax 802f21: 89 06 mov %eax,(%esi) if (perm_store) 802f23: 85 db test %ebx,%ebx 802f25: 74 0a je 802f31 <ipc_recv+0x44> *perm_store = thisenv->env_ipc_perm; 802f27: a1 24 54 80 00 mov 0x805424,%eax 802f2c: 8b 40 78 mov 0x78(%eax),%eax 802f2f: 89 03 mov %eax,(%ebx) return thisenv->env_ipc_value; 802f31: a1 24 54 80 00 mov 0x805424,%eax 802f36: 8b 40 70 mov 0x70(%eax),%eax } 802f39: 8d 65 f8 lea -0x8(%ebp),%esp 802f3c: 5b pop %ebx 802f3d: 5e pop %esi 802f3e: 5d pop %ebp 802f3f: c3 ret if (from_env_store) *from_env_store = 0; 802f40: 85 f6 test %esi,%esi 802f42: 74 06 je 802f4a <ipc_recv+0x5d> 802f44: c7 06 00 00 00 00 movl $0x0,(%esi) if (perm_store) *perm_store = 0; 802f4a: 85 db test %ebx,%ebx 802f4c: 74 eb je 802f39 <ipc_recv+0x4c> 802f4e: c7 03 00 00 00 00 movl $0x0,(%ebx) 802f54: eb e3 jmp 802f39 <ipc_recv+0x4c> 00802f56 <ipc_send>: // Use sys_yield() to be CPU-friendly. // If 'pg' is null, pass sys_ipc_try_send a value that it will understand // as meaning "no page". (Zero is not the right value.) void ipc_send(envid_t to_env, uint32_t val, void *pg, int perm) { 802f56: 55 push %ebp 802f57: 89 e5 mov %esp,%ebp 802f59: 57 push %edi 802f5a: 56 push %esi 802f5b: 53 push %ebx 802f5c: 83 ec 0c sub $0xc,%esp 802f5f: 8b 7d 08 mov 0x8(%ebp),%edi 802f62: 8b 75 0c mov 0xc(%ebp),%esi 802f65: 8b 5d 10 mov 0x10(%ebp),%ebx // LAB 4: Your code here. if (pg == NULL) { 802f68: 85 db test %ebx,%ebx pg = (void *)-1; 802f6a: b8 ff ff ff ff mov $0xffffffff,%eax 802f6f: 0f 44 d8 cmove %eax,%ebx } int r; while(1) { r = sys_ipc_try_send(to_env, val, pg, perm); 802f72: ff 75 14 pushl 0x14(%ebp) 802f75: 53 push %ebx 802f76: 56 push %esi 802f77: 57 push %edi 802f78: e8 26 e8 ff ff call 8017a3 <sys_ipc_try_send> if (r == 0) { //发送成功 802f7d: 83 c4 10 add $0x10,%esp 802f80: 85 c0 test %eax,%eax 802f82: 74 1e je 802fa2 <ipc_send+0x4c> return; } else if (r == -E_IPC_NOT_RECV) { //接收进程没有准备好 802f84: 83 f8 f9 cmp $0xfffffff9,%eax 802f87: 75 07 jne 802f90 <ipc_send+0x3a> sys_yield(); 802f89: e8 69 e6 ff ff call 8015f7 <sys_yield> r = sys_ipc_try_send(to_env, val, pg, perm); 802f8e: eb e2 jmp 802f72 <ipc_send+0x1c> } else { //其它错误 panic("ipc_send():%e", r); 802f90: 50 push %eax 802f91: 68 1e 3a 80 00 push $0x803a1e 802f96: 6a 41 push $0x41 802f98: 68 2c 3a 80 00 push $0x803a2c 802f9d: e8 91 da ff ff call 800a33 <_panic> } } } 802fa2: 8d 65 f4 lea -0xc(%ebp),%esp 802fa5: 5b pop %ebx 802fa6: 5e pop %esi 802fa7: 5f pop %edi 802fa8: 5d pop %ebp 802fa9: c3 ret 00802faa <ipc_find_env>: // Find the first environment of the given type. We'll use this to // find special environments. // Returns 0 if no such environment exists. envid_t ipc_find_env(enum EnvType type) { 802faa: 55 push %ebp 802fab: 89 e5 mov %esp,%ebp 802fad: 8b 4d 08 mov 0x8(%ebp),%ecx int i; for (i = 0; i < NENV; i++) 802fb0: b8 00 00 00 00 mov $0x0,%eax if (envs[i].env_type == type) 802fb5: 6b d0 7c imul $0x7c,%eax,%edx 802fb8: 81 c2 00 00 c0 ee add $0xeec00000,%edx 802fbe: 8b 52 50 mov 0x50(%edx),%edx 802fc1: 39 ca cmp %ecx,%edx 802fc3: 74 11 je 802fd6 <ipc_find_env+0x2c> for (i = 0; i < NENV; i++) 802fc5: 83 c0 01 add $0x1,%eax 802fc8: 3d 00 04 00 00 cmp $0x400,%eax 802fcd: 75 e6 jne 802fb5 <ipc_find_env+0xb> return envs[i].env_id; return 0; 802fcf: b8 00 00 00 00 mov $0x0,%eax 802fd4: eb 0b jmp 802fe1 <ipc_find_env+0x37> return envs[i].env_id; 802fd6: 6b c0 7c imul $0x7c,%eax,%eax 802fd9: 05 00 00 c0 ee add $0xeec00000,%eax 802fde: 8b 40 48 mov 0x48(%eax),%eax } 802fe1: 5d pop %ebp 802fe2: c3 ret 00802fe3 <pageref>: #include <inc/lib.h> int pageref(void *v) { 802fe3: 55 push %ebp 802fe4: 89 e5 mov %esp,%ebp 802fe6: 8b 55 08 mov 0x8(%ebp),%edx pte_t pte; if (!(uvpd[PDX(v)] & PTE_P)) 802fe9: 89 d0 mov %edx,%eax 802feb: c1 e8 16 shr $0x16,%eax 802fee: 8b 0c 85 00 d0 7b ef mov -0x10843000(,%eax,4),%ecx return 0; 802ff5: b8 00 00 00 00 mov $0x0,%eax if (!(uvpd[PDX(v)] & PTE_P)) 802ffa: f6 c1 01 test $0x1,%cl 802ffd: 74 1d je 80301c <pageref+0x39> pte = uvpt[PGNUM(v)]; 802fff: c1 ea 0c shr $0xc,%edx 803002: 8b 14 95 00 00 40 ef mov -0x10c00000(,%edx,4),%edx if (!(pte & PTE_P)) 803009: f6 c2 01 test $0x1,%dl 80300c: 74 0e je 80301c <pageref+0x39> return 0; return pages[PGNUM(pte)].pp_ref; 80300e: c1 ea 0c shr $0xc,%edx 803011: 0f b7 04 d5 04 00 00 movzwl -0x10fffffc(,%edx,8),%eax 803018: ef 803019: 0f b7 c0 movzwl %ax,%eax } 80301c: 5d pop %ebp 80301d: c3 ret 80301e: 66 90 xchg %ax,%ax 00803020 <__udivdi3>: 803020: 55 push %ebp 803021: 57 push %edi 803022: 56 push %esi 803023: 53 push %ebx 803024: 83 ec 1c sub $0x1c,%esp 803027: 8b 54 24 3c mov 0x3c(%esp),%edx 80302b: 8b 6c 24 30 mov 0x30(%esp),%ebp 80302f: 8b 74 24 34 mov 0x34(%esp),%esi 803033: 8b 5c 24 38 mov 0x38(%esp),%ebx 803037: 85 d2 test %edx,%edx 803039: 75 35 jne 803070 <__udivdi3+0x50> 80303b: 39 f3 cmp %esi,%ebx 80303d: 0f 87 bd 00 00 00 ja 803100 <__udivdi3+0xe0> 803043: 85 db test %ebx,%ebx 803045: 89 d9 mov %ebx,%ecx 803047: 75 0b jne 803054 <__udivdi3+0x34> 803049: b8 01 00 00 00 mov $0x1,%eax 80304e: 31 d2 xor %edx,%edx 803050: f7 f3 div %ebx 803052: 89 c1 mov %eax,%ecx 803054: 31 d2 xor %edx,%edx 803056: 89 f0 mov %esi,%eax 803058: f7 f1 div %ecx 80305a: 89 c6 mov %eax,%esi 80305c: 89 e8 mov %ebp,%eax 80305e: 89 f7 mov %esi,%edi 803060: f7 f1 div %ecx 803062: 89 fa mov %edi,%edx 803064: 83 c4 1c add $0x1c,%esp 803067: 5b pop %ebx 803068: 5e pop %esi 803069: 5f pop %edi 80306a: 5d pop %ebp 80306b: c3 ret 80306c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 803070: 39 f2 cmp %esi,%edx 803072: 77 7c ja 8030f0 <__udivdi3+0xd0> 803074: 0f bd fa bsr %edx,%edi 803077: 83 f7 1f xor $0x1f,%edi 80307a: 0f 84 98 00 00 00 je 803118 <__udivdi3+0xf8> 803080: 89 f9 mov %edi,%ecx 803082: b8 20 00 00 00 mov $0x20,%eax 803087: 29 f8 sub %edi,%eax 803089: d3 e2 shl %cl,%edx 80308b: 89 54 24 08 mov %edx,0x8(%esp) 80308f: 89 c1 mov %eax,%ecx 803091: 89 da mov %ebx,%edx 803093: d3 ea shr %cl,%edx 803095: 8b 4c 24 08 mov 0x8(%esp),%ecx 803099: 09 d1 or %edx,%ecx 80309b: 89 f2 mov %esi,%edx 80309d: 89 4c 24 08 mov %ecx,0x8(%esp) 8030a1: 89 f9 mov %edi,%ecx 8030a3: d3 e3 shl %cl,%ebx 8030a5: 89 c1 mov %eax,%ecx 8030a7: d3 ea shr %cl,%edx 8030a9: 89 f9 mov %edi,%ecx 8030ab: 89 5c 24 0c mov %ebx,0xc(%esp) 8030af: d3 e6 shl %cl,%esi 8030b1: 89 eb mov %ebp,%ebx 8030b3: 89 c1 mov %eax,%ecx 8030b5: d3 eb shr %cl,%ebx 8030b7: 09 de or %ebx,%esi 8030b9: 89 f0 mov %esi,%eax 8030bb: f7 74 24 08 divl 0x8(%esp) 8030bf: 89 d6 mov %edx,%esi 8030c1: 89 c3 mov %eax,%ebx 8030c3: f7 64 24 0c mull 0xc(%esp) 8030c7: 39 d6 cmp %edx,%esi 8030c9: 72 0c jb 8030d7 <__udivdi3+0xb7> 8030cb: 89 f9 mov %edi,%ecx 8030cd: d3 e5 shl %cl,%ebp 8030cf: 39 c5 cmp %eax,%ebp 8030d1: 73 5d jae 803130 <__udivdi3+0x110> 8030d3: 39 d6 cmp %edx,%esi 8030d5: 75 59 jne 803130 <__udivdi3+0x110> 8030d7: 8d 43 ff lea -0x1(%ebx),%eax 8030da: 31 ff xor %edi,%edi 8030dc: 89 fa mov %edi,%edx 8030de: 83 c4 1c add $0x1c,%esp 8030e1: 5b pop %ebx 8030e2: 5e pop %esi 8030e3: 5f pop %edi 8030e4: 5d pop %ebp 8030e5: c3 ret 8030e6: 8d 76 00 lea 0x0(%esi),%esi 8030e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 8030f0: 31 ff xor %edi,%edi 8030f2: 31 c0 xor %eax,%eax 8030f4: 89 fa mov %edi,%edx 8030f6: 83 c4 1c add $0x1c,%esp 8030f9: 5b pop %ebx 8030fa: 5e pop %esi 8030fb: 5f pop %edi 8030fc: 5d pop %ebp 8030fd: c3 ret 8030fe: 66 90 xchg %ax,%ax 803100: 31 ff xor %edi,%edi 803102: 89 e8 mov %ebp,%eax 803104: 89 f2 mov %esi,%edx 803106: f7 f3 div %ebx 803108: 89 fa mov %edi,%edx 80310a: 83 c4 1c add $0x1c,%esp 80310d: 5b pop %ebx 80310e: 5e pop %esi 80310f: 5f pop %edi 803110: 5d pop %ebp 803111: c3 ret 803112: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 803118: 39 f2 cmp %esi,%edx 80311a: 72 06 jb 803122 <__udivdi3+0x102> 80311c: 31 c0 xor %eax,%eax 80311e: 39 eb cmp %ebp,%ebx 803120: 77 d2 ja 8030f4 <__udivdi3+0xd4> 803122: b8 01 00 00 00 mov $0x1,%eax 803127: eb cb jmp 8030f4 <__udivdi3+0xd4> 803129: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 803130: 89 d8 mov %ebx,%eax 803132: 31 ff xor %edi,%edi 803134: eb be jmp 8030f4 <__udivdi3+0xd4> 803136: 66 90 xchg %ax,%ax 803138: 66 90 xchg %ax,%ax 80313a: 66 90 xchg %ax,%ax 80313c: 66 90 xchg %ax,%ax 80313e: 66 90 xchg %ax,%ax 00803140 <__umoddi3>: 803140: 55 push %ebp 803141: 57 push %edi 803142: 56 push %esi 803143: 53 push %ebx 803144: 83 ec 1c sub $0x1c,%esp 803147: 8b 6c 24 3c mov 0x3c(%esp),%ebp 80314b: 8b 74 24 30 mov 0x30(%esp),%esi 80314f: 8b 5c 24 34 mov 0x34(%esp),%ebx 803153: 8b 7c 24 38 mov 0x38(%esp),%edi 803157: 85 ed test %ebp,%ebp 803159: 89 f0 mov %esi,%eax 80315b: 89 da mov %ebx,%edx 80315d: 75 19 jne 803178 <__umoddi3+0x38> 80315f: 39 df cmp %ebx,%edi 803161: 0f 86 b1 00 00 00 jbe 803218 <__umoddi3+0xd8> 803167: f7 f7 div %edi 803169: 89 d0 mov %edx,%eax 80316b: 31 d2 xor %edx,%edx 80316d: 83 c4 1c add $0x1c,%esp 803170: 5b pop %ebx 803171: 5e pop %esi 803172: 5f pop %edi 803173: 5d pop %ebp 803174: c3 ret 803175: 8d 76 00 lea 0x0(%esi),%esi 803178: 39 dd cmp %ebx,%ebp 80317a: 77 f1 ja 80316d <__umoddi3+0x2d> 80317c: 0f bd cd bsr %ebp,%ecx 80317f: 83 f1 1f xor $0x1f,%ecx 803182: 89 4c 24 04 mov %ecx,0x4(%esp) 803186: 0f 84 b4 00 00 00 je 803240 <__umoddi3+0x100> 80318c: b8 20 00 00 00 mov $0x20,%eax 803191: 89 c2 mov %eax,%edx 803193: 8b 44 24 04 mov 0x4(%esp),%eax 803197: 29 c2 sub %eax,%edx 803199: 89 c1 mov %eax,%ecx 80319b: 89 f8 mov %edi,%eax 80319d: d3 e5 shl %cl,%ebp 80319f: 89 d1 mov %edx,%ecx 8031a1: 89 54 24 0c mov %edx,0xc(%esp) 8031a5: d3 e8 shr %cl,%eax 8031a7: 09 c5 or %eax,%ebp 8031a9: 8b 44 24 04 mov 0x4(%esp),%eax 8031ad: 89 c1 mov %eax,%ecx 8031af: d3 e7 shl %cl,%edi 8031b1: 89 d1 mov %edx,%ecx 8031b3: 89 7c 24 08 mov %edi,0x8(%esp) 8031b7: 89 df mov %ebx,%edi 8031b9: d3 ef shr %cl,%edi 8031bb: 89 c1 mov %eax,%ecx 8031bd: 89 f0 mov %esi,%eax 8031bf: d3 e3 shl %cl,%ebx 8031c1: 89 d1 mov %edx,%ecx 8031c3: 89 fa mov %edi,%edx 8031c5: d3 e8 shr %cl,%eax 8031c7: 0f b6 4c 24 04 movzbl 0x4(%esp),%ecx 8031cc: 09 d8 or %ebx,%eax 8031ce: f7 f5 div %ebp 8031d0: d3 e6 shl %cl,%esi 8031d2: 89 d1 mov %edx,%ecx 8031d4: f7 64 24 08 mull 0x8(%esp) 8031d8: 39 d1 cmp %edx,%ecx 8031da: 89 c3 mov %eax,%ebx 8031dc: 89 d7 mov %edx,%edi 8031de: 72 06 jb 8031e6 <__umoddi3+0xa6> 8031e0: 75 0e jne 8031f0 <__umoddi3+0xb0> 8031e2: 39 c6 cmp %eax,%esi 8031e4: 73 0a jae 8031f0 <__umoddi3+0xb0> 8031e6: 2b 44 24 08 sub 0x8(%esp),%eax 8031ea: 19 ea sbb %ebp,%edx 8031ec: 89 d7 mov %edx,%edi 8031ee: 89 c3 mov %eax,%ebx 8031f0: 89 ca mov %ecx,%edx 8031f2: 0f b6 4c 24 0c movzbl 0xc(%esp),%ecx 8031f7: 29 de sub %ebx,%esi 8031f9: 19 fa sbb %edi,%edx 8031fb: 8b 5c 24 04 mov 0x4(%esp),%ebx 8031ff: 89 d0 mov %edx,%eax 803201: d3 e0 shl %cl,%eax 803203: 89 d9 mov %ebx,%ecx 803205: d3 ee shr %cl,%esi 803207: d3 ea shr %cl,%edx 803209: 09 f0 or %esi,%eax 80320b: 83 c4 1c add $0x1c,%esp 80320e: 5b pop %ebx 80320f: 5e pop %esi 803210: 5f pop %edi 803211: 5d pop %ebp 803212: c3 ret 803213: 90 nop 803214: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 803218: 85 ff test %edi,%edi 80321a: 89 f9 mov %edi,%ecx 80321c: 75 0b jne 803229 <__umoddi3+0xe9> 80321e: b8 01 00 00 00 mov $0x1,%eax 803223: 31 d2 xor %edx,%edx 803225: f7 f7 div %edi 803227: 89 c1 mov %eax,%ecx 803229: 89 d8 mov %ebx,%eax 80322b: 31 d2 xor %edx,%edx 80322d: f7 f1 div %ecx 80322f: 89 f0 mov %esi,%eax 803231: f7 f1 div %ecx 803233: e9 31 ff ff ff jmp 803169 <__umoddi3+0x29> 803238: 90 nop 803239: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 803240: 39 dd cmp %ebx,%ebp 803242: 72 08 jb 80324c <__umoddi3+0x10c> 803244: 39 f7 cmp %esi,%edi 803246: 0f 87 21 ff ff ff ja 80316d <__umoddi3+0x2d> 80324c: 89 da mov %ebx,%edx 80324e: 89 f0 mov %esi,%eax 803250: 29 f8 sub %edi,%eax 803252: 19 ea sbb %ebp,%edx 803254: e9 14 ff ff ff jmp 80316d <__umoddi3+0x2d>
;***************************************************************************** ;* x86-optimized functions for hflip filter ;* ;* Copyright (C) 2017 Paul B Mahol ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* FFmpeg is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser General Public ;* License along with FFmpeg; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;***************************************************************************** %include "libavutil/x86/x86util.asm" SECTION_RODATA pb_flip_byte: db 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 pb_flip_short: db 14,15,12,13,10,11,8,9,6,7,4,5,2,3,0,1 SECTION .text ;%1 byte or short, %2 b or w, %3 size in byte (1 for byte, 2 for short) %macro HFLIP 3 cglobal hflip_%1, 3, 5, 3, src, dst, w, r, x VBROADCASTI128 m0, [pb_flip_%1] xor xq, xq %if %3 == 1 movsxdifnidn wq, wd %else ; short add wd, wd %endif mov rq, wq and rq, 2 * mmsize - 1 cmp wq, 2 * mmsize jl .loop1 sub wq, rq .loop0: neg xq %if mmsize == 32 vpermq m1, [srcq + xq - mmsize + %3], 0x4e; flip each lane at load vpermq m2, [srcq + xq - 2 * mmsize + %3], 0x4e; flip each lane at load %else movu m1, [srcq + xq - mmsize + %3] movu m2, [srcq + xq - 2 * mmsize + %3] %endif pshufb m1, m0 pshufb m2, m0 neg xq movu [dstq + xq ], m1 movu [dstq + xq + mmsize], m2 add xq, mmsize * 2 cmp xq, wq jl .loop0 cmp rq, 0 je .end add wq, rq .loop1: neg xq mov r%2, [srcq + xq] neg xq mov [dstq + xq], r%2 add xq, %3 cmp xq, wq jl .loop1 .end: RET %endmacro INIT_XMM ssse3 HFLIP byte, b, 1 HFLIP short, w, 2 %if HAVE_AVX2_EXTERNAL INIT_YMM avx2 HFLIP byte, b, 1 HFLIP short, w, 2 %endif
;CodeVisionAVR C Compiler V3.12 Advanced ;(C) Copyright 1998-2014 Pavel Haiduc, HP InfoTech s.r.l. ;http://www.hpinfotech.com ;Build configuration : Debug ;Chip type : ATmega32 ;Program type : Application ;Clock frequency : 8.000000 MHz ;Memory model : Small ;Optimize for : Size ;(s)printf features : int, width ;(s)scanf features : int, width ;External RAM size : 0 ;Data Stack size : 512 byte(s) ;Heap size : 0 byte(s) ;Promote 'char' to 'int': Yes ;'char' is unsigned : Yes ;8 bit enums : Yes ;Global 'const' stored in FLASH: Yes ;Enhanced function parameter passing: Yes ;Enhanced core instructions: On ;Automatic register allocation for global variables: On ;Smart register allocation: On #define _MODEL_SMALL_ #pragma AVRPART ADMIN PART_NAME ATmega32 #pragma AVRPART MEMORY PROG_FLASH 32768 #pragma AVRPART MEMORY EEPROM 1024 #pragma AVRPART MEMORY INT_SRAM SIZE 2048 #pragma AVRPART MEMORY INT_SRAM START_ADDR 0x60 #define CALL_SUPPORTED 1 .LISTMAC .EQU UDRE=0x5 .EQU RXC=0x7 .EQU USR=0xB .EQU UDR=0xC .EQU SPSR=0xE .EQU SPDR=0xF .EQU EERE=0x0 .EQU EEWE=0x1 .EQU EEMWE=0x2 .EQU EECR=0x1C .EQU EEDR=0x1D .EQU EEARL=0x1E .EQU EEARH=0x1F .EQU WDTCR=0x21 .EQU MCUCR=0x35 .EQU GICR=0x3B .EQU SPL=0x3D .EQU SPH=0x3E .EQU SREG=0x3F .DEF R0X0=R0 .DEF R0X1=R1 .DEF R0X2=R2 .DEF R0X3=R3 .DEF R0X4=R4 .DEF R0X5=R5 .DEF R0X6=R6 .DEF R0X7=R7 .DEF R0X8=R8 .DEF R0X9=R9 .DEF R0XA=R10 .DEF R0XB=R11 .DEF R0XC=R12 .DEF R0XD=R13 .DEF R0XE=R14 .DEF R0XF=R15 .DEF R0X10=R16 .DEF R0X11=R17 .DEF R0X12=R18 .DEF R0X13=R19 .DEF R0X14=R20 .DEF R0X15=R21 .DEF R0X16=R22 .DEF R0X17=R23 .DEF R0X18=R24 .DEF R0X19=R25 .DEF R0X1A=R26 .DEF R0X1B=R27 .DEF R0X1C=R28 .DEF R0X1D=R29 .DEF R0X1E=R30 .DEF R0X1F=R31 .EQU __SRAM_START=0x0060 .EQU __SRAM_END=0x085F .EQU __DSTACK_SIZE=0x0200 .EQU __HEAP_SIZE=0x0000 .EQU __CLEAR_SRAM_SIZE=__SRAM_END-__SRAM_START+1 .MACRO __CPD1N CPI R30,LOW(@0) LDI R26,HIGH(@0) CPC R31,R26 LDI R26,BYTE3(@0) CPC R22,R26 LDI R26,BYTE4(@0) CPC R23,R26 .ENDM .MACRO __CPD2N CPI R26,LOW(@0) LDI R30,HIGH(@0) CPC R27,R30 LDI R30,BYTE3(@0) CPC R24,R30 LDI R30,BYTE4(@0) CPC R25,R30 .ENDM .MACRO __CPWRR CP R@0,R@2 CPC R@1,R@3 .ENDM .MACRO __CPWRN CPI R@0,LOW(@2) LDI R30,HIGH(@2) CPC R@1,R30 .ENDM .MACRO __ADDB1MN SUBI R30,LOW(-@0-(@1)) .ENDM .MACRO __ADDB2MN SUBI R26,LOW(-@0-(@1)) .ENDM .MACRO __ADDW1MN SUBI R30,LOW(-@0-(@1)) SBCI R31,HIGH(-@0-(@1)) .ENDM .MACRO __ADDW2MN SUBI R26,LOW(-@0-(@1)) SBCI R27,HIGH(-@0-(@1)) .ENDM .MACRO __ADDW1FN SUBI R30,LOW(-2*@0-(@1)) SBCI R31,HIGH(-2*@0-(@1)) .ENDM .MACRO __ADDD1FN SUBI R30,LOW(-2*@0-(@1)) SBCI R31,HIGH(-2*@0-(@1)) SBCI R22,BYTE3(-2*@0-(@1)) .ENDM .MACRO __ADDD1N SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) SBCI R22,BYTE3(-@0) SBCI R23,BYTE4(-@0) .ENDM .MACRO __ADDD2N SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) SBCI R24,BYTE3(-@0) SBCI R25,BYTE4(-@0) .ENDM .MACRO __SUBD1N SUBI R30,LOW(@0) SBCI R31,HIGH(@0) SBCI R22,BYTE3(@0) SBCI R23,BYTE4(@0) .ENDM .MACRO __SUBD2N SUBI R26,LOW(@0) SBCI R27,HIGH(@0) SBCI R24,BYTE3(@0) SBCI R25,BYTE4(@0) .ENDM .MACRO __ANDBMNN LDS R30,@0+(@1) ANDI R30,LOW(@2) STS @0+(@1),R30 .ENDM .MACRO __ANDWMNN LDS R30,@0+(@1) ANDI R30,LOW(@2) STS @0+(@1),R30 LDS R30,@0+(@1)+1 ANDI R30,HIGH(@2) STS @0+(@1)+1,R30 .ENDM .MACRO __ANDD1N ANDI R30,LOW(@0) ANDI R31,HIGH(@0) ANDI R22,BYTE3(@0) ANDI R23,BYTE4(@0) .ENDM .MACRO __ANDD2N ANDI R26,LOW(@0) ANDI R27,HIGH(@0) ANDI R24,BYTE3(@0) ANDI R25,BYTE4(@0) .ENDM .MACRO __ORBMNN LDS R30,@0+(@1) ORI R30,LOW(@2) STS @0+(@1),R30 .ENDM .MACRO __ORWMNN LDS R30,@0+(@1) ORI R30,LOW(@2) STS @0+(@1),R30 LDS R30,@0+(@1)+1 ORI R30,HIGH(@2) STS @0+(@1)+1,R30 .ENDM .MACRO __ORD1N ORI R30,LOW(@0) ORI R31,HIGH(@0) ORI R22,BYTE3(@0) ORI R23,BYTE4(@0) .ENDM .MACRO __ORD2N ORI R26,LOW(@0) ORI R27,HIGH(@0) ORI R24,BYTE3(@0) ORI R25,BYTE4(@0) .ENDM .MACRO __DELAY_USB LDI R24,LOW(@0) __DELAY_USB_LOOP: DEC R24 BRNE __DELAY_USB_LOOP .ENDM .MACRO __DELAY_USW LDI R24,LOW(@0) LDI R25,HIGH(@0) __DELAY_USW_LOOP: SBIW R24,1 BRNE __DELAY_USW_LOOP .ENDM .MACRO __GETD1S LDD R30,Y+@0 LDD R31,Y+@0+1 LDD R22,Y+@0+2 LDD R23,Y+@0+3 .ENDM .MACRO __GETD2S LDD R26,Y+@0 LDD R27,Y+@0+1 LDD R24,Y+@0+2 LDD R25,Y+@0+3 .ENDM .MACRO __PUTD1S STD Y+@0,R30 STD Y+@0+1,R31 STD Y+@0+2,R22 STD Y+@0+3,R23 .ENDM .MACRO __PUTD2S STD Y+@0,R26 STD Y+@0+1,R27 STD Y+@0+2,R24 STD Y+@0+3,R25 .ENDM .MACRO __PUTDZ2 STD Z+@0,R26 STD Z+@0+1,R27 STD Z+@0+2,R24 STD Z+@0+3,R25 .ENDM .MACRO __CLRD1S STD Y+@0,R30 STD Y+@0+1,R30 STD Y+@0+2,R30 STD Y+@0+3,R30 .ENDM .MACRO __POINTB1MN LDI R30,LOW(@0+(@1)) .ENDM .MACRO __POINTW1MN LDI R30,LOW(@0+(@1)) LDI R31,HIGH(@0+(@1)) .ENDM .MACRO __POINTD1M LDI R30,LOW(@0) LDI R31,HIGH(@0) LDI R22,BYTE3(@0) LDI R23,BYTE4(@0) .ENDM .MACRO __POINTW1FN LDI R30,LOW(2*@0+(@1)) LDI R31,HIGH(2*@0+(@1)) .ENDM .MACRO __POINTD1FN LDI R30,LOW(2*@0+(@1)) LDI R31,HIGH(2*@0+(@1)) LDI R22,BYTE3(2*@0+(@1)) LDI R23,BYTE4(2*@0+(@1)) .ENDM .MACRO __POINTB2MN LDI R26,LOW(@0+(@1)) .ENDM .MACRO __POINTW2MN LDI R26,LOW(@0+(@1)) LDI R27,HIGH(@0+(@1)) .ENDM .MACRO __POINTW2FN LDI R26,LOW(2*@0+(@1)) LDI R27,HIGH(2*@0+(@1)) .ENDM .MACRO __POINTD2FN LDI R26,LOW(2*@0+(@1)) LDI R27,HIGH(2*@0+(@1)) LDI R24,BYTE3(2*@0+(@1)) LDI R25,BYTE4(2*@0+(@1)) .ENDM .MACRO __POINTBRM LDI R@0,LOW(@1) .ENDM .MACRO __POINTWRM LDI R@0,LOW(@2) LDI R@1,HIGH(@2) .ENDM .MACRO __POINTBRMN LDI R@0,LOW(@1+(@2)) .ENDM .MACRO __POINTWRMN LDI R@0,LOW(@2+(@3)) LDI R@1,HIGH(@2+(@3)) .ENDM .MACRO __POINTWRFN LDI R@0,LOW(@2*2+(@3)) LDI R@1,HIGH(@2*2+(@3)) .ENDM .MACRO __GETD1N LDI R30,LOW(@0) LDI R31,HIGH(@0) LDI R22,BYTE3(@0) LDI R23,BYTE4(@0) .ENDM .MACRO __GETD2N LDI R26,LOW(@0) LDI R27,HIGH(@0) LDI R24,BYTE3(@0) LDI R25,BYTE4(@0) .ENDM .MACRO __GETB1MN LDS R30,@0+(@1) .ENDM .MACRO __GETB1HMN LDS R31,@0+(@1) .ENDM .MACRO __GETW1MN LDS R30,@0+(@1) LDS R31,@0+(@1)+1 .ENDM .MACRO __GETD1MN LDS R30,@0+(@1) LDS R31,@0+(@1)+1 LDS R22,@0+(@1)+2 LDS R23,@0+(@1)+3 .ENDM .MACRO __GETBRMN LDS R@0,@1+(@2) .ENDM .MACRO __GETWRMN LDS R@0,@2+(@3) LDS R@1,@2+(@3)+1 .ENDM .MACRO __GETWRZ LDD R@0,Z+@2 LDD R@1,Z+@2+1 .ENDM .MACRO __GETD2Z LDD R26,Z+@0 LDD R27,Z+@0+1 LDD R24,Z+@0+2 LDD R25,Z+@0+3 .ENDM .MACRO __GETB2MN LDS R26,@0+(@1) .ENDM .MACRO __GETW2MN LDS R26,@0+(@1) LDS R27,@0+(@1)+1 .ENDM .MACRO __GETD2MN LDS R26,@0+(@1) LDS R27,@0+(@1)+1 LDS R24,@0+(@1)+2 LDS R25,@0+(@1)+3 .ENDM .MACRO __PUTB1MN STS @0+(@1),R30 .ENDM .MACRO __PUTW1MN STS @0+(@1),R30 STS @0+(@1)+1,R31 .ENDM .MACRO __PUTD1MN STS @0+(@1),R30 STS @0+(@1)+1,R31 STS @0+(@1)+2,R22 STS @0+(@1)+3,R23 .ENDM .MACRO __PUTB1EN LDI R26,LOW(@0+(@1)) LDI R27,HIGH(@0+(@1)) CALL __EEPROMWRB .ENDM .MACRO __PUTW1EN LDI R26,LOW(@0+(@1)) LDI R27,HIGH(@0+(@1)) CALL __EEPROMWRW .ENDM .MACRO __PUTD1EN LDI R26,LOW(@0+(@1)) LDI R27,HIGH(@0+(@1)) CALL __EEPROMWRD .ENDM .MACRO __PUTBR0MN STS @0+(@1),R0 .ENDM .MACRO __PUTBMRN STS @0+(@1),R@2 .ENDM .MACRO __PUTWMRN STS @0+(@1),R@2 STS @0+(@1)+1,R@3 .ENDM .MACRO __PUTBZR STD Z+@1,R@0 .ENDM .MACRO __PUTWZR STD Z+@2,R@0 STD Z+@2+1,R@1 .ENDM .MACRO __GETW1R MOV R30,R@0 MOV R31,R@1 .ENDM .MACRO __GETW2R MOV R26,R@0 MOV R27,R@1 .ENDM .MACRO __GETWRN LDI R@0,LOW(@2) LDI R@1,HIGH(@2) .ENDM .MACRO __PUTW1R MOV R@0,R30 MOV R@1,R31 .ENDM .MACRO __PUTW2R MOV R@0,R26 MOV R@1,R27 .ENDM .MACRO __ADDWRN SUBI R@0,LOW(-@2) SBCI R@1,HIGH(-@2) .ENDM .MACRO __ADDWRR ADD R@0,R@2 ADC R@1,R@3 .ENDM .MACRO __SUBWRN SUBI R@0,LOW(@2) SBCI R@1,HIGH(@2) .ENDM .MACRO __SUBWRR SUB R@0,R@2 SBC R@1,R@3 .ENDM .MACRO __ANDWRN ANDI R@0,LOW(@2) ANDI R@1,HIGH(@2) .ENDM .MACRO __ANDWRR AND R@0,R@2 AND R@1,R@3 .ENDM .MACRO __ORWRN ORI R@0,LOW(@2) ORI R@1,HIGH(@2) .ENDM .MACRO __ORWRR OR R@0,R@2 OR R@1,R@3 .ENDM .MACRO __EORWRR EOR R@0,R@2 EOR R@1,R@3 .ENDM .MACRO __GETWRS LDD R@0,Y+@2 LDD R@1,Y+@2+1 .ENDM .MACRO __PUTBSR STD Y+@1,R@0 .ENDM .MACRO __PUTWSR STD Y+@2,R@0 STD Y+@2+1,R@1 .ENDM .MACRO __MOVEWRR MOV R@0,R@2 MOV R@1,R@3 .ENDM .MACRO __INWR IN R@0,@2 IN R@1,@2+1 .ENDM .MACRO __OUTWR OUT @2+1,R@1 OUT @2,R@0 .ENDM .MACRO __CALL1MN LDS R30,@0+(@1) LDS R31,@0+(@1)+1 ICALL .ENDM .MACRO __CALL1FN LDI R30,LOW(2*@0+(@1)) LDI R31,HIGH(2*@0+(@1)) CALL __GETW1PF ICALL .ENDM .MACRO __CALL2EN PUSH R26 PUSH R27 LDI R26,LOW(@0+(@1)) LDI R27,HIGH(@0+(@1)) CALL __EEPROMRDW POP R27 POP R26 ICALL .ENDM .MACRO __CALL2EX SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) CALL __EEPROMRDD ICALL .ENDM .MACRO __GETW1STACK IN R30,SPL IN R31,SPH ADIW R30,@0+1 LD R0,Z+ LD R31,Z MOV R30,R0 .ENDM .MACRO __GETD1STACK IN R30,SPL IN R31,SPH ADIW R30,@0+1 LD R0,Z+ LD R1,Z+ LD R22,Z MOVW R30,R0 .ENDM .MACRO __NBST BST R@0,@1 IN R30,SREG LDI R31,0x40 EOR R30,R31 OUT SREG,R30 .ENDM .MACRO __PUTB1SN LDD R26,Y+@0 LDD R27,Y+@0+1 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X,R30 .ENDM .MACRO __PUTW1SN LDD R26,Y+@0 LDD R27,Y+@0+1 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1SN LDD R26,Y+@0 LDD R27,Y+@0+1 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) CALL __PUTDP1 .ENDM .MACRO __PUTB1SNS LDD R26,Y+@0 LDD R27,Y+@0+1 ADIW R26,@1 ST X,R30 .ENDM .MACRO __PUTW1SNS LDD R26,Y+@0 LDD R27,Y+@0+1 ADIW R26,@1 ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1SNS LDD R26,Y+@0 LDD R27,Y+@0+1 ADIW R26,@1 CALL __PUTDP1 .ENDM .MACRO __PUTB1PMN LDS R26,@0 LDS R27,@0+1 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X,R30 .ENDM .MACRO __PUTW1PMN LDS R26,@0 LDS R27,@0+1 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1PMN LDS R26,@0 LDS R27,@0+1 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) CALL __PUTDP1 .ENDM .MACRO __PUTB1PMNS LDS R26,@0 LDS R27,@0+1 ADIW R26,@1 ST X,R30 .ENDM .MACRO __PUTW1PMNS LDS R26,@0 LDS R27,@0+1 ADIW R26,@1 ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1PMNS LDS R26,@0 LDS R27,@0+1 ADIW R26,@1 CALL __PUTDP1 .ENDM .MACRO __PUTB1RN MOVW R26,R@0 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X,R30 .ENDM .MACRO __PUTW1RN MOVW R26,R@0 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1RN MOVW R26,R@0 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) CALL __PUTDP1 .ENDM .MACRO __PUTB1RNS MOVW R26,R@0 ADIW R26,@1 ST X,R30 .ENDM .MACRO __PUTW1RNS MOVW R26,R@0 ADIW R26,@1 ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1RNS MOVW R26,R@0 ADIW R26,@1 CALL __PUTDP1 .ENDM .MACRO __PUTB1RON MOV R26,R@0 MOV R27,R@1 SUBI R26,LOW(-@2) SBCI R27,HIGH(-@2) ST X,R30 .ENDM .MACRO __PUTW1RON MOV R26,R@0 MOV R27,R@1 SUBI R26,LOW(-@2) SBCI R27,HIGH(-@2) ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1RON MOV R26,R@0 MOV R27,R@1 SUBI R26,LOW(-@2) SBCI R27,HIGH(-@2) CALL __PUTDP1 .ENDM .MACRO __PUTB1RONS MOV R26,R@0 MOV R27,R@1 ADIW R26,@2 ST X,R30 .ENDM .MACRO __PUTW1RONS MOV R26,R@0 MOV R27,R@1 ADIW R26,@2 ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1RONS MOV R26,R@0 MOV R27,R@1 ADIW R26,@2 CALL __PUTDP1 .ENDM .MACRO __GETB1SX MOVW R30,R28 SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) LD R30,Z .ENDM .MACRO __GETB1HSX MOVW R30,R28 SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) LD R31,Z .ENDM .MACRO __GETW1SX MOVW R30,R28 SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) LD R0,Z+ LD R31,Z MOV R30,R0 .ENDM .MACRO __GETD1SX MOVW R30,R28 SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) LD R0,Z+ LD R1,Z+ LD R22,Z+ LD R23,Z MOVW R30,R0 .ENDM .MACRO __GETB2SX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) LD R26,X .ENDM .MACRO __GETW2SX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) LD R0,X+ LD R27,X MOV R26,R0 .ENDM .MACRO __GETD2SX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) LD R0,X+ LD R1,X+ LD R24,X+ LD R25,X MOVW R26,R0 .ENDM .MACRO __GETBRSX MOVW R30,R28 SUBI R30,LOW(-@1) SBCI R31,HIGH(-@1) LD R@0,Z .ENDM .MACRO __GETWRSX MOVW R30,R28 SUBI R30,LOW(-@2) SBCI R31,HIGH(-@2) LD R@0,Z+ LD R@1,Z .ENDM .MACRO __GETBRSX2 MOVW R26,R28 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) LD R@0,X .ENDM .MACRO __GETWRSX2 MOVW R26,R28 SUBI R26,LOW(-@2) SBCI R27,HIGH(-@2) LD R@0,X+ LD R@1,X .ENDM .MACRO __LSLW8SX MOVW R30,R28 SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) LD R31,Z CLR R30 .ENDM .MACRO __PUTB1SX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) ST X,R30 .ENDM .MACRO __PUTW1SX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1SX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) ST X+,R30 ST X+,R31 ST X+,R22 ST X,R23 .ENDM .MACRO __CLRW1SX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) ST X+,R30 ST X,R30 .ENDM .MACRO __CLRD1SX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) ST X+,R30 ST X+,R30 ST X+,R30 ST X,R30 .ENDM .MACRO __PUTB2SX MOVW R30,R28 SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) ST Z,R26 .ENDM .MACRO __PUTW2SX MOVW R30,R28 SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) ST Z+,R26 ST Z,R27 .ENDM .MACRO __PUTD2SX MOVW R30,R28 SUBI R30,LOW(-@0) SBCI R31,HIGH(-@0) ST Z+,R26 ST Z+,R27 ST Z+,R24 ST Z,R25 .ENDM .MACRO __PUTBSRX MOVW R30,R28 SUBI R30,LOW(-@1) SBCI R31,HIGH(-@1) ST Z,R@0 .ENDM .MACRO __PUTWSRX MOVW R30,R28 SUBI R30,LOW(-@2) SBCI R31,HIGH(-@2) ST Z+,R@0 ST Z,R@1 .ENDM .MACRO __PUTB1SNX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) LD R0,X+ LD R27,X MOV R26,R0 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X,R30 .ENDM .MACRO __PUTW1SNX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) LD R0,X+ LD R27,X MOV R26,R0 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X+,R30 ST X,R31 .ENDM .MACRO __PUTD1SNX MOVW R26,R28 SUBI R26,LOW(-@0) SBCI R27,HIGH(-@0) LD R0,X+ LD R27,X MOV R26,R0 SUBI R26,LOW(-@1) SBCI R27,HIGH(-@1) ST X+,R30 ST X+,R31 ST X+,R22 ST X,R23 .ENDM .MACRO __MULBRR MULS R@0,R@1 MOVW R30,R0 .ENDM .MACRO __MULBRRU MUL R@0,R@1 MOVW R30,R0 .ENDM .MACRO __MULBRR0 MULS R@0,R@1 .ENDM .MACRO __MULBRRU0 MUL R@0,R@1 .ENDM .MACRO __MULBNWRU LDI R26,@2 MUL R26,R@0 MOVW R30,R0 MUL R26,R@1 ADD R31,R0 .ENDM ;NAME DEFINITIONS FOR GLOBAL VARIABLES ALLOCATED TO REGISTERS .DEF _minute_read=R4 .DEF _minute_read_msb=R5 .DEF _second_read=R6 .DEF _second_read_msb=R7 .DEF _hour_read=R8 .DEF _hour_read_msb=R9 .DEF _pause=R10 .DEF _pause_msb=R11 .DEF _second_counter=R12 .DEF _second_counter_msb=R13 .CSEG .ORG 0x00 ;START OF CODE MARKER __START_OF_CODE: ;INTERRUPT VECTORS JMP __RESET JMP _ext_int0_isr JMP _ext_int1_isr JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP _timer0_comp_isr JMP _timer0_ovf_isr JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 JMP 0x00 _tbl10_G100: .DB 0x10,0x27,0xE8,0x3,0x64,0x0,0xA,0x0 .DB 0x1,0x0 _tbl16_G100: .DB 0x0,0x10,0x0,0x1,0x10,0x0,0x1,0x0 ;GLOBAL REGISTER VARIABLES INITIALIZATION __REG_VARS: .DB 0x0,0x0,0x0,0x0 .DB 0x0,0x0,0x0,0x0 .DB 0x0,0x0 _0x3: .DB 0x30,0x30,0x3A,0x30,0x30,0x3A,0x30,0x30 _0x0: .DB 0x20,0x43,0x6F,0x6D,0x70,0x6C,0x65,0x74 .DB 0x65,0x64,0x20,0x0,0x25,0x64,0x20,0x3A .DB 0x20,0x25,0x64,0x20,0x3A,0x20,0x25,0x64 .DB 0x20,0x0 _0x2020003: .DB 0x80,0xC0 __GLOBAL_INI_TBL: .DW 0x0A .DW 0x04 .DW __REG_VARS*2 .DW 0x08 .DW _time .DW _0x3*2 .DW 0x02 .DW __base_y_G101 .DW _0x2020003*2 _0xFFFFFFFF: .DW 0 #define __GLOBAL_INI_TBL_PRESENT 1 __RESET: CLI CLR R30 OUT EECR,R30 ;INTERRUPT VECTORS ARE PLACED ;AT THE START OF FLASH LDI R31,1 OUT GICR,R31 OUT GICR,R30 OUT MCUCR,R30 ;CLEAR R2-R14 LDI R24,(14-2)+1 LDI R26,2 CLR R27 __CLEAR_REG: ST X+,R30 DEC R24 BRNE __CLEAR_REG ;CLEAR SRAM LDI R24,LOW(__CLEAR_SRAM_SIZE) LDI R25,HIGH(__CLEAR_SRAM_SIZE) LDI R26,__SRAM_START __CLEAR_SRAM: ST X+,R30 SBIW R24,1 BRNE __CLEAR_SRAM ;GLOBAL VARIABLES INITIALIZATION LDI R30,LOW(__GLOBAL_INI_TBL*2) LDI R31,HIGH(__GLOBAL_INI_TBL*2) __GLOBAL_INI_NEXT: LPM R24,Z+ LPM R25,Z+ SBIW R24,0 BREQ __GLOBAL_INI_END LPM R26,Z+ LPM R27,Z+ LPM R0,Z+ LPM R1,Z+ MOVW R22,R30 MOVW R30,R0 __GLOBAL_INI_LOOP: LPM R0,Z+ ST X+,R0 SBIW R24,1 BRNE __GLOBAL_INI_LOOP MOVW R30,R22 RJMP __GLOBAL_INI_NEXT __GLOBAL_INI_END: ;HARDWARE STACK POINTER INITIALIZATION LDI R30,LOW(__SRAM_END-__HEAP_SIZE) OUT SPL,R30 LDI R30,HIGH(__SRAM_END-__HEAP_SIZE) OUT SPH,R30 ;DATA STACK POINTER INITIALIZATION LDI R28,LOW(__SRAM_START+__DSTACK_SIZE) LDI R29,HIGH(__SRAM_START+__DSTACK_SIZE) JMP _main .ESEG .ORG 0 .DSEG .ORG 0x260 .CSEG ;/******************************************************* ;This program was created by the ;CodeWizardAVR V3.12 Advanced ;Automatic Program Generator ;� Copyright 1998-2014 Pavel Haiduc, HP InfoTech s.r.l. ;http://www.hpinfotech.com ; ;Project : ;Version : ;Date : 6/2/2019 ;Author : ;Company : ;Comments: ; ; ;Chip type : ATmega32 ;Program type : Application ;AVR Core Clock frequency: 8.000000 MHz ;Memory model : Small ;External RAM size : 0 ;Data Stack size : 512 ;*******************************************************/ ; ;#include <mega32.h> #ifndef __SLEEP_DEFINED__ #define __SLEEP_DEFINED__ .EQU __se_bit=0x80 .EQU __sm_mask=0x70 .EQU __sm_powerdown=0x20 .EQU __sm_powersave=0x30 .EQU __sm_standby=0x60 .EQU __sm_ext_standby=0x70 .EQU __sm_adc_noise_red=0x10 .SET power_ctrl_reg=mcucr #endif ;#include <stdio.h> ;// Alphanumeric LCD functions ;#include <alcd.h> ;#include <delay.h> ;//NOTICE : BE advised to Control that the frequency set by code vision must be the same frequency given to the ATmega32. ;// Declare your global variables here ;int minute_read = 0; ;int second_read = 0; ;int hour_read = 0 ; ; ;int pause = 0; ;int second_counter = 0 ; ;int minute_counter = 0; ;int hour_counter = 0 ; ; ; ; ;int counter; ; ; ; ; ;char time[20] = "00:00:00"; .DSEG ;char message[16] = "" ; ;// External Interrupt 0 service routine ;//reset button ;interrupt [EXT_INT0] void ext_int0_isr(void) { ; 0000 0033 interrupt [2] void ext_int0_isr(void) { .CSEG _ext_int0_isr: ; .FSTART _ext_int0_isr ST -Y,R30 ST -Y,R31 ; 0000 0034 second_counter = minute_counter = hour_counter ; LDS R30,_hour_counter LDS R31,_hour_counter+1 STS _minute_counter,R30 STS _minute_counter+1,R31 MOVW R12,R30 ; 0000 0035 } LD R31,Y+ LD R30,Y+ RETI ; .FEND ; ;interrupt [EXT_INT1] void ext_int1_isr(void) ; 0000 0038 { _ext_int1_isr: ; .FSTART _ext_int1_isr ST -Y,R30 ST -Y,R31 IN R30,SREG ST -Y,R30 ; 0000 0039 // Place your code here ; 0000 003A pause = !pause ; MOVW R30,R10 CALL __LNEGW1 MOV R10,R30 CLR R11 ; 0000 003B } LD R30,Y+ OUT SREG,R30 LD R31,Y+ LD R30,Y+ RETI ; .FEND ; ;void update(){ ; 0000 003D void update(){ _update: ; .FSTART _update ; 0000 003E ; 0000 003F if(second_counter == 60){ LDI R30,LOW(60) LDI R31,HIGH(60) CP R30,R12 CPC R31,R13 BRNE _0x4 ; 0000 0040 second_counter = 0 ; CLR R12 CLR R13 ; 0000 0041 minute_counter++; LDI R26,LOW(_minute_counter) LDI R27,HIGH(_minute_counter) CALL SUBOPT_0x0 ; 0000 0042 if(minute_counter == 60){ LDS R26,_minute_counter LDS R27,_minute_counter+1 SBIW R26,60 BRNE _0x5 ; 0000 0043 minute_counter = 0 ; LDI R30,LOW(0) STS _minute_counter,R30 STS _minute_counter+1,R30 ; 0000 0044 hour_counter++; LDI R26,LOW(_hour_counter) LDI R27,HIGH(_hour_counter) CALL SUBOPT_0x0 ; 0000 0045 } ; 0000 0046 } _0x5: ; 0000 0047 else { RJMP _0x6 _0x4: ; 0000 0048 second_counter++; MOVW R30,R12 ADIW R30,1 MOVW R12,R30 ; 0000 0049 } _0x6: ; 0000 004A } RET ; .FEND ;// Timer 0 overflow interrupt service routine ;interrupt [TIM0_OVF] void timer0_ovf_isr(void) ; 0000 004D { _timer0_ovf_isr: ; .FSTART _timer0_ovf_isr ; 0000 004E ; 0000 004F } RETI ; .FEND ; ; ;// Timer 0 output compare interrupt service routine ;interrupt [TIM0_COMP] void timer0_comp_isr(void) ; 0000 0054 { _timer0_comp_isr: ; .FSTART _timer0_comp_isr ; 0000 0055 // Place your code here ; 0000 0056 ; 0000 0057 } RETI ; .FEND ; ;void main(void) ; 0000 005A { _main: ; .FSTART _main ; 0000 005B // Declare your local variables here ; 0000 005C ; 0000 005D // Input/Output Ports initialization ; 0000 005E // Port A initialization ; 0000 005F // Function: Bit7=In Bit6=In Bit5=In Bit4=In Bit3=In Bit2=In Bit1=In Bit0=In ; 0000 0060 DDRA=(0<<DDA7) | (0<<DDA6) | (0<<DDA5) | (0<<DDA4) | (0<<DDA3) | (0<<DDA2) | (0<<DDA1) | (0<<DDA0); LDI R30,LOW(0) OUT 0x1A,R30 ; 0000 0061 // State: Bit7=T Bit6=T Bit5=T Bit4=T Bit3=T Bit2=T Bit1=T Bit0=T ; 0000 0062 PORTA=(0<<PORTA7) | (0<<PORTA6) | (0<<PORTA5) | (0<<PORTA4) | (0<<PORTA3) | (0<<PORTA2) | (0<<PORTA1) | (0<<PORTA0); OUT 0x1B,R30 ; 0000 0063 ; 0000 0064 // Port B initialization ; 0000 0065 // Function: Bit7=In Bit6=In Bit5=In Bit4=In Bit3=In Bit2=In Bit1=In Bit0=In ; 0000 0066 DDRB=(0<<DDB7) | (0<<DDB6) | (0<<DDB5) | (0<<DDB4) | (0<<DDB3) | (0<<DDB2) | (0<<DDB1) | (0<<DDB0); OUT 0x17,R30 ; 0000 0067 // State: Bit7=T Bit6=T Bit5=T Bit4=T Bit3=T Bit2=T Bit1=T Bit0=T ; 0000 0068 PORTB=(0<<PORTB7) | (0<<PORTB6) | (0<<PORTB5) | (0<<PORTB4) | (0<<PORTB3) | (0<<PORTB2) | (0<<PORTB1) | (0<<PORTB0); OUT 0x18,R30 ; 0000 0069 ; 0000 006A // Port C initialization ; 0000 006B // Function: Bit7=Out Bit6=Out Bit5=Out Bit4=Out Bit3=Out Bit2=Out Bit1=Out Bit0=Out ; 0000 006C DDRC=(1<<DDC7) | (1<<DDC6) | (1<<DDC5) | (1<<DDC4) | (1<<DDC3) | (1<<DDC2) | (1<<DDC1) | (1<<DDC0); LDI R30,LOW(255) OUT 0x14,R30 ; 0000 006D // State: Bit7=0 Bit6=0 Bit5=0 Bit4=0 Bit3=0 Bit2=0 Bit1=0 Bit0=0 ; 0000 006E PORTC=(0<<PORTC7) | (0<<PORTC6) | (0<<PORTC5) | (0<<PORTC4) | (0<<PORTC3) | (0<<PORTC2) | (0<<PORTC1) | (0<<PORTC0); LDI R30,LOW(0) OUT 0x15,R30 ; 0000 006F ; 0000 0070 // Port D initialization ; 0000 0071 // Function: Bit7=In Bit6=Out Bit5=In Bit4=In Bit3=In Bit2=In Bit1=In Bit0=In ; 0000 0072 DDRD=(0<<DDD7) | (1<<DDD6) | (0<<DDD5) | (0<<DDD4) | (0<<DDD3) | (0<<DDD2) | (0<<DDD1) | (0<<DDD0); LDI R30,LOW(64) OUT 0x11,R30 ; 0000 0073 // State: Bit7=T Bit6=0 Bit5=T Bit4=T Bit3=T Bit2=T Bit1=T Bit0=T ; 0000 0074 PORTD=(0<<PORTD7) | (0<<PORTD6) | (0<<PORTD5) | (0<<PORTD4) | (0<<PORTD3) | (0<<PORTD2) | (0<<PORTD1) | (0<<PORTD0); LDI R30,LOW(0) OUT 0x12,R30 ; 0000 0075 ; 0000 0076 // Timer/Counter 0 initialization ; 0000 0077 // Clock source: System Clock ; 0000 0078 // Clock value: 125.000 kHz ; 0000 0079 // Mode: Normal top=0xFF ; 0000 007A // OC0 output: Disconnected ; 0000 007B // Timer Period: 1 ms ; 0000 007C TCCR0=(0<<WGM00) | (0<<COM01) | (0<<COM00) | (0<<WGM01) | (0<<CS02) | (1<<CS01) | (1<<CS00); LDI R30,LOW(3) OUT 0x33,R30 ; 0000 007D TCNT0=0x83; LDI R30,LOW(131) OUT 0x32,R30 ; 0000 007E OCR0=0x00; LDI R30,LOW(0) OUT 0x3C,R30 ; 0000 007F ; 0000 0080 // Timer/Counter 1 initialization ; 0000 0081 // Clock source: System Clock ; 0000 0082 // Clock value: Timer1 Stopped ; 0000 0083 // Mode: Normal top=0xFFFF ; 0000 0084 // OC1A output: Disconnected ; 0000 0085 // OC1B output: Disconnected ; 0000 0086 // Noise Canceler: Off ; 0000 0087 // Input Capture on Falling Edge ; 0000 0088 // Timer1 Overflow Interrupt: Off ; 0000 0089 // Input Capture Interrupt: Off ; 0000 008A // Compare A Match Interrupt: Off ; 0000 008B // Compare B Match Interrupt: Off ; 0000 008C TCCR1A=(0<<COM1A1) | (0<<COM1A0) | (0<<COM1B1) | (0<<COM1B0) | (0<<WGM11) | (0<<WGM10); OUT 0x2F,R30 ; 0000 008D TCCR1B=(0<<ICNC1) | (0<<ICES1) | (0<<WGM13) | (0<<WGM12) | (0<<CS12) | (0<<CS11) | (0<<CS10); OUT 0x2E,R30 ; 0000 008E TCNT1H=0x00; OUT 0x2D,R30 ; 0000 008F TCNT1L=0x00; OUT 0x2C,R30 ; 0000 0090 ICR1H=0x00; OUT 0x27,R30 ; 0000 0091 ICR1L=0x00; OUT 0x26,R30 ; 0000 0092 OCR1AH=0x00; OUT 0x2B,R30 ; 0000 0093 OCR1AL=0x00; OUT 0x2A,R30 ; 0000 0094 OCR1BH=0x00; OUT 0x29,R30 ; 0000 0095 OCR1BL=0x00; OUT 0x28,R30 ; 0000 0096 ; 0000 0097 // Timer/Counter 2 initialization ; 0000 0098 // Clock source: System Clock ; 0000 0099 // Clock value: Timer2 Stopped ; 0000 009A // Mode: Normal top=0xFF ; 0000 009B // OC2 output: Disconnected ; 0000 009C ASSR=0<<AS2; OUT 0x22,R30 ; 0000 009D TCCR2=(0<<PWM2) | (0<<COM21) | (0<<COM20) | (0<<CTC2) | (0<<CS22) | (0<<CS21) | (0<<CS20); OUT 0x25,R30 ; 0000 009E TCNT2=0x00; OUT 0x24,R30 ; 0000 009F OCR2=0x00; OUT 0x23,R30 ; 0000 00A0 ; 0000 00A1 // Timer(s)/Counter(s) Interrupt(s) initialization ; 0000 00A2 TIMSK=(0<<OCIE2) | (0<<TOIE2) | (0<<TICIE1) | (0<<OCIE1A) | (0<<OCIE1B) | (0<<TOIE1) | (0<<OCIE0) | (1<<TOIE0); LDI R30,LOW(1) OUT 0x39,R30 ; 0000 00A3 ; 0000 00A4 // External Interrupt(s) initialization ; 0000 00A5 // INT0: On ; 0000 00A6 // INT0 Mode: Low level ; 0000 00A7 // INT1: Off ; 0000 00A8 // INT2: Off ; 0000 00A9 GICR|=(1<<INT1) | (1<<INT0) | (0<<INT2); IN R30,0x3B ORI R30,LOW(0xC0) OUT 0x3B,R30 ; 0000 00AA MCUCR=(1<<ISC11) | (1<<ISC10) | (1<<ISC01) | (1<<ISC00); LDI R30,LOW(15) OUT 0x35,R30 ; 0000 00AB MCUCSR=(0<<ISC2); LDI R30,LOW(0) OUT 0x34,R30 ; 0000 00AC GIFR=(1<<INTF1) | (1<<INTF0) | (0<<INTF2); LDI R30,LOW(192) OUT 0x3A,R30 ; 0000 00AD ; 0000 00AE // USART initialization ; 0000 00AF // USART disabled ; 0000 00B0 UCSRB=(0<<RXCIE) | (0<<TXCIE) | (0<<UDRIE) | (0<<RXEN) | (0<<TXEN) | (0<<UCSZ2) | (0<<RXB8) | (0<<TXB8); LDI R30,LOW(0) OUT 0xA,R30 ; 0000 00B1 ; 0000 00B2 // Analog Comparator initialization ; 0000 00B3 // Analog Comparator: Off ; 0000 00B4 // The Analog Comparator's positive input is ; 0000 00B5 // connected to the AIN0 pin ; 0000 00B6 // The Analog Comparator's negative input is ; 0000 00B7 // connected to the AIN1 pin ; 0000 00B8 ACSR=(1<<ACD) | (0<<ACBG) | (0<<ACO) | (0<<ACI) | (0<<ACIE) | (0<<ACIC) | (0<<ACIS1) | (0<<ACIS0); LDI R30,LOW(128) OUT 0x8,R30 ; 0000 00B9 SFIOR=(0<<ACME); LDI R30,LOW(0) OUT 0x30,R30 ; 0000 00BA ; 0000 00BB // ADC initialization ; 0000 00BC // ADC disabled ; 0000 00BD ADCSRA=(0<<ADEN) | (0<<ADSC) | (0<<ADATE) | (0<<ADIF) | (0<<ADIE) | (0<<ADPS2) | (0<<ADPS1) | (0<<ADPS0); OUT 0x6,R30 ; 0000 00BE ; 0000 00BF // SPI initialization ; 0000 00C0 // SPI disabled ; 0000 00C1 SPCR=(0<<SPIE) | (0<<SPE) | (0<<DORD) | (0<<MSTR) | (0<<CPOL) | (0<<CPHA) | (0<<SPR1) | (0<<SPR0); OUT 0xD,R30 ; 0000 00C2 ; 0000 00C3 // TWI initialization ; 0000 00C4 // TWI disabled ; 0000 00C5 TWCR=(0<<TWEA) | (0<<TWSTA) | (0<<TWSTO) | (0<<TWEN) | (0<<TWIE); OUT 0x36,R30 ; 0000 00C6 ; 0000 00C7 // Alphanumeric LCD initialization ; 0000 00C8 // Connections are specified in the ; 0000 00C9 // Project|Configure|C Compiler|Libraries|Alphanumeric LCD menu: ; 0000 00CA // RS - PORTC Bit 0 ; 0000 00CB // RD - PORTC Bit 1 ; 0000 00CC // EN - PORTC Bit 2 ; 0000 00CD // D4 - PORTC Bit 4 ; 0000 00CE // D5 - PORTC Bit 5 ; 0000 00CF // D6 - PORTC Bit 6 ; 0000 00D0 // D7 - PORTC Bit 7 ; 0000 00D1 // Characters/line: 16 ; 0000 00D2 lcd_init(16); LDI R26,LOW(16) CALL _lcd_init ; 0000 00D3 ; 0000 00D4 // Global enable interrupts ; 0000 00D5 #asm("sei") sei ; 0000 00D6 ; 0000 00D7 while (1) _0x7: ; 0000 00D8 { ; 0000 00D9 //minute_read = PINA; ; 0000 00DA second_read = 20; LDI R30,LOW(20) LDI R31,HIGH(20) MOVW R6,R30 ; 0000 00DB minute_read = 10 ; LDI R30,LOW(10) LDI R31,HIGH(10) MOVW R4,R30 ; 0000 00DC hour_read = 1 ; LDI R30,LOW(1) LDI R31,HIGH(1) MOVW R8,R30 ; 0000 00DD if ( pause == 0 ){ MOV R0,R10 OR R0,R11 BRNE _0xA ; 0000 00DE delay_ms(10); LDI R26,LOW(10) LDI R27,0 CALL _delay_ms ; 0000 00DF update(); RCALL _update ; 0000 00E0 } ; 0000 00E1 ; 0000 00E2 ; 0000 00E3 if(second_counter == second_read && minute_counter == minute_read && hour_counter == hour_read){ _0xA: __CPWRR 6,7,12,13 BRNE _0xC LDS R26,_minute_counter LDS R27,_minute_counter+1 CP R4,R26 CPC R5,R27 BRNE _0xC LDS R26,_hour_counter LDS R27,_hour_counter+1 CP R8,R26 CPC R9,R27 BREQ _0xD _0xC: RJMP _0xB _0xD: ; 0000 00E4 sprintf(time , " Completed " ); LDI R30,LOW(_time) LDI R31,HIGH(_time) ST -Y,R31 ST -Y,R30 __POINTW1FN _0x0,0 ST -Y,R31 ST -Y,R30 LDI R24,0 CALL _sprintf ADIW R28,4 ; 0000 00E5 second_counter = minute_counter = hour_counter = 0 ; LDI R30,LOW(0) LDI R31,HIGH(0) STS _hour_counter,R30 STS _hour_counter+1,R31 STS _minute_counter,R30 STS _minute_counter+1,R31 MOVW R12,R30 ; 0000 00E6 } ; 0000 00E7 ; 0000 00E8 else { RJMP _0xE _0xB: ; 0000 00E9 sprintf(time , "%d : %d : %d " , hour_counter, minute_counter , second_counter); LDI R30,LOW(_time) LDI R31,HIGH(_time) ST -Y,R31 ST -Y,R30 __POINTW1FN _0x0,12 ST -Y,R31 ST -Y,R30 LDS R30,_hour_counter LDS R31,_hour_counter+1 CALL SUBOPT_0x1 LDS R30,_minute_counter LDS R31,_minute_counter+1 CALL SUBOPT_0x1 MOVW R30,R12 CALL SUBOPT_0x1 LDI R24,12 CALL _sprintf ADIW R28,16 ; 0000 00EA } _0xE: ; 0000 00EB ; 0000 00EC ; 0000 00ED lcd_gotoxy(0,0); LDI R30,LOW(0) ST -Y,R30 LDI R26,LOW(0) CALL _lcd_gotoxy ; 0000 00EE lcd_puts(time); LDI R26,LOW(_time) LDI R27,HIGH(_time) CALL _lcd_puts ; 0000 00EF ; 0000 00F0 } RJMP _0x7 ; 0000 00F1 } _0xF: RJMP _0xF ; .FEND #ifndef __SLEEP_DEFINED__ #define __SLEEP_DEFINED__ .EQU __se_bit=0x80 .EQU __sm_mask=0x70 .EQU __sm_powerdown=0x20 .EQU __sm_powersave=0x30 .EQU __sm_standby=0x60 .EQU __sm_ext_standby=0x70 .EQU __sm_adc_noise_red=0x10 .SET power_ctrl_reg=mcucr #endif .CSEG _put_buff_G100: ; .FSTART _put_buff_G100 ST -Y,R27 ST -Y,R26 ST -Y,R17 ST -Y,R16 LDD R26,Y+2 LDD R27,Y+2+1 ADIW R26,2 CALL __GETW1P SBIW R30,0 BREQ _0x2000010 LDD R26,Y+2 LDD R27,Y+2+1 ADIW R26,4 CALL __GETW1P MOVW R16,R30 SBIW R30,0 BREQ _0x2000012 __CPWRN 16,17,2 BRLO _0x2000013 MOVW R30,R16 SBIW R30,1 MOVW R16,R30 __PUTW1SNS 2,4 _0x2000012: LDD R26,Y+2 LDD R27,Y+2+1 ADIW R26,2 CALL SUBOPT_0x0 SBIW R30,1 LDD R26,Y+4 STD Z+0,R26 _0x2000013: LDD R26,Y+2 LDD R27,Y+2+1 CALL __GETW1P TST R31 BRMI _0x2000014 CALL SUBOPT_0x0 _0x2000014: RJMP _0x2000015 _0x2000010: LDD R26,Y+2 LDD R27,Y+2+1 LDI R30,LOW(65535) LDI R31,HIGH(65535) ST X+,R30 ST X,R31 _0x2000015: LDD R17,Y+1 LDD R16,Y+0 ADIW R28,5 RET ; .FEND __print_G100: ; .FSTART __print_G100 ST -Y,R27 ST -Y,R26 SBIW R28,6 CALL __SAVELOCR6 LDI R17,0 LDD R26,Y+12 LDD R27,Y+12+1 LDI R30,LOW(0) LDI R31,HIGH(0) ST X+,R30 ST X,R31 _0x2000016: LDD R30,Y+18 LDD R31,Y+18+1 ADIW R30,1 STD Y+18,R30 STD Y+18+1,R31 SBIW R30,1 LPM R30,Z MOV R18,R30 CPI R30,0 BRNE PC+2 RJMP _0x2000018 MOV R30,R17 CPI R30,0 BRNE _0x200001C CPI R18,37 BRNE _0x200001D LDI R17,LOW(1) RJMP _0x200001E _0x200001D: CALL SUBOPT_0x2 _0x200001E: RJMP _0x200001B _0x200001C: CPI R30,LOW(0x1) BRNE _0x200001F CPI R18,37 BRNE _0x2000020 CALL SUBOPT_0x2 RJMP _0x20000CC _0x2000020: LDI R17,LOW(2) LDI R20,LOW(0) LDI R16,LOW(0) CPI R18,45 BRNE _0x2000021 LDI R16,LOW(1) RJMP _0x200001B _0x2000021: CPI R18,43 BRNE _0x2000022 LDI R20,LOW(43) RJMP _0x200001B _0x2000022: CPI R18,32 BRNE _0x2000023 LDI R20,LOW(32) RJMP _0x200001B _0x2000023: RJMP _0x2000024 _0x200001F: CPI R30,LOW(0x2) BRNE _0x2000025 _0x2000024: LDI R21,LOW(0) LDI R17,LOW(3) CPI R18,48 BRNE _0x2000026 ORI R16,LOW(128) RJMP _0x200001B _0x2000026: RJMP _0x2000027 _0x2000025: CPI R30,LOW(0x3) BREQ PC+2 RJMP _0x200001B _0x2000027: CPI R18,48 BRLO _0x200002A CPI R18,58 BRLO _0x200002B _0x200002A: RJMP _0x2000029 _0x200002B: LDI R26,LOW(10) MUL R21,R26 MOV R21,R0 MOV R30,R18 SUBI R30,LOW(48) ADD R21,R30 RJMP _0x200001B _0x2000029: MOV R30,R18 CPI R30,LOW(0x63) BRNE _0x200002F CALL SUBOPT_0x3 LDD R30,Y+16 LDD R31,Y+16+1 LDD R26,Z+4 ST -Y,R26 CALL SUBOPT_0x4 RJMP _0x2000030 _0x200002F: CPI R30,LOW(0x73) BRNE _0x2000032 CALL SUBOPT_0x3 CALL SUBOPT_0x5 CALL _strlen MOV R17,R30 RJMP _0x2000033 _0x2000032: CPI R30,LOW(0x70) BRNE _0x2000035 CALL SUBOPT_0x3 CALL SUBOPT_0x5 CALL _strlenf MOV R17,R30 ORI R16,LOW(8) _0x2000033: ORI R16,LOW(2) ANDI R16,LOW(127) LDI R19,LOW(0) RJMP _0x2000036 _0x2000035: CPI R30,LOW(0x64) BREQ _0x2000039 CPI R30,LOW(0x69) BRNE _0x200003A _0x2000039: ORI R16,LOW(4) RJMP _0x200003B _0x200003A: CPI R30,LOW(0x75) BRNE _0x200003C _0x200003B: LDI R30,LOW(_tbl10_G100*2) LDI R31,HIGH(_tbl10_G100*2) STD Y+6,R30 STD Y+6+1,R31 LDI R17,LOW(5) RJMP _0x200003D _0x200003C: CPI R30,LOW(0x58) BRNE _0x200003F ORI R16,LOW(8) RJMP _0x2000040 _0x200003F: CPI R30,LOW(0x78) BREQ PC+2 RJMP _0x2000071 _0x2000040: LDI R30,LOW(_tbl16_G100*2) LDI R31,HIGH(_tbl16_G100*2) STD Y+6,R30 STD Y+6+1,R31 LDI R17,LOW(4) _0x200003D: SBRS R16,2 RJMP _0x2000042 CALL SUBOPT_0x3 CALL SUBOPT_0x6 LDD R26,Y+11 TST R26 BRPL _0x2000043 LDD R30,Y+10 LDD R31,Y+10+1 CALL __ANEGW1 STD Y+10,R30 STD Y+10+1,R31 LDI R20,LOW(45) _0x2000043: CPI R20,0 BREQ _0x2000044 SUBI R17,-LOW(1) RJMP _0x2000045 _0x2000044: ANDI R16,LOW(251) _0x2000045: RJMP _0x2000046 _0x2000042: CALL SUBOPT_0x3 CALL SUBOPT_0x6 _0x2000046: _0x2000036: SBRC R16,0 RJMP _0x2000047 _0x2000048: CP R17,R21 BRSH _0x200004A SBRS R16,7 RJMP _0x200004B SBRS R16,2 RJMP _0x200004C ANDI R16,LOW(251) MOV R18,R20 SUBI R17,LOW(1) RJMP _0x200004D _0x200004C: LDI R18,LOW(48) _0x200004D: RJMP _0x200004E _0x200004B: LDI R18,LOW(32) _0x200004E: CALL SUBOPT_0x2 SUBI R21,LOW(1) RJMP _0x2000048 _0x200004A: _0x2000047: MOV R19,R17 SBRS R16,1 RJMP _0x200004F _0x2000050: CPI R19,0 BREQ _0x2000052 SBRS R16,3 RJMP _0x2000053 LDD R30,Y+6 LDD R31,Y+6+1 LPM R18,Z+ STD Y+6,R30 STD Y+6+1,R31 RJMP _0x2000054 _0x2000053: LDD R26,Y+6 LDD R27,Y+6+1 LD R18,X+ STD Y+6,R26 STD Y+6+1,R27 _0x2000054: CALL SUBOPT_0x2 CPI R21,0 BREQ _0x2000055 SUBI R21,LOW(1) _0x2000055: SUBI R19,LOW(1) RJMP _0x2000050 _0x2000052: RJMP _0x2000056 _0x200004F: _0x2000058: LDI R18,LOW(48) LDD R30,Y+6 LDD R31,Y+6+1 CALL __GETW1PF STD Y+8,R30 STD Y+8+1,R31 LDD R30,Y+6 LDD R31,Y+6+1 ADIW R30,2 STD Y+6,R30 STD Y+6+1,R31 _0x200005A: LDD R30,Y+8 LDD R31,Y+8+1 LDD R26,Y+10 LDD R27,Y+10+1 CP R26,R30 CPC R27,R31 BRLO _0x200005C SUBI R18,-LOW(1) LDD R26,Y+8 LDD R27,Y+8+1 LDD R30,Y+10 LDD R31,Y+10+1 SUB R30,R26 SBC R31,R27 STD Y+10,R30 STD Y+10+1,R31 RJMP _0x200005A _0x200005C: CPI R18,58 BRLO _0x200005D SBRS R16,3 RJMP _0x200005E SUBI R18,-LOW(7) RJMP _0x200005F _0x200005E: SUBI R18,-LOW(39) _0x200005F: _0x200005D: SBRC R16,4 RJMP _0x2000061 CPI R18,49 BRSH _0x2000063 LDD R26,Y+8 LDD R27,Y+8+1 SBIW R26,1 BRNE _0x2000062 _0x2000063: RJMP _0x20000CD _0x2000062: CP R21,R19 BRLO _0x2000067 SBRS R16,0 RJMP _0x2000068 _0x2000067: RJMP _0x2000066 _0x2000068: LDI R18,LOW(32) SBRS R16,7 RJMP _0x2000069 LDI R18,LOW(48) _0x20000CD: ORI R16,LOW(16) SBRS R16,2 RJMP _0x200006A ANDI R16,LOW(251) ST -Y,R20 CALL SUBOPT_0x4 CPI R21,0 BREQ _0x200006B SUBI R21,LOW(1) _0x200006B: _0x200006A: _0x2000069: _0x2000061: CALL SUBOPT_0x2 CPI R21,0 BREQ _0x200006C SUBI R21,LOW(1) _0x200006C: _0x2000066: SUBI R19,LOW(1) LDD R26,Y+8 LDD R27,Y+8+1 SBIW R26,2 BRLO _0x2000059 RJMP _0x2000058 _0x2000059: _0x2000056: SBRS R16,0 RJMP _0x200006D _0x200006E: CPI R21,0 BREQ _0x2000070 SUBI R21,LOW(1) LDI R30,LOW(32) ST -Y,R30 CALL SUBOPT_0x4 RJMP _0x200006E _0x2000070: _0x200006D: _0x2000071: _0x2000030: _0x20000CC: LDI R17,LOW(0) _0x200001B: RJMP _0x2000016 _0x2000018: LDD R26,Y+12 LDD R27,Y+12+1 CALL __GETW1P CALL __LOADLOCR6 ADIW R28,20 RET ; .FEND _sprintf: ; .FSTART _sprintf PUSH R15 MOV R15,R24 SBIW R28,6 CALL __SAVELOCR4 CALL SUBOPT_0x7 SBIW R30,0 BRNE _0x2000072 LDI R30,LOW(65535) LDI R31,HIGH(65535) RJMP _0x2080002 _0x2000072: MOVW R26,R28 ADIW R26,6 CALL __ADDW2R15 MOVW R16,R26 CALL SUBOPT_0x7 STD Y+6,R30 STD Y+6+1,R31 LDI R30,LOW(0) STD Y+8,R30 STD Y+8+1,R30 MOVW R26,R28 ADIW R26,10 CALL __ADDW2R15 CALL __GETW1P ST -Y,R31 ST -Y,R30 ST -Y,R17 ST -Y,R16 LDI R30,LOW(_put_buff_G100) LDI R31,HIGH(_put_buff_G100) ST -Y,R31 ST -Y,R30 MOVW R26,R28 ADIW R26,10 RCALL __print_G100 MOVW R18,R30 LDD R26,Y+6 LDD R27,Y+6+1 LDI R30,LOW(0) ST X,R30 MOVW R30,R18 _0x2080002: CALL __LOADLOCR4 ADIW R28,10 POP R15 RET ; .FEND #ifndef __SLEEP_DEFINED__ #define __SLEEP_DEFINED__ .EQU __se_bit=0x80 .EQU __sm_mask=0x70 .EQU __sm_powerdown=0x20 .EQU __sm_powersave=0x30 .EQU __sm_standby=0x60 .EQU __sm_ext_standby=0x70 .EQU __sm_adc_noise_red=0x10 .SET power_ctrl_reg=mcucr #endif .DSEG .CSEG __lcd_write_nibble_G101: ; .FSTART __lcd_write_nibble_G101 ST -Y,R26 IN R30,0x15 ANDI R30,LOW(0xF) MOV R26,R30 LD R30,Y ANDI R30,LOW(0xF0) OR R30,R26 OUT 0x15,R30 __DELAY_USB 13 SBI 0x15,2 __DELAY_USB 13 CBI 0x15,2 __DELAY_USB 13 RJMP _0x2080001 ; .FEND __lcd_write_data: ; .FSTART __lcd_write_data ST -Y,R26 LD R26,Y RCALL __lcd_write_nibble_G101 ld r30,y swap r30 st y,r30 LD R26,Y RCALL __lcd_write_nibble_G101 __DELAY_USB 133 RJMP _0x2080001 ; .FEND _lcd_gotoxy: ; .FSTART _lcd_gotoxy ST -Y,R26 LD R30,Y LDI R31,0 SUBI R30,LOW(-__base_y_G101) SBCI R31,HIGH(-__base_y_G101) LD R30,Z LDD R26,Y+1 ADD R26,R30 RCALL __lcd_write_data LDD R30,Y+1 STS __lcd_x,R30 LD R30,Y STS __lcd_y,R30 ADIW R28,2 RET ; .FEND _lcd_clear: ; .FSTART _lcd_clear LDI R26,LOW(2) CALL SUBOPT_0x8 LDI R26,LOW(12) RCALL __lcd_write_data LDI R26,LOW(1) CALL SUBOPT_0x8 LDI R30,LOW(0) STS __lcd_y,R30 STS __lcd_x,R30 RET ; .FEND _lcd_putchar: ; .FSTART _lcd_putchar ST -Y,R26 LD R26,Y CPI R26,LOW(0xA) BREQ _0x2020005 LDS R30,__lcd_maxx LDS R26,__lcd_x CP R26,R30 BRLO _0x2020004 _0x2020005: LDI R30,LOW(0) ST -Y,R30 LDS R26,__lcd_y SUBI R26,-LOW(1) STS __lcd_y,R26 RCALL _lcd_gotoxy LD R26,Y CPI R26,LOW(0xA) BRNE _0x2020007 RJMP _0x2080001 _0x2020007: _0x2020004: LDS R30,__lcd_x SUBI R30,-LOW(1) STS __lcd_x,R30 SBI 0x15,0 LD R26,Y RCALL __lcd_write_data CBI 0x15,0 RJMP _0x2080001 ; .FEND _lcd_puts: ; .FSTART _lcd_puts ST -Y,R27 ST -Y,R26 ST -Y,R17 _0x2020008: LDD R26,Y+1 LDD R27,Y+1+1 LD R30,X+ STD Y+1,R26 STD Y+1+1,R27 MOV R17,R30 CPI R30,0 BREQ _0x202000A MOV R26,R17 RCALL _lcd_putchar RJMP _0x2020008 _0x202000A: LDD R17,Y+0 ADIW R28,3 RET ; .FEND _lcd_init: ; .FSTART _lcd_init ST -Y,R26 IN R30,0x14 ORI R30,LOW(0xF0) OUT 0x14,R30 SBI 0x14,2 SBI 0x14,0 SBI 0x14,1 CBI 0x15,2 CBI 0x15,0 CBI 0x15,1 LD R30,Y STS __lcd_maxx,R30 SUBI R30,-LOW(128) __PUTB1MN __base_y_G101,2 LD R30,Y SUBI R30,-LOW(192) __PUTB1MN __base_y_G101,3 LDI R26,LOW(20) LDI R27,0 CALL _delay_ms CALL SUBOPT_0x9 CALL SUBOPT_0x9 CALL SUBOPT_0x9 LDI R26,LOW(32) RCALL __lcd_write_nibble_G101 __DELAY_USW 200 LDI R26,LOW(40) RCALL __lcd_write_data LDI R26,LOW(4) RCALL __lcd_write_data LDI R26,LOW(133) RCALL __lcd_write_data LDI R26,LOW(6) RCALL __lcd_write_data RCALL _lcd_clear _0x2080001: ADIW R28,1 RET ; .FEND .CSEG .CSEG _strlen: ; .FSTART _strlen ST -Y,R27 ST -Y,R26 ld r26,y+ ld r27,y+ clr r30 clr r31 strlen0: ld r22,x+ tst r22 breq strlen1 adiw r30,1 rjmp strlen0 strlen1: ret ; .FEND _strlenf: ; .FSTART _strlenf ST -Y,R27 ST -Y,R26 clr r26 clr r27 ld r30,y+ ld r31,y+ strlenf0: lpm r0,z+ tst r0 breq strlenf1 adiw r26,1 rjmp strlenf0 strlenf1: movw r30,r26 ret ; .FEND .DSEG _minute_counter: .BYTE 0x2 _hour_counter: .BYTE 0x2 _time: .BYTE 0x14 __base_y_G101: .BYTE 0x4 __lcd_x: .BYTE 0x1 __lcd_y: .BYTE 0x1 __lcd_maxx: .BYTE 0x1 .CSEG ;OPTIMIZER ADDED SUBROUTINE, CALLED 4 TIMES, CODE SIZE REDUCTION:6 WORDS SUBOPT_0x0: LD R30,X+ LD R31,X+ ADIW R30,1 ST -X,R31 ST -X,R30 RET ;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:1 WORDS SUBOPT_0x1: CALL __CWD1 CALL __PUTPARD1 RET ;OPTIMIZER ADDED SUBROUTINE, CALLED 5 TIMES, CODE SIZE REDUCTION:13 WORDS SUBOPT_0x2: ST -Y,R18 LDD R26,Y+13 LDD R27,Y+13+1 LDD R30,Y+15 LDD R31,Y+15+1 ICALL RET ;OPTIMIZER ADDED SUBROUTINE, CALLED 5 TIMES, CODE SIZE REDUCTION:9 WORDS SUBOPT_0x3: LDD R30,Y+16 LDD R31,Y+16+1 SBIW R30,4 STD Y+16,R30 STD Y+16+1,R31 RET ;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:3 WORDS SUBOPT_0x4: LDD R26,Y+13 LDD R27,Y+13+1 LDD R30,Y+15 LDD R31,Y+15+1 ICALL RET ;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:4 WORDS SUBOPT_0x5: LDD R26,Y+16 LDD R27,Y+16+1 ADIW R26,4 CALL __GETW1P STD Y+6,R30 STD Y+6+1,R31 LDD R26,Y+6 LDD R27,Y+6+1 RET ;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:2 WORDS SUBOPT_0x6: LDD R26,Y+16 LDD R27,Y+16+1 ADIW R26,4 CALL __GETW1P STD Y+10,R30 STD Y+10+1,R31 RET ;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:1 WORDS SUBOPT_0x7: MOVW R26,R28 ADIW R26,12 CALL __ADDW2R15 CALL __GETW1P RET ;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:1 WORDS SUBOPT_0x8: CALL __lcd_write_data LDI R26,LOW(3) LDI R27,0 JMP _delay_ms ;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:7 WORDS SUBOPT_0x9: LDI R26,LOW(48) CALL __lcd_write_nibble_G101 __DELAY_USW 200 RET .CSEG _delay_ms: adiw r26,0 breq __delay_ms1 __delay_ms0: __DELAY_USW 0x7D0 wdr sbiw r26,1 brne __delay_ms0 __delay_ms1: ret __ADDW2R15: CLR R0 ADD R26,R15 ADC R27,R0 RET __ANEGW1: NEG R31 NEG R30 SBCI R31,0 RET __CWD1: MOV R22,R31 ADD R22,R22 SBC R22,R22 MOV R23,R22 RET __LNEGW1: OR R30,R31 LDI R30,1 BREQ __LNEGW1F LDI R30,0 __LNEGW1F: RET __GETW1P: LD R30,X+ LD R31,X SBIW R26,1 RET __GETW1PF: LPM R0,Z+ LPM R31,Z MOV R30,R0 RET __PUTPARD1: ST -Y,R23 ST -Y,R22 ST -Y,R31 ST -Y,R30 RET __SAVELOCR6: ST -Y,R21 __SAVELOCR5: ST -Y,R20 __SAVELOCR4: ST -Y,R19 __SAVELOCR3: ST -Y,R18 __SAVELOCR2: ST -Y,R17 ST -Y,R16 RET __LOADLOCR6: LDD R21,Y+5 __LOADLOCR5: LDD R20,Y+4 __LOADLOCR4: LDD R19,Y+3 __LOADLOCR3: LDD R18,Y+2 __LOADLOCR2: LDD R17,Y+1 LD R16,Y RET ;END OF CODE MARKER __END_OF_CODE:
; A037952: a(n) = binomial(n, floor((n-1)/2)). ; 0,1,1,3,4,10,15,35,56,126,210,462,792,1716,3003,6435,11440,24310,43758,92378,167960,352716,646646,1352078,2496144,5200300,9657700,20058300,37442160,77558760,145422675,300540195,565722720,1166803110,2203961430,4537567650,8597496600,17672631900,33578000610,68923264410,131282408400,269128937220,513791607420,1052049481860,2012616400080,4116715363800,7890371113950,16123801841550,30957699535776,63205303218876,121548660036300,247959266474052,477551179875952,973469712824056,1877405874732108,3824345300380220,7384942649010080 mov $1,$0 div $0,2 add $0,1 bin $1,$0
; ; Created by Mateusz Stompór on 21/07/2019. ; %ifndef LL_CONSTANTS %define LL_CONSTANTS ; List %define NULL_PTR 0 %endif
; A024015: 2^n-n^5. ; 1,1,-28,-235,-1008,-3093,-7712,-16679,-32512,-58537,-98976,-159003,-244736,-363101,-521440,-726607,-983040,-1288785,-1627424,-1951811,-2151424,-1986949,-959328,1952265,8814592,23788807,55227488,119868821,251225088,516359763,1049441824,2118854497,4261412864,8550799199,17134433760,34307216493,68659010560,137369609515,274798671776,549665589689,1099409227776,2198907399351,4397915819872,8795946013765,17592021128192,35184187560707,70368538214688,140737259010321,281474721906688,562949670946063 mov $1,2 pow $1,$0 pow $0,5 add $0,1 sub $1,$0 add $1,1 mov $0,$1
; A106709: Expansion of g.f. -2*x/(1 - 5*x + 2*x^2). ; 0,-2,-10,-46,-210,-958,-4370,-19934,-90930,-414782,-1892050,-8630686,-39369330,-179585278,-819187730,-3736768094,-17045465010,-77753788862,-354678014290,-1617882493726,-7380056440050,-33664517212798,-153562473183890,-700483331493854,-3195291711101490,-14575491892519742,-66486876040395730,-303283396416939166,-1383443230003904370,-6310649357185643518,-28786360325920408850,-131310502915230757214,-598979793924312968370,-2732277963791103327422,-12463430231106890700370,-56852595227952246847006 mul $0,2 mov $2,1 lpb $0 sub $0,2 sub $2,$1 sub $1,$2 mul $1,2 lpe mov $0,$1
SECTION "Output", ROM0[0] dw Rom0Label1 dw Rom0Label2 dw SramLabel1 dw SramLabel2 dw RomxLabel1 dw RomxLabel2 dw HramLabel SECTION "A", ROM0[$1324] Rom0Label1: LOAD "LA", SRAM[$BEAD] SramLabel1: PUSHS ; not inside a section or load section here yet SECTION "B", ROMX[$4698] RomxLabel1: LOAD "LB", HRAM[$FF86] HramLabel: ENDL RomxLabel2: POPS SramLabel2: ENDL Rom0Label2:
SECTION TEXT S_INPUT BUFFER, 100 S_OUTPUT BUFFER, 100 INPUT N1 INPUT N2 LOAD N1 SUB N2 STORE N1 OUTPUT N1 INPUT N1 LOAD N1 L1: SUB UM STORE N1 OUTPUT N1 JMPP L1 JMPZ CASE FIM: STOP CASE: ADD UM STORE N1 OUTPUT N1 SUB UM JMPZ FIM SECTION DATA BUFFER: SPACE 20 N1: SPACE 1 N2: SPACE 1 ZERO: CONST 0 UM: CONST 1
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/optimizer/rule/like_optimizations.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/optimizer/rule.hpp" #include "duckdb/function/scalar/string_functions.hpp" namespace duckdb { // The Like Optimization rule rewrites LIKE to optimized scalar functions (e.g.: prefix, suffix, and contains) class LikeOptimizationRule : public Rule { public: LikeOptimizationRule(ExpressionRewriter &rewriter); unique_ptr<Expression> Apply(LogicalOperator &op, vector<Expression *> &bindings, bool &changes_made) override; unique_ptr<Expression> ApplyRule(BoundFunctionExpression *expr, ScalarFunction function, string pattern); }; } // namespace duckdb
.size 8000 .text@48 ei jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld c, 44 ld b, 90 lbegin_waitly90: ldff a, (c) cmp a, b jrnz lbegin_waitly90 ld a, 11 ldff(40), a ld hl, 8000 ld b, 08 lbegin_settile0data: ld a, 00 ld(hl++), a ld a, 7e ld(hl++), a dec b jrnz lbegin_settile0data ld b, 08 lbegin_settile1data: ld a, 00 ld(hl++), a ld a, 81 ld(hl++), a dec b jrnz lbegin_settile1data ld b, 08 lbegin_settile2data: ld a, ff ld(hl++), a ld a, 81 ld(hl++), a dec b jrnz lbegin_settile2data ld b, 08 lbegin_settile3data: ld a, ff ld(hl++), a ld a, 7e ld(hl++), a dec b jrnz lbegin_settile3data ld c, 12 ld hl, 9800 lbegin_set_bgmap: ld b, 06 ld a, 02 lbegin_set_bgmapline_tilenos0to11: ld(hl++), a inc a ld(hl++), a dec a dec b jrnz lbegin_set_bgmapline_tilenos0to11 ld b, 0a lbegin_set_bgmapline_tilenos12to31: xor a, a ld(hl++), a inc a ld(hl++), a dec b jrnz lbegin_set_bgmapline_tilenos12to31 dec c jrnz lbegin_set_bgmap ld a, 27 ldff(47), a ld a, 80 ldff(68), a ld c, 69 xor a, a ldff(c), a ldff(c), a ld a, 94 ldff(c), a ld a, 52 ldff(c), a ld a, 08 ldff(c), a ld a, 21 ldff(c), a ld a, ff ldff(c), a ldff(c), a ld a, 20 ldff(41), a ld a, 02 ldff(ff), a ld c, 43 ld a, 91 ldff(40), a ei xor a, a .text@1000 lstatint: ldff(c), a ld a, 63 nop nop nop nop nop nop nop nop nop nop ldff(c), a pop hl ld a, c0 .text@1028 ldff(c), a xor a, a
; A304831: a(n) = 123*2^n - 135 (n>=1). ; 111,357,849,1833,3801,7737,15609,31353,62841,125817,251769,503673,1007481,2015097,4030329,8060793,16121721,32243577,64487289,128974713,257949561,515899257,1031798649,2063597433,4127195001,8254390137,16508780409,33017560953,66035122041,132070244217,264140488569,528280977273,1056561954681,2113123909497,4226247819129,8452495638393,16904991276921,33809982553977,67619965108089,135239930216313,270479860432761,540959720865657,1081919441731449,2163838883463033,4327677766926201,8655355533852537 mov $1,2 pow $1,$0 sub $1,1 mul $1,246 add $1,111
; SPIR-V ; Version: 1.0 ; Generator: Khronos Glslang Reference Front End; 10 ; Bound: 51 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" %32 OpExecutionMode %4 OriginUpperLeft OpSource ESSL 320 OpName %4 "main" OpName %8 "a" OpName %13 "buf0" OpMemberName %13 0 "_GLF_uniform_int_values" OpName %15 "" OpName %32 "_GLF_color" OpDecorate %12 ArrayStride 16 OpMemberDecorate %13 0 Offset 0 OpDecorate %13 Block OpDecorate %15 DescriptorSet 0 OpDecorate %15 Binding 0 OpDecorate %32 Location 0 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 -7563 %10 = OpTypeInt 32 0 %11 = OpConstant %10 2 %12 = OpTypeArray %6 %11 %13 = OpTypeStruct %12 %14 = OpTypePointer Uniform %13 %15 = OpVariable %14 Uniform %16 = OpConstant %6 0 %17 = OpConstant %6 1 %18 = OpTypePointer Uniform %6 %25 = OpTypeBool %29 = OpTypeFloat 32 %30 = OpTypeVector %29 4 %31 = OpTypePointer Output %30 %32 = OpVariable %31 Output %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function OpStore %8 %9 %19 = OpAccessChain %18 %15 %16 %17 %20 = OpLoad %6 %19 %21 = OpLoad %6 %8 %22 = OpSDiv %6 %20 %21 %23 = OpAccessChain %18 %15 %16 %16 %24 = OpLoad %6 %23 %26 = OpIEqual %25 %22 %24 OpSelectionMerge %28 None OpBranchConditional %26 %27 %46 %27 = OpLabel %33 = OpAccessChain %18 %15 %16 %17 %34 = OpLoad %6 %33 %35 = OpConvertSToF %29 %34 %36 = OpAccessChain %18 %15 %16 %16 %37 = OpLoad %6 %36 %38 = OpConvertSToF %29 %37 %39 = OpAccessChain %18 %15 %16 %16 %40 = OpLoad %6 %39 %41 = OpConvertSToF %29 %40 %42 = OpAccessChain %18 %15 %16 %17 %43 = OpLoad %6 %42 %44 = OpConvertSToF %29 %43 %45 = OpCompositeConstruct %30 %35 %38 %41 %44 OpStore %32 %45 OpBranch %28 %46 = OpLabel %47 = OpAccessChain %18 %15 %16 %16 %48 = OpLoad %6 %47 %49 = OpConvertSToF %29 %48 %50 = OpCompositeConstruct %30 %49 %49 %49 %49 OpStore %32 %50 OpBranch %28 %28 = OpLabel OpReturn OpFunctionEnd
SFX_Tink_3_Ch4: duty 2 unknownsfx0x10 58 unknownsfx0x20 4, 242, 0, 2 unknownsfx0x10 34 unknownsfx0x20 8, 226, 0, 2 unknownsfx0x10 8 endchannel
GUI.UP: equ 1 GUI.DOWN: equ 2 GUI.PLAY: equ 3 GUI.SHEET: equ 4 GUI.PLAYER: equ 5 GUI.HEARTS: equ 6 GUI.CLEAR: equ 7 GUI.TEXT: equ 8 SPRITE.GUI: equ 0 SPRITE.PLAYER: equ 8 SPRITE.CURSOR: equ 16 INPUT.UP: equ 1 INPUT.RIGHT: equ 3 INPUT.DOWN: equ 5 INPUT.LEFT: equ 7 INPUT.FIRE1: equ 9 INPUT.FIRE2: equ 10 INPUT.ESC: equ 11 INPUT.DEL: equ 12 INPUT.F1: equ 13 INPUT.F2: equ 14 INPUT.F5: equ 15 SHEETS.MAXIMUM: equ 18 SKOOTER.INITIALIZE_SP: equ $4015 SKOOTER.UPDATE_STATE: equ $415D SKOOTER.LIVES: equ $42C0 SKOOTER.INITIALIZE_SHEET_NUMBER: equ $42B9 SKOOTER.CALL_HANDLE_SELECTOR_CHOICES: equ $4350 SKOOTER.CALL_UPDATE_STATE: equ $5A40 SKOOTER.HANDLE_SELECTOR_CHOICES: equ $5E64 SKOOTER.SHEETS: equ $659F SKOOTER.RAM_VARIABLES: equ $C000 SKOOTER.SHEET_NUMBER: equ $C3BD STRUCT SHEET POINTER WORD ; pointer to next sheet MAP BLOCK 121 ; map of 11x11 tiles PLAYER BLOCK 2 ; X/Y ITEMS BLOCK 8 ; 4x X/Y combinations HEARTS BLOCK 8 ; 4x X/Y combinations ENEMIES BLOCK 8 ; 4x X/Y combinations UNKNOWN BLOCK 1 ; ? TEXT BYTE ; actual size depends on the level ENDS
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r14 push %r15 push %r8 push %r9 push %rcx push %rdi push %rsi lea addresses_WC_ht+0xff1c, %rcx nop xor %r12, %r12 vmovups (%rcx), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $1, %xmm4, %r15 nop nop nop nop and $34908, %r13 lea addresses_D_ht+0x1c30, %r14 nop nop nop nop nop cmp $6516, %r9 mov $0x6162636465666768, %r8 movq %r8, %xmm7 movups %xmm7, (%r14) nop nop nop nop xor %r15, %r15 lea addresses_UC_ht+0x1912, %r9 nop nop cmp %r15, %r15 movl $0x61626364, (%r9) inc %r12 lea addresses_WC_ht+0x11a52, %r12 add %r8, %r8 movl $0x61626364, (%r12) nop nop nop and $22963, %rcx lea addresses_A_ht+0xcfea, %rsi lea addresses_WT_ht+0x11112, %rdi nop nop nop nop nop sub $37051, %r9 mov $17, %rcx rep movsl nop add $8160, %rdi lea addresses_WC_ht+0x5412, %rsi nop nop add $28015, %r12 mov (%rsi), %r8w nop sub $45618, %r9 lea addresses_normal_ht+0x19f22, %rsi lea addresses_UC_ht+0x40d5, %rdi nop nop nop xor $45992, %r13 mov $5, %rcx rep movsb nop nop nop nop nop xor %rcx, %rcx pop %rsi pop %rdi pop %rcx pop %r9 pop %r8 pop %r15 pop %r14 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r13 push %r15 push %r9 push %rax push %rdi push %rsi // Store mov $0x26d1a20000000792, %rdi clflush (%rdi) nop nop nop nop xor $41450, %rsi movw $0x5152, (%rdi) nop nop nop nop add %r13, %r13 // Faulty Load lea addresses_US+0x1b912, %r15 nop nop nop nop and $4895, %rax movb (%r15), %r13b lea oracles, %r15 and $0xff, %r13 shlq $12, %r13 mov (%r15,%r13,1), %r13 pop %rsi pop %rdi pop %rax pop %r9 pop %r15 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 5, 'size': 2, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 1, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 1, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 10, 'size': 4, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 6, 'size': 4, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 8, 'size': 2, 'same': True, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
INCLUDE "graphics/grafix.inc" PUBLIC fill EXTERN w_pixeladdress ; EXTERN l_cmp .ws1 defw 0 .index defw 0 ;.sline defs 512 * 2 * 3 ;.sline2 defs 512 * 2 * 3 .fill pop bc pop de ; y pop hl ; x push hl push de push bc ld a,maxy cp e ret c ld a,1 cp h ret c call w_pixeladdress ld b,a ld a,1 jr z,cont; pixel is at bit 0... .loop3 rlca djnz loop3 .cont ; ld hl,sline ld hl,-maxx * 2 * 3 ; create buffer 2 on stack add hl,sp ; The stack size depends on the display height. ld (sl2ptr+1),hl ; We don't undersize it because we have lots of RAM ld sp,hl ld hl,-maxx * 2 * 3 ; create buffer 1 on stack add hl,sp ld sp,hl ld (w_sline+3),hl ld (ws1),hl ld b,a set 2,c ; semafor = 1 res 3,c ; indeks_ws = 0 call segm .petelka bit 3,c; indeks_ws1 == 0 ret z res 3,c; indeks_ws1 = 0 .dalej2 push hl pop ix; W = ws1 ld hl,(ws1) ld (index),hl bit 2,c jr z,w_sline res 2,c .sl2ptr ; ld hl,sline2 ld hl,0 ld (ws1),hl jr inner_loop .w_sline set 2,c ; ld hl,sline ld hl,0 ld (ws1),hl .inner_loop ld a,(index) cp ixl jr nz,dalej ld a,(index+1) cp ixh jr z,petelka .dalej dec ix ld d,(ix+0) dec ix ld e,(ix+0) dec ix ld b,(ix+0) call segm jr inner_loop .write ld (hl),b inc hl ld (hl),e inc hl ld (hl),d inc hl set 3,c ret .test_up_down ld a,(de) or b ld (de),a ; plot(x,y) push de call decy jr c, down ld a,(de) and b ; point(x, y - 1) jr z, test_write set 0,c jr down .test_write bit 0,c; if (is_above) { jr z,down res 0,c ; is_above = 0; call write .down pop de push de call incy jr c,wypad ld a,(de) and b ; point(x, y + 1) jr z, test_write2 set 1,c jr wypad .test_write2 bit 1,c; if (is_below) { jr z,wypad res 1,c ; is_below = 0; call write .wypad pop de ret .segm ; de - address ; b - mask of the pixel set 0,c set 1,c; is_above = 1, is_below = 1 push de ld a,b push af .loop1 ld a,(de) and b jr nz,right call test_up_down call decx jr nc,loop1 .right pop af ld b,a pop de .loop2 call incx ret c ld a,(de) and b ret nz call test_up_down jr loop2 ; enter: de = valid screen address ; b = uchar mask ; exit : carry = moved off screen ; de = new screen address left one pixel ; b = new bitmask left one pixel ; uses : af, b, de .decx rlc b ret nc bit 5,d jr nz,first_1 set 5,d ld a,e dec e and $1f ret nz scf ret .first_1 res 5,d or a ret ; b mask ; de - screen address .incx rrc b ret nc bit 5,d jr nz,first set 5,d or a ret .first res 5,d inc e ld a,e and $1f ret nz scf ret ; enter: de = valid screen address ; exit : carry = moved off screen ; de = new screen address one pixel up ; uses : af, de .decy bit 5,d jr z,decy_1 res 5,d call decy_1 ret c set 5,d ret .decy_1 ld a,d dec d and $07 ret nz ld a,$08 add a,d ld d,a ld a,e sub $20 ld e,a ret nc ld a,d sub $08 ld d,a cp $40 ret ; in: de - address ; exit : carry = moved off screen ; de = new screen address one pixel up ; uses : af, de .incy inc d ld a,d and $07 ret nz ld a,d sub $08 ld d,a ld a,e add a,$20 ld e,a ret nc ld a,d add a,$08 ld d,a and 95 cp $58 ccf ret ;#define TEST_UP_DOWN \ ;if (y > 0) { \ ; if (point(xs, y - 1)) is_above = 1; \ ; else if (is_above) { \ ; is_above = 0; \ ; ws1->xs = xs; \ ; ws1->y = y - 1; \ ; ws1++; \ ; indeks_ws1++; \ ; }; \ ;} \ ;if (y < 191) { \ ; if (point(xs, y + 1)) is_below = 1; \ ; else if (is_below) { \ ; is_below = 0; \ ; ws1->xs = xs; \ ; ws1->y = y + 1; \ ; ws1++; \ ; indeks_ws1++; \ ; } \ ;} ;struct segment { ; int xs; ; int y; ;}; ;struct segment sline[2 * 2 * 512 + 4]; ;struct segment *ws1 = sline; ;int indeks_ws1 = 0; ;void ;seg(int xs, int y) ;{ ; int txs = xs; ; char is_above = 1; ; char is_below = 1; ; for(; xs > 0; xs--) { ; if (point(xs, y)) break; ; plot(xs, y); ; TEST_UP_DOWN; ; } ; xs = txs; ; if (xs == 511) return; ; ++xs; ; for (; xs < 511; xs++) { ; if (point(xs, y)) return; ; plot(xs, y); ; TEST_UP_DOWN; ; } ;} ;void ;fill3(int x, int y) ;{ ; char l; ; int indeks; ; struct segment *W; ; int semafor = 1; ; ; ws1 = sline; ; indeks_ws1 = 0; ; seg(x, y); ; while (indeks_ws1 != 0) { ; W = ws1; ; indeks = indeks_ws1; ; indeks_ws1 = 0; ; if (semafor == 1) { ; semafor = 0; ; ws1 = &sline[2 * 256 + 2]; ; } else { ; semafor = 1; ; ws1 = sline; ; } ; while ((indeks--) > 0) { ; W--; ; seg(W->xs, W->y); ; } ; } ;} ;main() ;{ ;#asm ; ld a,6 ; out (255),a ;#endasm ; clg(); ; drawb(20, 20, 260, 120); ; fill(128, 128); ;}
%define ASCII_0 0x30 %define ASCII_NEWLINE 0xa %define BUFSIZE 10 ; print the integer pointed to by the first argument print: push ebp mov ebp, esp mov eax, [ebp + 8] mov ebx, 10 mov ecx, 0 sub esp, BUFSIZE; reserve space for the integer mov esi, BUFSIZE - 1 sub esi, ecx mov byte [ebp - 1], ASCII_NEWLINE add ecx, 1 ; adjust length .loop: ; push character on the stack ; store length in ecx mov edx, 0 ; zero upper bits of EDX:EAX div ebx ; divide by 10 add edx, ASCII_0 ; adjust to ascii mov esi, BUFSIZE - 1 sub esi, ecx mov [esp + esi], dl; store in the buffer add ecx, 1 ; adjust length cmp eax, 0 ; see if we are done jnz .loop mov eax, 4 ; write syscall mov ebx, 0 ; stdout fd mov edx, ecx ; length of string mov ecx, ebp sub ecx, edx ; location of output string int 0x80 mov esp, ebp pop ebp ret ; get the length of a null terminated string strlen: mov esi, [esp + 4] xor ebx, ebx .start: mov al, [esi + ebx] cmp al, 0 jz .done add ebx, 1 jmp .start .done: mov eax, ebx ret putc: mov edx, 1 mov eax, 4 mov ebx, 0 push 0xa mov ecx, esp int 0x80 add esp, 4 ret ; print a string to stdout prints: push dword [esp + 4] call strlen add esp, 4 mov edx, eax ; length of the string mov eax, 4 ; write syscall mov ebx, 0 ; stdout fd mov ecx, [esp + 4] ; location of string to print int 0x80 push 0xa ;print a newline call putc add esp, 4 ret exit: mov ebx, [esp + 4] mov eax, 1 int 0x80
; A226201: 8^n + n. ; 1,9,66,515,4100,32773,262150,2097159,16777224,134217737,1073741834,8589934603,68719476748,549755813901,4398046511118,35184372088847,281474976710672,2251799813685265,18014398509482002,144115188075855891,1152921504606846996,9223372036854775829,73786976294838206486,590295810358705651735,4722366482869645213720,37778931862957161709593,302231454903657293676570,2417851639229258349412379,19342813113834066795298844,154742504910672534362390557,1237940039285380274899124254,9903520314283042199192993823 mov $2,8 pow $2,$0 add $0,$2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2020 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. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Function API: ; UINT32 crc32_gzip_refl_by8_02( ; UINT32 init_crc, //initial CRC value, 32 bits ; const unsigned char *buf, //buffer pointer to calculate CRC on ; UINT64 len //buffer length in bytes (64-bit data) ; ); ; ; Authors: ; Erdinc Ozturk ; Vinodh Gopal ; James Guilford ; ; Reference paper titled "Fast CRC Computation for Generic Polynomials Using PCLMULQDQ Instruction" ; URL: http://download.intel.com/design/intarch/papers/323102.pdf ; ; ; sample yasm command line: ; yasm -f x64 -f elf64 -X gnu -g dwarf2 crc32_gzip_refl_by8 ; ; As explained here: ; http://docs.oracle.com/javase/7/docs/api/java/util/zip/package-summary.html ; CRC-32 checksum is described in RFC 1952 ; Implementing RFC 1952 CRC: ; http://www.ietf.org/rfc/rfc1952.txt %include "reg_sizes.asm" %define fetch_dist 1024 [bits 64] default rel section .text %ifidn __OUTPUT_FORMAT__, win64 %xdefine arg1 rcx %xdefine arg2 rdx %xdefine arg3 r8 %xdefine arg1_low32 ecx %else %xdefine arg1 rdi %xdefine arg2 rsi %xdefine arg3 rdx %xdefine arg1_low32 edi %endif %define TMP 16*0 %ifidn __OUTPUT_FORMAT__, win64 %define XMM_SAVE 16*2 %define VARIABLE_OFFSET 16*10+8 %else %define VARIABLE_OFFSET 16*2+8 %endif align 16 mk_global crc32_gzip_refl_by8_02, function crc32_gzip_refl_by8_02: not arg1_low32 sub rsp, VARIABLE_OFFSET %ifidn __OUTPUT_FORMAT__, win64 ; push the xmm registers into the stack to maintain vmovdqa [rsp + XMM_SAVE + 16*0], xmm6 vmovdqa [rsp + XMM_SAVE + 16*1], xmm7 vmovdqa [rsp + XMM_SAVE + 16*2], xmm8 vmovdqa [rsp + XMM_SAVE + 16*3], xmm9 vmovdqa [rsp + XMM_SAVE + 16*4], xmm10 vmovdqa [rsp + XMM_SAVE + 16*5], xmm11 vmovdqa [rsp + XMM_SAVE + 16*6], xmm12 vmovdqa [rsp + XMM_SAVE + 16*7], xmm13 %endif ; check if smaller than 256B cmp arg3, 256 jl .less_than_256 ; load the initial crc value vmovd xmm10, arg1_low32 ; initial crc ; receive the initial 64B data, xor the initial crc value vmovdqu xmm0, [arg2+16*0] vmovdqu xmm1, [arg2+16*1] vmovdqu xmm2, [arg2+16*2] vmovdqu xmm3, [arg2+16*3] vmovdqu xmm4, [arg2+16*4] vmovdqu xmm5, [arg2+16*5] vmovdqu xmm6, [arg2+16*6] vmovdqu xmm7, [arg2+16*7] ; XOR the initial_crc value vpxor xmm0, xmm10 vmovdqa xmm10, [rk3] ;xmm10 has rk3 and rk4 ;imm value of pclmulqdq instruction will determine which constant to use ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; we subtract 256 instead of 128 to save one instruction from the loop sub arg3, 256 ; at this section of the code, there is 128*x+y (0<=y<128) bytes of buffer. The fold_128_B_loop ; loop will fold 128B at a time until we have 128+y Bytes of buffer ; fold 128B at a time. This section of the code folds 8 xmm registers in parallel .fold_128_B_loop: add arg2, 128 prefetchnta [arg2+fetch_dist+0] vmovdqu xmm9, [arg2+16*0] vmovdqu xmm12, [arg2+16*1] vpclmulqdq xmm8, xmm0, xmm10, 0x10 vpclmulqdq xmm0, xmm0, xmm10 , 0x1 vpclmulqdq xmm13, xmm1, xmm10, 0x10 vpclmulqdq xmm1, xmm1, xmm10 , 0x1 vpxor xmm0, xmm9 vxorps xmm0, xmm8 vpxor xmm1, xmm12 vxorps xmm1, xmm13 prefetchnta [arg2+fetch_dist+32] vmovdqu xmm9, [arg2+16*2] vmovdqu xmm12, [arg2+16*3] vpclmulqdq xmm8, xmm2, xmm10, 0x10 vpclmulqdq xmm2, xmm2, xmm10 , 0x1 vpclmulqdq xmm13, xmm3, xmm10, 0x10 vpclmulqdq xmm3, xmm3, xmm10 , 0x1 vpxor xmm2, xmm9 vxorps xmm2, xmm8 vpxor xmm3, xmm12 vxorps xmm3, xmm13 prefetchnta [arg2+fetch_dist+64] vmovdqu xmm9, [arg2+16*4] vmovdqu xmm12, [arg2+16*5] vpclmulqdq xmm8, xmm4, xmm10, 0x10 vpclmulqdq xmm4, xmm4, xmm10 , 0x1 vpclmulqdq xmm13, xmm5, xmm10, 0x10 vpclmulqdq xmm5, xmm5, xmm10 , 0x1 vpxor xmm4, xmm9 vxorps xmm4, xmm8 vpxor xmm5, xmm12 vxorps xmm5, xmm13 prefetchnta [arg2+fetch_dist+96] vmovdqu xmm9, [arg2+16*6] vmovdqu xmm12, [arg2+16*7] vpclmulqdq xmm8, xmm6, xmm10, 0x10 vpclmulqdq xmm6, xmm6, xmm10 , 0x1 vpclmulqdq xmm13, xmm7, xmm10, 0x10 vpclmulqdq xmm7, xmm7, xmm10 , 0x1 vpxor xmm6, xmm9 vxorps xmm6, xmm8 vpxor xmm7, xmm12 vxorps xmm7, xmm13 sub arg3, 128 jge .fold_128_B_loop ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; add arg2, 128 ; at this point, the buffer pointer is pointing at the last y Bytes of the buffer, where 0 <= y < 128 ; the 128B of folded data is in 8 of the xmm registers: xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7 ; fold the 8 xmm registers to 1 xmm register with different constants vmovdqa xmm10, [rk9] vpclmulqdq xmm8, xmm0, xmm10, 0x1 vpclmulqdq xmm0, xmm0, xmm10, 0x10 vpxor xmm7, xmm8 vxorps xmm7, xmm0 vmovdqa xmm10, [rk11] vpclmulqdq xmm8, xmm1, xmm10, 0x1 vpclmulqdq xmm1, xmm1, xmm10, 0x10 vpxor xmm7, xmm8 vxorps xmm7, xmm1 vmovdqa xmm10, [rk13] vpclmulqdq xmm8, xmm2, xmm10, 0x1 vpclmulqdq xmm2, xmm2, xmm10, 0x10 vpxor xmm7, xmm8 vpxor xmm7, xmm2 vmovdqa xmm10, [rk15] vpclmulqdq xmm8, xmm3, xmm10, 0x1 vpclmulqdq xmm3, xmm3, xmm10, 0x10 vpxor xmm7, xmm8 vxorps xmm7, xmm3 vmovdqa xmm10, [rk17] vpclmulqdq xmm8, xmm4, xmm10, 0x1 vpclmulqdq xmm4, xmm4, xmm10, 0x10 vpxor xmm7, xmm8 vpxor xmm7, xmm4 vmovdqa xmm10, [rk19] vpclmulqdq xmm8, xmm5, xmm10, 0x1 vpclmulqdq xmm5, xmm5, xmm10, 0x10 vpxor xmm7, xmm8 vxorps xmm7, xmm5 vmovdqa xmm10, [rk1] vpclmulqdq xmm8, xmm6, xmm10, 0x1 vpclmulqdq xmm6, xmm6, xmm10, 0x10 vpxor xmm7, xmm8 vpxor xmm7, xmm6 ; instead of 128, we add 128-16 to the loop counter to save 1 instruction from the loop ; instead of a cmp instruction, we use the negative flag with the jl instruction add arg3, 128-16 jl .final_reduction_for_128 ; now we have 16+y bytes left to reduce. 16 Bytes is in register xmm7 and the rest is in memory ; we can fold 16 bytes at a time if y>=16 ; continue folding 16B at a time .16B_reduction_loop: vpclmulqdq xmm8, xmm7, xmm10, 0x1 vpclmulqdq xmm7, xmm7, xmm10, 0x10 vpxor xmm7, xmm8 vmovdqu xmm0, [arg2] vpxor xmm7, xmm0 add arg2, 16 sub arg3, 16 ; instead of a cmp instruction, we utilize the flags with the jge instruction ; equivalent of: cmp arg3, 16-16 ; check if there is any more 16B in the buffer to be able to fold jge .16B_reduction_loop ;now we have 16+z bytes left to reduce, where 0<= z < 16. ;first, we reduce the data in the xmm7 register .final_reduction_for_128: add arg3, 16 je .128_done ; here we are getting data that is less than 16 bytes. ; since we know that there was data before the pointer, we can offset ; the input pointer before the actual point, to receive exactly 16 bytes. ; after that the registers need to be adjusted. .get_last_two_xmms: vmovdqa xmm2, xmm7 vmovdqu xmm1, [arg2 - 16 + arg3] ; get rid of the extra data that was loaded before ; load the shift constant lea rax, [pshufb_shf_table] add rax, arg3 vmovdqu xmm0, [rax] vpshufb xmm7, xmm0 vpxor xmm0, [mask3] vpshufb xmm2, xmm0 vpblendvb xmm2, xmm2, xmm1, xmm0 ;;;;;;;;;; vpclmulqdq xmm8, xmm7, xmm10, 0x1 vpclmulqdq xmm7, xmm7, xmm10, 0x10 vpxor xmm7, xmm8 vpxor xmm7, xmm2 .128_done: ; compute crc of a 128-bit value vmovdqa xmm10, [rk5] vmovdqa xmm0, xmm7 ;64b fold vpclmulqdq xmm7, xmm10, 0 vpsrldq xmm0, 8 vpxor xmm7, xmm0 ;32b fold vmovdqa xmm0, xmm7 vpslldq xmm7, 4 vpclmulqdq xmm7, xmm10, 0x10 vpxor xmm7, xmm0 ;barrett reduction .barrett: vpand xmm7, [mask2] vmovdqa xmm1, xmm7 vmovdqa xmm2, xmm7 vmovdqa xmm10, [rk7] vpclmulqdq xmm7, xmm10, 0 vpxor xmm7, xmm2 vpand xmm7, [mask] vmovdqa xmm2, xmm7 vpclmulqdq xmm7, xmm10, 0x10 vpxor xmm7, xmm2 vpxor xmm7, xmm1 vpextrd eax, xmm7, 2 .cleanup: not eax %ifidn __OUTPUT_FORMAT__, win64 vmovdqa xmm6, [rsp + XMM_SAVE + 16*0] vmovdqa xmm7, [rsp + XMM_SAVE + 16*1] vmovdqa xmm8, [rsp + XMM_SAVE + 16*2] vmovdqa xmm9, [rsp + XMM_SAVE + 16*3] vmovdqa xmm10, [rsp + XMM_SAVE + 16*4] vmovdqa xmm11, [rsp + XMM_SAVE + 16*5] vmovdqa xmm12, [rsp + XMM_SAVE + 16*6] vmovdqa xmm13, [rsp + XMM_SAVE + 16*7] %endif add rsp, VARIABLE_OFFSET ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 .less_than_256: ; check if there is enough buffer to be able to fold 16B at a time cmp arg3, 32 jl .less_than_32 ; if there is, load the constants vmovdqa xmm10, [rk1] ; rk1 and rk2 in xmm10 vmovd xmm0, arg1_low32 ; get the initial crc value vmovdqu xmm7, [arg2] ; load the plaintext vpxor xmm7, xmm0 ; update the buffer pointer add arg2, 16 ; update the counter. subtract 32 instead of 16 to save one instruction from the loop sub arg3, 32 jmp .16B_reduction_loop align 16 .less_than_32: ; mov initial crc to the return value. this is necessary for zero-length buffers. mov eax, arg1_low32 test arg3, arg3 je .cleanup vmovd xmm0, arg1_low32 ; get the initial crc value cmp arg3, 16 je .exact_16_left jl .less_than_16_left vmovdqu xmm7, [arg2] ; load the plaintext vpxor xmm7, xmm0 ; xor the initial crc value add arg2, 16 sub arg3, 16 vmovdqa xmm10, [rk1] ; rk1 and rk2 in xmm10 jmp .get_last_two_xmms align 16 .less_than_16_left: ; use stack space to load data less than 16 bytes, zero-out the 16B in memory first. vpxor xmm1, xmm1 mov r11, rsp vmovdqa [r11], xmm1 cmp arg3, 4 jl .only_less_than_4 ; backup the counter value mov r9, arg3 cmp arg3, 8 jl .less_than_8_left ; load 8 Bytes mov rax, [arg2] mov [r11], rax add r11, 8 sub arg3, 8 add arg2, 8 .less_than_8_left: cmp arg3, 4 jl .less_than_4_left ; load 4 Bytes mov eax, [arg2] mov [r11], eax add r11, 4 sub arg3, 4 add arg2, 4 .less_than_4_left: cmp arg3, 2 jl .less_than_2_left ; load 2 Bytes mov ax, [arg2] mov [r11], ax add r11, 2 sub arg3, 2 add arg2, 2 .less_than_2_left: cmp arg3, 1 jl .zero_left ; load 1 Byte mov al, [arg2] mov [r11], al .zero_left: vmovdqa xmm7, [rsp] vpxor xmm7, xmm0 ; xor the initial crc value lea rax,[pshufb_shf_table] vmovdqu xmm0, [rax + r9] vpshufb xmm7,xmm0 jmp .128_done align 16 .exact_16_left: vmovdqu xmm7, [arg2] vpxor xmm7, xmm0 ; xor the initial crc value jmp .128_done .only_less_than_4: cmp arg3, 3 jl .only_less_than_3 ; load 3 Bytes mov al, [arg2] mov [r11], al mov al, [arg2+1] mov [r11+1], al mov al, [arg2+2] mov [r11+2], al vmovdqa xmm7, [rsp] vpxor xmm7, xmm0 ; xor the initial crc value vpslldq xmm7, 5 jmp .barrett .only_less_than_3: cmp arg3, 2 jl .only_less_than_2 ; load 2 Bytes mov al, [arg2] mov [r11], al mov al, [arg2+1] mov [r11+1], al vmovdqa xmm7, [rsp] vpxor xmm7, xmm0 ; xor the initial crc value vpslldq xmm7, 6 jmp .barrett .only_less_than_2: ; load 1 Byte mov al, [arg2] mov [r11], al vmovdqa xmm7, [rsp] vpxor xmm7, xmm0 ; xor the initial crc value vpslldq xmm7, 7 jmp .barrett section .data ; precomputed constants align 16 rk1: dq 0x00000000ccaa009e rk2: dq 0x00000001751997d0 rk3: dq 0x000000014a7fe880 rk4: dq 0x00000001e88ef372 rk5: dq 0x00000000ccaa009e rk6: dq 0x0000000163cd6124 rk7: dq 0x00000001f7011640 rk8: dq 0x00000001db710640 rk9: dq 0x00000001d7cfc6ac rk10: dq 0x00000001ea89367e rk11: dq 0x000000018cb44e58 rk12: dq 0x00000000df068dc2 rk13: dq 0x00000000ae0b5394 rk14: dq 0x00000001c7569e54 rk15: dq 0x00000001c6e41596 rk16: dq 0x0000000154442bd4 rk17: dq 0x0000000174359406 rk18: dq 0x000000003db1ecdc rk19: dq 0x000000015a546366 rk20: dq 0x00000000f1da05aa mask: dq 0xFFFFFFFFFFFFFFFF, 0x0000000000000000 mask2: dq 0xFFFFFFFF00000000, 0xFFFFFFFFFFFFFFFF mask3: dq 0x8080808080808080, 0x8080808080808080 pshufb_shf_table: ; use these values for shift constants for the pshufb instruction ; different alignments result in values as shown: ; dq 0x8887868584838281, 0x008f8e8d8c8b8a89 ; shl 15 (16-1) / shr1 ; dq 0x8988878685848382, 0x01008f8e8d8c8b8a ; shl 14 (16-3) / shr2 ; dq 0x8a89888786858483, 0x0201008f8e8d8c8b ; shl 13 (16-4) / shr3 ; dq 0x8b8a898887868584, 0x030201008f8e8d8c ; shl 12 (16-4) / shr4 ; dq 0x8c8b8a8988878685, 0x04030201008f8e8d ; shl 11 (16-5) / shr5 ; dq 0x8d8c8b8a89888786, 0x0504030201008f8e ; shl 10 (16-6) / shr6 ; dq 0x8e8d8c8b8a898887, 0x060504030201008f ; shl 9 (16-7) / shr7 ; dq 0x8f8e8d8c8b8a8988, 0x0706050403020100 ; shl 8 (16-8) / shr8 ; dq 0x008f8e8d8c8b8a89, 0x0807060504030201 ; shl 7 (16-9) / shr9 ; dq 0x01008f8e8d8c8b8a, 0x0908070605040302 ; shl 6 (16-10) / shr10 ; dq 0x0201008f8e8d8c8b, 0x0a09080706050403 ; shl 5 (16-11) / shr11 ; dq 0x030201008f8e8d8c, 0x0b0a090807060504 ; shl 4 (16-12) / shr12 ; dq 0x04030201008f8e8d, 0x0c0b0a0908070605 ; shl 3 (16-13) / shr13 ; dq 0x0504030201008f8e, 0x0d0c0b0a09080706 ; shl 2 (16-14) / shr14 ; dq 0x060504030201008f, 0x0e0d0c0b0a090807 ; shl 1 (16-15) / shr15 dq 0x8786858483828100, 0x8f8e8d8c8b8a8988 dq 0x0706050403020100, 0x000e0d0c0b0a0908
#include <fcntl.h> #include <sys/stat.h> #include "./capsicum-test.h" // There was a Capsicum-related regression in FreeBSD renameat, // which affects certain cases independent of Capsicum or capability mode // // added to test the renameat syscall for the case that // - the "to" file already exists // - the "to" file is specified by an absolute path // - the "to" file descriptor is used // (this descriptor should be ignored if absolute path is provided) // // details at: https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=222258 const char * create_tmp_src(const char* filename) { const char *src_path = TmpFile(filename); int src_fd = open(src_path, O_CREAT|O_RDWR, 0644); close(src_fd); return src_path; } TEST(Rename, AbsDesignationSame) { const char *src_path = create_tmp_src("rename_test"); EXPECT_OK(rename(src_path, src_path)); unlink(src_path); } TEST(RenameAt, AbsDesignationSame) { const char *src_path = create_tmp_src("renameat_test"); const char *dir_path = TmpFile("renameat_test_dir"); EXPECT_OK(mkdir(dir_path, 0755)); // random temporary directory descriptor int dfd = open(dir_path, O_DIRECTORY); // Various rename from/to the same absolute path; in each case the source // and dest directory FDs should be irrelevant. EXPECT_OK(renameat(AT_FDCWD, src_path, AT_FDCWD, src_path)); EXPECT_OK(renameat(AT_FDCWD, src_path, dfd, src_path)); EXPECT_OK(renameat(dfd, src_path, AT_FDCWD, src_path)); EXPECT_OK(renameat(dfd, src_path, dfd, src_path)); close(dfd); rmdir(dir_path); unlink(src_path); }
#include <iostream> #include <vector> #include <stack> #include <queue> #include <map> // #include <unordered_map> // can't compile on poj #include <algorithm> #include <cstring> #include <climits> using namespace std; /* O(log(m + n)) TODO !! Some Bugs, can't pass below test case online: [0,0,0,0,0] [-1,0,0,0,0,0,1] */ class Solution { private: double getKth(int* nums1, int* nums2, int m, int n, int k) { // let m <= n if (m > n) return getKth(nums2, nums1, n, m, k); if (m == 0) return nums2[k - 1]; if (k == 1) return min(nums1[0], nums2[0]); int j = min(k / 2, n); int i = k - j; if (nums1[i - 1] > nums2[j - 1]) return getKth(nums1, nums2 + j, m, n - j, k - j); else return getKth(nums1 + i, nums2, m - i, n, k - i); } double findMedian(int* nums1, int* nums2, int m, int n) { int l = (m + n + 1) >> 1; int r = (m + n + 2) >> 1; return (getKth(nums1, nums2, m, n, l) + getKth(nums1, nums2, m, n, r)) / 2.0; } public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); int *pNums1 = m > 0 ? &nums1[0] : nullptr; int *pNums2 = n > 0 ? &nums2[0] : nullptr; return findMedian(pNums1, pNums2, m, n); } }; int main() { // vector<int> nums1 = {1, 2}; vector<int> nums2 = {3, 4}; // vector<int> nums1 = {0, 0}; vector<int> nums2 = {0, 0}; // vector<int> nums1 = {}; vector<int> nums2 = {1}; vector<int> nums1 = {0, 0, 0, 0, 0}; vector<int> nums2 = {-1, 0, 0, 0, 0, 0, 1}; Solution sol; cout << sol.findMedianSortedArrays(nums1, nums2) << endl; return 0; }
; A060851: a(n) = (2n-1) * 3^(2n-1). ; 3,81,1215,15309,177147,1948617,20726199,215233605,2195382771,22082967873,219667417263,2165293113021,21182215236075,205891132094649,1990280943581607,19147875284802357,183448998696332259,1751104078464989745,16660504517966902431,158049650967740074413,1495392851464002242523,14115049597965094337961,132944071794787516438935,1249674274871002654525989,11725667132300258949914067,109838392116853446081848097,1027312020387041054530226319,9594706605501609848914377885,89492445247678651863510470091 mul $0,2 add $0,1 mov $1,3 pow $1,$0 mul $1,$0 mov $0,$1
; ; Copyright (C) 2017-2017 Intel Corporation. ; SPDX-License-Identifier: MIT ; PUBLIC iretTest PUBLIC iret_func .code iret_func PROC mov rax,-2 iretq iret_func ENDP iretTest PROC push rbx ; Move the stack pointer down, so that we can check that the stack pointer ; is correctly restored by the iretq mov rbx,rsp sub rsp,80 mov rax,ss push rax push rbx ; Restored stack pointer pushfq mov rax,cs push rax call iret_func pop rbx ret iretTest ENDP end
; A277229: Convolution of the odd-indexed triangular numbers (A000384(n+1)) and the squares (A000290). ; 0,1,10,48,158,413,924,1848,3396,5841,9526,14872,22386,32669,46424,64464,87720,117249,154242,200032,256102,324093,405812,503240,618540,754065,912366,1096200,1308538,1552573,1831728,2149664,2510288,2917761,3376506,3891216,4466862,5108701,5822284,6613464,7488404,8453585,9515814,10682232,11960322,13357917,14883208,16544752,18351480,20312705,22438130,24737856,27222390,29902653,32789988,35896168,39233404,42814353,46652126,50760296,55152906,59844477,64850016,70185024,75865504,81907969,88329450,95147504,102380222,110046237,118164732,126755448,135838692,145435345,155566870,166255320,177523346,189394205,201891768,215040528,228865608,243392769,258648418,274659616,291454086,309060221,327507092,346824456,367042764,388193169,410307534,433418440,457559194,482763837,509067152,536504672,565112688,594928257,625989210,658334160 lpb $0 add $3,$0 sub $0,1 add $2,$3 add $1,$2 add $4,$3 add $2,$4 add $3,$0 lpe mov $0,$1
// By KRT girl xiplus #include <bits/stdc++.h> #define endl '\n' using namespace std; int main(){ // ios::sync_with_stdio(false); // cin.tie(0); int t; cin>>t; string s; while(t--){ cin>>s; int sz=s.size(); int sum=0; for(int q=0;q<sz;q++){ sum+=s[sz-q-1]*(q%2+1); } if(sum%3)cout<<"No"<<endl; else cout<<"Yes"<<endl; } }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r15 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x874, %rsi nop nop and $23932, %r15 mov (%rsi), %di add %r10, %r10 lea addresses_UC_ht+0x14234, %rsi nop nop nop nop nop cmp %rax, %rax vmovups (%rsi), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $0, %xmm0, %rbx nop nop nop nop nop and $28970, %rax lea addresses_D_ht+0xc904, %rbx nop nop nop xor %rsi, %rsi mov $0x6162636465666768, %rax movq %rax, (%rbx) nop nop nop and $25484, %rbx lea addresses_WT_ht+0x1e434, %rsi lea addresses_D_ht+0x2434, %rdi nop cmp %r13, %r13 mov $4, %rcx rep movsb nop nop nop nop nop cmp %rbx, %rbx lea addresses_normal_ht+0xe434, %rax nop cmp %rcx, %rcx movups (%rax), %xmm5 vpextrq $0, %xmm5, %r13 nop nop nop xor $1422, %r10 lea addresses_UC_ht+0x1ab34, %rsi lea addresses_D_ht+0x10034, %rdi nop nop nop nop xor %rbx, %rbx mov $75, %rcx rep movsb nop nop cmp $64017, %rsi lea addresses_WC_ht+0x1dc82, %rsi cmp %rax, %rax mov $0x6162636465666768, %r15 movq %r15, (%rsi) nop xor $35393, %rax lea addresses_WT_ht+0x5bac, %r10 nop nop nop nop and $12703, %rax mov (%r10), %di nop nop nop nop nop and %rbx, %rbx pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r15 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r15 push %r8 push %r9 push %rax push %rcx push %rdi push %rsi // REPMOV mov $0x1efce60000000bf4, %rsi lea addresses_US+0x9954, %rdi nop nop nop nop and $49162, %r15 mov $3, %rcx rep movsl nop add $39423, %rdi // Faulty Load lea addresses_UC+0xa434, %rsi nop nop nop cmp $60246, %r15 movups (%rsi), %xmm7 vpextrq $0, %xmm7, %r9 lea oracles, %rsi and $0xff, %r9 shlq $12, %r9 mov (%rsi,%r9,1), %r9 pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r8 pop %r15 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} {'src': {'congruent': 4, 'same': False, 'type': 'addresses_NC'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_US'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 9, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': True, 'type': 'addresses_D_ht'}} {'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'47': 3, '00': 44, 'ff': 23, 'e0': 8} 00 e0 ff 00 00 00 00 00 00 ff ff ff ff 47 00 ff e0 ff 00 ff ff 00 00 ff 00 ff 00 00 00 ff 00 00 47 00 00 ff 00 ff 00 00 e0 00 ff e0 00 00 e0 00 00 ff 47 ff ff 00 00 00 ff 00 e0 00 00 ff ff 00 00 e0 00 00 00 00 e0 00 ff 00 00 00 ff 00 */
BITS 16 org 4000h disk_buffer equ 2000h jmp start jmp reset_unreal ; Required by os_load_file (some BIOSes like to destroy cr0!?) start: cli ; Clear interrupts mov ax, 0 mov ss, ax ; Set stack segment and pointer mov sp, 0FFFEh sti ; Restore interrupts cld ; The default direction for string operations ; will be 'up' - incrementing address in RAM mov ax, 0000h ; Set all segments to match where the bootloader is loaded mov ds, ax mov es, ax mov ax, 1000h mov fs, ax mov [bootdev], dl mov [Sides], bx mov [SecsPerTrack], cx mov eax, 0 ; Needed for some older BIOSes mov si, .dbg_info call os_print_string mov al, [bootdev] call os_print_2hex call os_print_newline mov ax, .sys_already_started mov bx, 0 cmp byte [fs:8000h], 0 ; Check if INPYOOS.SYS is already loaded jne .catastrophic_failure mov si, .load_msg1 call os_print_string mov cx, 0 int 12h cmp ax, 192 jl .not_enough_memory push es mov ax, .system_name mov es, [.load_sgmt] mov cx, 8000h call os_load_file jc .catastrophic_failure pop es mov si, .load_msg4 call os_print_string mov ax, .vesa_name mov cx, 7000h call os_load_file jc .catastrophic_failure mov si, .load_msg4_5 call os_print_string mov ax, .bg_name mov cx, 7100h call os_load_file jnc .background_ok mov byte [7100h], 0 .background_ok: mov si, .load_msg5 call os_print_string mov ax, .font_name mov cx, 8000h call os_load_file jc .catastrophic_failure mov si, .load_msg6 call os_print_string mov ax, .fileman_name mov cx, 9000h call os_load_file jc .catastrophic_failure ; Enable Unreal Mode mov si, .unreal_msg1 call os_print_string cli ; no interrupts push ds ; save real mode mov si, .unreal_msg2 call os_print_string lgdt [.gdtinfo] ; load gdt register mov eax, cr0 ; switch to pmode by or al,1 ; set pmode bit mov si, .unreal_msg3 call os_print_string mov cr0, eax jmp .good ; tell 386/486 to not crash .good: mov bx, 0x08 ; select descriptor 1 mov ds, bx ; 8h = 1000b and al, 0xFE ; back to realmode mov cr0, eax ; by toggling bit again pop ds ; get back old segment sti mov si, .unreal_msg4 call os_print_string mov ax, 0 mov ah, 88h ; Also get the high memory (>1MB)... int 15h cmp ax, 0 ; If the computer doesn't have any high memory, skip the A20 je .A20_on mov si, .a20_try1 call os_print_string call A20_check mov si, .a20_try2 call os_print_string call enable_A20_1 call A20_check mov si, .a20_try3 call os_print_string call enable_A20_2 call A20_check mov si, .a20_try4 call os_print_string call enable_A20_3 call A20_check mov si, .a20_try5 call os_print_string call enable_A20_4 call A20_check jnc .A20_on mov si, .err_msg call os_print_string .error_loop: hlt jmp .error_loop .A20_on: mov dl, [bootdev] jmp long 1000h:8000h .catastrophic_failure: push ax mov si, .cf_msg call os_print_string pop si call os_print_string call os_print_newline cmp bx, 0 je .no_desc mov si, .error_desc call os_print_string mov si, bx call os_print_string call os_print_newline .no_desc: jmp $ .not_enough_memory: mov si, .mem_msg call os_print_string jmp $ .gdtinfo: dw .gdt_end - .gdt - 1 ;last byte in table dd .gdt ;start of table .gdt dd 0,0 ; entry 0 is always unused .flatdesc db 0xff, 0xff, 0, 0, 0, 10010010b, 11001111b, 0 .gdt_end: .system_name db 'INPYOOS.SYS', 0 .load_sgmt dw 1000h .load_msg1 db 'InpyoOS is starting up...', 13, 10, 10 .load_msg2 db 'Loading InpyoOS kernel...', 13, 10, 0 .load_msg4 db 'Loading VESA color palette...', 13, 10, 0 .load_msg4_5 db 'Loading desktop background...', 13, 10, 0 .load_msg5 db 'Loading InpyoOS System Font...', 13, 10, 0 .load_msg6 db 'Loading InpyoOS File Manager...', 13, 10, 0 .mem_msg db 'Not enough memory to start InpyoOS!', 13, 10 .mem_msg2 db '192K of RAM is required!', 0 .a20_try1 db 'Checking if the A20 line is already enabled...', 0 .a20_try2 db 'Attempting to enable the A20 line via the keyboard controller...', 0 .a20_try3 db 'Attempting to enable the A20 line via the fast A20 gate...', 0 .a20_try4 db 'Attempting to enable the A20 line via the BIOS...', 0 .a20_try5 db 'Attempting to enable the A20 line via the 0xEE port...', 0 .unreal_msg1 db 'Preparing for switching to protected mode...', 13, 10, 0 .unreal_msg2 db 'Loading the GDT register...', 13, 10, 0 .unreal_msg3 db 'Switching to protected mode...', 13, 10, 0 .unreal_msg4 db 'We', 39, 're in unreal mode!', 13, 10, 0 .boot_msg1 db 'Preparing for jumping to INPYOOS.SYS...', 13, 10, 0 .fail_msg1 db ' fail.', 13, 10, 0 .fail_msg2 db 'Expected ', 0 .fail_msg3 db ', but received ', 0 .succ_msg1 db ' success!', 13, 10, 0 .succ_msg2 db 'Expected ', 0 .succ_msg3 db ', received ', 0 .err_msg db 'Error enabling the A20 line!', 0 .fileman_name db 'FILEMAN.APP', 0 .font_name db 'FONT.SYS', 0 .vesa_name db 'VESA.SYS', 0 .bg_name db 'BG.SYS', 0 .cf_msg db 'Something went terribly wrong, and InpyoOS was shut down.', 13, 10, 'Error: ', 0 .sys_already_started db 'System already booted, jumped into nowhere', 0 .error_desc db 'Error description: ', 0 .dbg_info db 'Boot device: ', 0 reset_unreal: pushad cli ; no interrupts push ds ; save real mode mov ax, 0 mov ds, ax lgdt [start.gdtinfo] ; load gdt register mov eax, cr0 ; switch to pmode by or al,1 ; set pmode bit mov cr0, eax jmp .good ; tell 386/486 to not crash .good: mov bx, 0x08 ; select descriptor 1 mov ds, bx ; 8h = 1000b and al, 0xFE ; back to realmode mov cr0, eax ; by toggling bit again pop ds ; get back old segment sti popad retf enable_A20_1: cli call .a20wait mov al, 0xAD out 0x64, al call .a20wait mov al, 0xD0 out 0x64, al call .a20wait2 in al, 0x60 push eax call .a20wait mov al, 0xD1 out 0x64, al call .a20wait pop eax or al, 2 out 0x60, al call .a20wait mov al, 0xAE out 0x64, al call .a20wait sti ret .a20wait: in al, 0x64 test al, 2 jnz .a20wait ret .a20wait2: in al, 0x64 test al, 1 jz .a20wait2 ret enable_A20_2: in al, 0x92 or al, 2 out 0x92, al ret enable_A20_3: mov ax, 2403h ;--- A20-Gate Support --- int 15h jb .exit ;INT 15h is not supported cmp ah, 0 jnz .exit ;INT 15h is not supported mov ax, 2402h ;--- A20-Gate Status --- int 15h jb .exit ;couldn't get status cmp ah, 0 jnz .exit ;couldn't get status cmp al, 1 jz .exit ;A20 is already activated mov ax, 2401h ;--- A20-Gate Activate --- int 15h jb .exit ;couldn't activate the gate cmp ah, 0 jnz .exit ;couldn't activate the gate .exit: ret enable_A20_4: in al, 0xee ret A20_check: mov esi, 0x000000 mov edi, 0x100000 mov byte [esi], 0xFF mov byte [edi], 0x11 mov byte al, [esi] mov byte bl, [edi] cmp byte al, bl jne .A20_on push esi mov si, start.fail_msg1 call os_print_string mov si, start.fail_msg2 call os_print_string mov al, 0xFF call os_print_2hex mov si, start.fail_msg3 call os_print_string pop esi mov al, [esi] call os_print_2hex call os_print_newline stc ret .A20_on: push esi mov si, start.succ_msg1 call os_print_string mov si, start.succ_msg2 call os_print_string mov al, 0xFF call os_print_2hex mov si, start.succ_msg3 call os_print_string pop esi mov al, [esi] call os_print_2hex call os_print_newline clc ret ; ------------------------------------------------------------------ ; os_load_file -- Load file into RAM ; IN: AX = location of filename, CX = location in RAM to load file ; OUT: BX = file size (in bytes), carry set if file not found os_load_file: push ax mov [.old_segment], es mov es, [.default_segment] call os_string_uppercase call int_filename_convert mov [.filename_loc], ax ; Store filename location mov [.load_position], cx ; And where to load the file! mov eax, 0 ; Needed for some older BIOSes call disk_reset_floppy ; In case floppy has been changed jnc .floppy_ok ; Did the floppy reset OK? jmp $ .floppy_ok: ; Ready to read first block of data mov ax, 19 ; Root dir starts at logical sector 19 call disk_convert_l2hts mov si, disk_buffer ; ES:BX should point to our buffer mov bx, si mov ah, 2 ; Params for int 13h: read floppy sectors mov al, 14 ; 14 root directory sectors pusha ; Prepare to enter loop .read_root_dir: popa pusha stc ; A few BIOSes clear, but don't set properly int 13h ; Read sectors jnc .search_root_dir ; No errors = continue call disk_reset_floppy ; Problem = reset controller and try again jnc .read_root_dir popa jmp .drive_problem ; Double error = exit .search_root_dir: popa mov cx, word 224 ; Search all entries in root dir mov bx, -32 ; Begin searching at offset 0 in root dir .next_root_entry: add bx, 32 ; Bump searched entries by 1 (offset + 32 bytes) mov di, disk_buffer ; Point root dir at next entry add di, bx mov al, [di] ; First character of name cmp al, 0 ; Last file name already checked? je .root_problem cmp al, 229 ; Was this file deleted? je .next_root_entry ; If yes, skip it mov al, [di+11] ; Get the attribute byte cmp al, 0Fh ; Is this a special Windows entry? je .next_root_entry test al, 18h ; Is this a directory entry or volume label? jnz .next_root_entry mov byte [di+11], 0 ; Add a terminator to directory name entry mov ax, di ; Convert root buffer name to upper case call os_string_uppercase mov si, [.filename_loc] ; DS:SI = location of filename to load call os_string_compare ; Current entry same as requested? jc .found_file_to_load loop .next_root_entry .root_problem: stc ; return with size = 0 and carry set pop ax mov bx, .root_problem_msg ret .drive_problem: stc ; return with size = 0 and carry set pop ax mov bx, .drive_problem_msg ret .fat_problem: stc ; return with size = 0 and carry set pop ax mov bx, .fat_problem_msg ret .sector_problem: stc ; return with size = 0 and carry set pop ax mov bx, .sector_problem_msg ret .found_file_to_load: ; Now fetch cluster and load FAT into RAM mov ax, [di+28] ; Store file size to return to calling routine mov word [.file_size], ax cmp ax, 0 ; If the file size is zero, don't bother trying je .end ; to read more clusters mov ax, [di+26] ; Now fetch cluster and load FAT into RAM mov word [.cluster], ax mov ax, 1 ; Sector 1 = first sector of first FAT call disk_convert_l2hts mov di, disk_buffer ; ES:BX points to our buffer mov bx, di mov ah, 2 ; int 13h params: read sectors mov al, 9 ; And read 9 of them pusha .read_fat: popa ; In case registers altered by int 13h pusha stc int 13h jnc .read_fat_ok call disk_reset_floppy jnc .read_fat popa jmp .fat_problem .read_fat_ok: popa .load_file_sector: mov ax, word [.cluster] ; Convert sector to logical add ax, 31 call disk_convert_l2hts ; Make appropriate params for int 13h mov bx, [.load_position] mov es, [.old_segment] mov ah, 02 ; AH = read sectors, AL = just read 1 mov al, 01 stc int 13h mov es, [.default_segment] jnc .calculate_next_cluster ; If there's no error... call disk_reset_floppy ; Otherwise, reset floppy and retry jnc .load_file_sector jmp .sector_problem .calculate_next_cluster: mov ax, [.cluster] mov bx, 3 mul bx mov bx, 2 div bx ; DX = [CLUSTER] mod 2 mov si, disk_buffer ; AX = word in FAT for the 12 bits add si, ax mov ax, word [ds:si] or dx, dx ; If DX = 0 [CLUSTER] = even, if DX = 1 then odd jz .even ; If [CLUSTER] = even, drop last 4 bits of word ; with next cluster; if odd, drop first 4 bits .odd: shr ax, 4 ; Shift out first 4 bits (belong to another entry) jmp .calculate_cluster_cont ; Onto next sector! .even: and ax, 0FFFh ; Mask out top (last) 4 bits .calculate_cluster_cont: mov word [.cluster], ax ; Store cluster cmp ax, 0FF8h jae .end add word [.load_position], 512 jmp .load_file_sector ; Onto next sector! .end: mov bx, [.file_size] ; Get file size to pass back in BX clc ; Carry clear = good load mov es, [.old_segment] pop ax ret .cluster dw 0 ; Cluster of the file we want to load .pointer dw 0 ; Pointer into disk_buffer, for loading 'file2load' .filename_loc dw 0 ; Temporary store of filename location .load_position dw 0 ; Where we'll load the file .file_size dw 0 ; Size of the file .string_buff times 12 db 0 ; For size (integer) printing .old_segment dw 0 .default_segment dw 0 .root_problem_msg db 'File not found', 0 .drive_problem_msg db 'Generic drive error', 0 .fat_problem_msg db 'Error reading FAT', 0 .sector_problem_msg db 'Error reading file sectors', 0 ; -------------------------------------------------------------------------- ; Reset floppy disk disk_reset_floppy: push ax push dx mov ax, 0 ; ****************************************************************** mov dl, [bootdev] ; ****************************************************************** stc int 13h pop dx pop ax ret ; -------------------------------------------------------------------------- ; disk_convert_l2hts -- Calculate head, track and sector for int 13h ; IN: logical sector in AX; OUT: correct registers for int 13h disk_convert_l2hts: push bx push ax mov bx, ax ; Save logical sector mov dx, 0 ; First the sector div word [SecsPerTrack] ; Sectors per track add dl, 01h ; Physical sectors start at 1 mov cl, dl ; Sectors belong in CL for int 13h mov ax, bx mov dx, 0 ; Now calculate the head div word [SecsPerTrack] ; Sectors per track mov dx, 0 div word [Sides] ; Floppy sides mov dh, dl ; Head/side mov ch, al ; Track pop ax pop bx ; ****************************************************************** mov dl, [bootdev] ; Set correct device ; ****************************************************************** ret Sides dw 2 SecsPerTrack dw 18 ; ****************************************************************** bootdev db 0 ; Boot device number ; ****************************************************************** ; ------------------------------------------------------------------ ; int_filename_convert -- Change 'TEST.BIN' into 'TEST BIN' as per FAT12 ; IN: AX = filename string ; OUT: AX = location of converted string (carry set if invalid) int_filename_convert: pusha mov si, ax call os_string_length cmp ax, 14 ; Filename too long? jg .failure ; Fail if so cmp ax, 0 je .failure ; Similarly, fail if zero-char string mov dx, ax ; Store string length for now mov di, .dest_string mov cx, 0 .copy_loop: lodsb cmp al, '.' je .extension_found stosb inc cx cmp cx, dx jg .failure ; No extension found = wrong jmp .copy_loop .extension_found: cmp cx, 0 je .failure ; Fail if extension dot is first char cmp cx, 8 je .do_extension ; Skip spaces if first bit is 8 chars ; Now it's time to pad out the rest of the first part of the filename ; with spaces, if necessary .add_spaces: mov byte [di], ' ' inc di inc cx cmp cx, 8 jl .add_spaces ; Finally, copy over the extension .do_extension: lodsb ; 3 characters cmp al, 0 je .failure stosb lodsb cmp al, 0 je .failure stosb lodsb cmp al, 0 je .failure stosb mov byte [di], 0 ; Zero-terminate filename popa mov ax, .dest_string clc ; Clear carry for success ret .failure: popa stc ; Set carry for failure ret .dest_string times 13 db 0 ; ------------------------------------------------------------------ ; os_string_length -- Return length of a string ; IN: AX = string location ; OUT AX = length (other regs preserved) os_string_length: pusha mov bx, ax ; Move location of string to BX mov cx, 0 ; Counter .more: cmp byte [bx], 0 ; Zero (end of string) yet? je .done inc bx ; If not, keep adding inc cx jmp .more .done: mov word [.tmp_counter], cx ; Store count before restoring other registers popa mov ax, [.tmp_counter] ; Put count back into AX before returning ret .tmp_counter dw 0 ; ------------------------------------------------------------------ ; os_string_uppercase -- Convert zero-terminated string to upper case ; IN/OUT: AX = string location os_string_uppercase: pusha mov si, ax ; Use SI to access string .more: cmp byte [si], 0 ; Zero-termination of string? je .done ; If so, quit cmp byte [si], 'a' ; In the lower case A to Z range? jb .noatoz cmp byte [si], 'z' ja .noatoz sub byte [si], 20h ; If so, convert input char to upper case inc si jmp .more .noatoz: inc si jmp .more .done: popa ret ; ------------------------------------------------------------------ ; os_string_compare -- See if two strings match ; IN: SI = string one, DI = string two ; OUT: carry set if same, clear if different os_string_compare: pusha .more: mov al, [si] ; Retrieve string contents mov bl, [di] cmp al, bl ; Compare characters at current location jne .not_same cmp al, 0 ; End of first string? Must also be end of second je .terminated inc si inc di jmp .more .not_same: ; If unequal lengths with same beginning, the byte popa ; comparison fails at shortest string terminator clc ; Clear carry flag ret .terminated: ; Both strings terminated at the same position popa stc ; Set carry flag ret ; ------------------------------------------------------------------ ; os_print_string -- Displays text ; IN: SI = message location (zero-terminated string) ; OUT: Nothing (registers preserved) os_print_string: pusha mov ah, 0Eh ; int 10h teletype function .repeat: lodsb ; Get char from string cmp al, 0 je .done ; If char is zero, end of string int 10h ; Otherwise, print it jmp .repeat ; And move on to next char .done: popa ret ; ------------------------------------------------------------------ ; os_clear_screen -- Clears the screen to background ; IN/OUT: Nothing (registers preserved) os_clear_screen: pusha mov dx, 0 ; Position cursor at top-left call os_move_cursor mov ah, 6 ; Scroll full-screen mov al, 0 ; Normal white on black mov bh, 7 ; mov cx, 0 ; Top-left mov dh, 24 ; Bottom-right mov dl, 79 int 10h popa ret ; ------------------------------------------------------------------ ; os_move_cursor -- Moves cursor in text mode ; IN: DH, DL = row, column; OUT: Nothing (registers preserved) os_move_cursor: pusha mov bh, 0 mov ah, 2 int 10h ; BIOS interrupt to move cursor popa ret ; ------------------------------------------------------------------ ; os_print_1hex -- Displays low nibble of AL in hex format ; IN: AL = number to format and print os_print_1hex: pusha and ax, 0Fh ; Mask off data to display call os_print_digit popa ret ; ------------------------------------------------------------------ ; os_print_2hex -- Displays AL in hex format ; IN: AL = number to format and print os_print_2hex: pusha push ax ; Output high nibble shr ax, 4 call os_print_1hex pop ax ; Output low nibble call os_print_1hex popa ret ; ------------------------------------------------------------------ ; os_print_4hex -- Displays AX in hex format ; IN: AX = number to format and print os_print_4hex: pusha push ax ; Output high byte mov al, ah call os_print_2hex pop ax ; Output low byte call os_print_2hex popa ret ; Displays EAX in hex format ; IN: EAX = unsigned integer ; OUT: nothing os_print_8hex: pusha rol eax, 16 call os_print_4hex rol eax, 16 call os_print_4hex popa ret ; ------------------------------------------------------------------ ; os_print_digit -- Displays contents of AX as a single digit ; Works up to base 37, ie digits 0-Z ; IN: AX = "digit" to format and print os_print_digit: pusha cmp ax, 9 ; There is a break in ASCII table between 9 and A jle .digit_format add ax, 'A'-'9'-1 ; Correct for the skipped punctuation .digit_format: add ax, '0' ; 0 will display as '0', etc. mov ah, 0Eh ; May modify other registers int 10h popa ret ; ------------------------------------------------------------------ ; os_print_newline -- Reset cursor to start of next line ; IN/OUT: Nothing (registers preserved) os_print_newline: pusha mov ah, 0Eh ; BIOS output char code mov al, 13 int 10h mov al, 10 int 10h popa ret ; Converts an unsigned 32-bit integer into a string. ; IN: EAX = unsigned int ; OUT: AX = string location os_32int_to_string: pusha mov cx, 0 mov ebx, 10 ; Set BX 10, for division and mod mov di, .t ; Get our pointer ready .push: mov edx, 0 div ebx ; Remainder in DX, quotient in AX inc cx ; Increase pop loop counter push edx ; Push remainder, so as to reverse order when popping test eax, eax ; Is quotient zero? jnz .push ; If not, loop again .pop: pop edx ; Pop off values in reverse order, and add 48 to make them digits add dl, '0' ; And save them in the string, increasing the pointer each time mov [di], dl inc di dec cx jnz .pop mov byte [di], 0 ; Zero-terminate string popa mov ax, .t ; Return location of string ret .t times 11 db 0 os_print_32int: pushad call os_32int_to_string mov si, ax call os_print_string popad ret
#include <log4cxx/logger.h> #include <KrisLibrary/Logger.h> #include "CholeskyDecomposition.h" #include "backsubstitute.h" #include "complex.h" #include <iostream> #include <errors.h> namespace Math { template <class T> CholeskyDecomposition<T>::CholeskyDecomposition() :zeroEpsilon((T)1e-10) {} template <class T> CholeskyDecomposition<T>::CholeskyDecomposition(const MatrixT& A) :zeroEpsilon((T)1e-10) { set(A); } template <class T> CholeskyDecomposition<T>::CholeskyDecomposition(const MatrixT& A,MatrixT& L) :zeroEpsilon((T)1e-10) { setDestination(L); set(A); } template <class T> void CholeskyDecomposition<T>::setDestination(MatrixT& L_input) { L.setRef(L_input); } template <class T> bool CholeskyDecomposition<T>::set(const MatrixT& A) { if(A.m != A.n) return false; int n=A.n; L.resize(n,n); int i,j,k; T temp,lii; for(i=0; i<n; i++) { temp = A(i,i); for(k=0; k<i; k++) temp -= Sqr(L(i,k)); if(temp <= -Zero) { LOG4CXX_INFO(KrisLibrary::logger(),"CholeskyDecomposition: A is not positive definite!\n"); LOG4CXX_INFO(KrisLibrary::logger()," "<<i<<"'th row, temp is "<<temp); return false; } lii = Sqrt(temp); if(lii < zeroEpsilon) { LOG4CXX_INFO(KrisLibrary::logger(),"CholeskyDecomposition: A is not strictly positive definite!\n"); lii = (T)zeroEpsilon; } L(i,i)=lii; for(j=i+1; j<n; j++) { temp = A(i,j); for(k=0; k<i; k++) temp -= L(i,k)*L(j,k); L(j,i) = temp / lii; } for(j=0; j<i; j++) L(j,i) = Zero; } return true; } using namespace std; template <class T> bool CholeskyDecomposition<T>::setPerturbed(const MatrixT& A,T& lambda) { if(A.m != A.n) return false; int n=A.n; L.resize(n,n); int i,j,k; T temp,lii; lambda = Zero; for(i=0; i<n; i++) { temp = A(i,i); for(k=0; k<i; k++) temp -= Sqr(L(i,k)); if(temp < zeroEpsilon) { if(temp + lambda <= zeroEpsilon) lambda = -temp+zeroEpsilon; lii = Sqrt(temp+lambda); } else { lii = Sqrt(temp); } L(i,i) = lii; for(j=i+1; j<n; j++) { temp = A(i,j); for(k=0; k<i; k++) temp -= L(i,k)*L(j,k); L(j,i) = temp / lii; } } if(lambda == Zero) return true; LOG4CXX_INFO(KrisLibrary::logger(),"Lambda is "<<lambda<<"\n"); for(i=0; i<n; i++) { temp = A(i,i); for(k=0; k<i; k++) temp -= Sqr(L(i,k)); //if(temp < lambda) // lii = Sqrt(Min(temp+lambda,lambda)); //else lii = Sqrt(temp+lambda); L(i,i) = lii; for(j=i+1; j<n; j++) { temp = A(i,j); for(k=0; k<i; k++) temp -= L(i,k)*L(j,k); L(j,i) = temp / lii; } for(j=0; j<i; j++) L(j,i) = Zero; } return true; } template <class T> void CholeskyDecomposition<T>::backSub(const VectorT& b, VectorT& x) const { //LLt*x=b //Lt*x=L^-1*b=y //x=(Lt^-1)y VectorT y; LBackSub(b,y); LTBackSub(y,x); } template <class T> void CholeskyDecomposition<T>::backSub(const MatrixT& B, MatrixT& X) const { X.resize(B.m,B.n); MatrixT temp(B.m,B.n); if(!LBackSubstitute(L,B,temp)) FatalError("CholeskyDecomposition: LBackSubstitute failed!"); if(!LtBackSubstitute(L,temp,X)) FatalError("CholeskyDecomposition: LtBackSubstitute failed!"); } template <class T> void CholeskyDecomposition<T>::LBackSub(const VectorT& b, VectorT& x) const { x.resize(L.n); if(!LBackSubstitute(L,b,x)) FatalError("CholeskyDecomposition: LBackSubstitute failed!"); } template <class T> void CholeskyDecomposition<T>::LTBackSub(const VectorT& b, VectorT& x) const { x.resize(L.n); if(!LtBackSubstitute(L,b,x)) FatalError("CholeskyDecomposition: LtBackSubstitute failed!"); } template <class T> void CholeskyDecomposition<T>::getInverse(MatrixT& Ainv) const { Ainv.resize(L.n,L.n); VectorT temp(L.n,Zero),y,x; for(int i=0;i<L.n;i++) { Ainv.getColRef(i,x); //x &= col i of A temp(i)=One; LBackSub(temp,y); LTBackSub(y,x); temp(i)=Zero; } } template<class T> void CholeskyDecomposition<T>::update(const VectorT& _x) { VectorT x = _x; //make a copy, we'll change it int n=L.n; Assert(x.n == n); T alpha=1; for(int i=0;i<n;i++) { T deltai = Sqr(L(i,i)); T temp = alpha + Sqr(x(i))/deltai; deltai = deltai*temp; T gamma = x(i)/deltai; deltai = deltai / alpha; alpha = temp; L(i,i) = Sqrt(deltai); for(int k=i+1;k<n;k++) { x(k) -= x(i)*L(k,i); L(k,i) += gamma*x(k); } } } template <class T> bool CholeskyDecomposition<T>::downdate(const VectorT& _x) { VectorT x = _x; //make a copy, we'll change it int n=L.n; Assert(x.n == n); T alpha=1; for(int i=0;i<n;i++) { T deltai = Sqr(L(i,i)); T temp = alpha - Sqr(x(i))/deltai; deltai = deltai*temp; if(deltai == 0) return false; T gamma = x(i)/deltai; deltai = deltai / alpha; alpha = temp; if(deltai < 0) return false; L(i,i) = Sqrt(deltai); for(int k=i+1;k<n;k++) { x(k) -= x(i)*L(k,i); L(k,i) -= gamma*x(k); } } return true; } /* //template instantiation for Complex bool CholeskyDecomposition<Complex>::set(const MatrixT& A) { if(A.m != A.n) return false; int n=A.n; L.resize(n,n); int i,j,k; Complex temp,lii; for(i=0; i<n; i++) { temp = A(i,i); for(k=0; k<i; k++) temp -= Sqr(L(i,k)); lii = Sqrt(temp); if(Abs(lii) < zeroEpsilon.x) { LOG4CXX_INFO(KrisLibrary::logger(),"CholeskyDecomposition<Complex>: A is not strictly positive definite!\n"); return false; } L(i,i)=lii; for(j=i+1; j<n; j++) { temp = A(i,j); for(k=0; k<i; k++) temp -= L(i,k)*L(j,k); L(j,i) = temp / lii; } for(j=0; j<i; j++) L(j,i) = Zero; } return true; } bool CholeskyDecomposition<Complex>::setPerturbed(const MatrixT& A,Complex& lambda) { LOG4CXX_INFO(KrisLibrary::logger(),"CholeskyDecomposition<Complex>: Perturbed decomposition isn't defined\n"); return false; } */ template class CholeskyDecomposition<float>; template class CholeskyDecomposition<double>; //template class CholeskyDecomposition<Complex>; } //namespace Math
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r8 push %r9 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0x128d, %rdx cmp $34168, %rbp mov $0x6162636465666768, %rdi movq %rdi, %xmm2 and $0xffffffffffffffc0, %rdx movaps %xmm2, (%rdx) nop nop nop add %r9, %r9 lea addresses_WT_ht+0xc1d, %r9 nop nop nop nop add %r8, %r8 movups (%r9), %xmm1 vpextrq $1, %xmm1, %r12 sub $54694, %r12 lea addresses_WT_ht+0xfc8d, %r8 nop nop and %r10, %r10 mov $0x6162636465666768, %rbp movq %rbp, %xmm7 and $0xffffffffffffffc0, %r8 movntdq %xmm7, (%r8) cmp %rdx, %rdx lea addresses_normal_ht+0x2b1f, %rdx nop nop nop nop nop and $2841, %r8 mov $0x6162636465666768, %r12 movq %r12, %xmm0 movups %xmm0, (%rdx) nop nop nop nop nop xor %r8, %r8 lea addresses_UC_ht+0x182e9, %rsi lea addresses_UC_ht+0x640d, %rdi nop nop xor $51533, %r10 mov $93, %rcx rep movsl sub $6182, %rdi lea addresses_A_ht+0x10e8d, %rsi lea addresses_A_ht+0xdc35, %rdi nop nop nop add $9862, %r8 mov $102, %rcx rep movsl nop nop nop nop sub %rcx, %rcx lea addresses_UC_ht+0xe25, %r12 and %rbp, %rbp mov (%r12), %rdx nop nop nop nop nop and %r10, %r10 lea addresses_D_ht+0x1e50d, %r12 nop nop nop nop nop and %rdx, %rdx mov $0x6162636465666768, %r9 movq %r9, %xmm2 movups %xmm2, (%r12) nop nop cmp $27633, %rdx lea addresses_WT_ht+0xb28d, %rsi lea addresses_D_ht+0x1df35, %rdi nop nop nop nop xor %rbp, %rbp mov $78, %rcx rep movsw nop nop nop nop xor %r9, %r9 lea addresses_WT_ht+0x15eed, %r8 nop nop and %rdx, %rdx movb $0x61, (%r8) nop nop nop nop nop and $170, %rbp lea addresses_WC_ht+0x7001, %rsi lea addresses_normal_ht+0x548d, %rdi nop nop dec %r12 mov $45, %rcx rep movsq nop nop nop nop nop xor %rcx, %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r8 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r14 push %rax push %rbp push %rbx push %rcx push %rdx // Load lea addresses_US+0x6ce0, %rbp clflush (%rbp) nop nop add %rdx, %rdx mov (%rbp), %cx nop nop nop nop nop xor $31228, %r11 // Faulty Load lea addresses_PSE+0x1aa8d, %r14 nop nop nop nop xor %rax, %rax movb (%r14), %bl lea oracles, %rcx and $0xff, %rbx shlq $12, %rbx mov (%rcx,%rbx,1), %rbx pop %rdx pop %rcx pop %rbx pop %rbp pop %rax pop %r14 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_PSE', 'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': True, 'size': 16, 'congruent': 11}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 1}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_A_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 3}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 5}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_normal_ht'}} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; Stubs Written by D Morris - 15/10/98 ; ; ; Page the graphics bank in/out - used by all gfx functions ; Simply does a swap... ; ; ; $Id: swapgfxbk.asm,v 1.5 2017/01/02 22:57:59 aralbrec Exp $ ; SECTION code_clib PUBLIC swapgfxbk PUBLIC _swapgfxbk PUBLIC swapgfxbk1 PUBLIC _swapgfxbk1 .swapgfxbk ._swapgfxbk .swapgfxbk1 ._swapgfxbk1 ret
// Indexing tensors by by tensors // // This corresponds to "advanced indexing" in NumPy. The two operations are: // // index(Tensor self, indices) -> Tensor // index_put_(Tensor self, indices, value, accumulate=false) // // The index is a TensorList containg kLong, kBool or kByte tensors or nulls. Byte // tensors (boolean masks) are expanded to long tensors via nonzero(). Null // tensors signify that the dimension is not indexed. // // All indexes are broadcast together and iterated as *one*. From NumPy: // // result[i_1, ..., i_M] == x[ind_1[i_1, ..., i_M], ind_2[i_1, ..., i_M], // ..., ind_N[i_1, ..., i_M]] // // Note 1: ByteTensors expand to index as many dimensions as there are in the // mask. // // Note 2: The behavior is more complicated when the index tensors are not all // adjacent (e.g. x[[0, 1], :, [2, 3]]). In this case, self and the index // tensors are transposed to the front: x.transpose(1, 2)[[0, 1], [2, 3]] // // The code contains two implementations of indexing. The more efficient // implementation treats indexing like an elementwise operation over the // tensors `result`, `x`, `ind_1`, `ind_2`, etc. This implementation does // not work for index_put_ with accumulate=True. The other implementation // combines the indexed tensors into a single linear index that is used // with Tensor.put_. This is used for index_put_ with accumulate=True. // // The more efficient implementation takes the following steps for the // above operation: // // 1) Broadcast ind_1, ind_2, ind_3 together to a common shape // 2) Record x.stride(i) for each indexed dimension `i` // 3) Replace the indexed subspace of `x` with the shape of the corresponding // subspace of `result` but with stride 0 // 4) Add dimensions of size 1 to the index tensors (ind_1, ind_2, etc.) so // that their shape is compatible with the result shape // // The CPU or CUDA kernel then computes element-wise over the broadcasted // and restrided result, x, ind_1, ind_2, etc.: // // result[...] = *(&x[...] + // ind_1[...] * x.stride(1) + // ind_2[...] * x.stride(2) + // ...) // // where & and * represent the C-style address-of and indirection operations. #include <ATen/native/TensorAdvancedIndexing.h> #include <ATen/native/IndexKernel.h> #include <ATen/native/IndexingUtils.h> #include <ATen/ATen.h> #include <ATen/NativeFunctions.h> #include <ATen/ExpandUtils.h> #include <ATen/MemoryOverlap.h> #include <ATen/native/TensorIterator.h> #include <ATen/native/BinaryOps.h> #include <ATen/native/Copy.h> #include <ATen/native/Resize.h> #include <ATen/native/ScatterGatherChecks.h> #include <ATen/Parallel.h> #include <c10/util/irange.h> #include <c10/util/Unroll.h> #include <algorithm> #include <functional> #include <numeric> #include <vector> namespace at { namespace meta { native::SCATTER_GATHER_OP get_operator_enum(const c10::string_view reduce, bool use_new_options = false) { if (use_new_options) { if (reduce == "sum") { return native::SCATTER_GATHER_OP::REDUCE_ADD; } else if (reduce == "prod") { return native::SCATTER_GATHER_OP::REDUCE_MULTIPLY; } else if (reduce == "mean") { return native::SCATTER_GATHER_OP::REDUCE_MEAN; } else if (reduce == "amax") { return native::SCATTER_GATHER_OP::REDUCE_MAXIMUM; } else if (reduce == "amin") { return native::SCATTER_GATHER_OP::REDUCE_MINIMUM; } else { TORCH_CHECK(false, "reduce argument must be either sum, prod, mean, amax or amin."); } } else { if (reduce == "add") { return native::SCATTER_GATHER_OP::REDUCE_ADD; } else if (reduce == "multiply") { return native::SCATTER_GATHER_OP::REDUCE_MULTIPLY; } else { TORCH_CHECK(false, "reduce argument must be either add or multiply.") } } } TORCH_META_FUNC(gather) (const Tensor & self, int64_t dim, const Tensor & index, bool sparse_grad) { const Tensor& result = maybe_get_output(0); int64_t wrapped_dim = at::maybe_wrap_dim(dim, self.dim()); // Memory overlap checks need to be done after resizing (if required) is done. // But it only makes sense to do these checks when result was defined, hence // the boolean variable `check_result` here. // For more details, see: https://github.com/pytorch/pytorch/pull/63312#discussion_r694794832 // and https://github.com/pytorch/pytorch/issues/63837 bool check_result = result.defined(); set_output(index.sizes(), self.options()); if (check_result) { at::assert_no_internal_overlap(result); at::assert_no_overlap(result, self); at::assert_no_partial_overlap(result, index); } auto is_index_empty = index.numel() == 0; if (!is_index_empty) { TORCH_CHECK( index.scalar_type() == at::ScalarType::Long, "gather", "(): Expected dtype int64 for index" ); } if (is_index_empty) return; at::native::gather_shape_check(self, wrapped_dim, index); } template <bool use_new_options = false, typename Meta> void scatter_meta_impl( Meta& meta, const Tensor& self, int64_t dim, const Tensor& index, const c10::optional<Tensor>& src = nullopt, const c10::optional<c10::string_view> reduce = nullopt) { int64_t wrapped_dim = at::maybe_wrap_dim(dim, self.dim()); at::native::scatter_gather_dtype_check("scatter", self, index, src); at::native::scatter_shape_check(self, wrapped_dim, index, src); auto output = meta.maybe_get_output(0); if (output.defined()) { at::assert_no_internal_overlap(output); at::assert_no_overlap(output, index); if (src.has_value()) { at::assert_no_overlap(output, src.value()); } } meta.set_output(self.sizes(), self.options()); if (reduce.has_value()) { // Check if we have a valid reduce operator. get_operator_enum(reduce.value(), use_new_options); } } TORCH_META_FUNC2(scatter, src) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src) { scatter_meta_impl(*this, self, dim, index, src); } TORCH_META_FUNC2(scatter, value) (const Tensor& self, int64_t dim, const Tensor& index, const Scalar& value) { scatter_meta_impl(*this, self, dim, index); } TORCH_META_FUNC2(scatter, reduce) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src, const c10::string_view reduce) { scatter_meta_impl(*this, self, dim, index, src, reduce); } TORCH_META_FUNC2(scatter, value_reduce) (const Tensor& self, int64_t dim, const Tensor& index, const Scalar& src, const c10::string_view reduce) { scatter_meta_impl(*this, self, dim, index, nullopt, reduce); } TORCH_META_FUNC(scatter_add) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src) { scatter_meta_impl(*this, self, dim, index, src, "add"); } TORCH_META_FUNC2(scatter_reduce, two) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src, const c10::string_view reduce) { scatter_meta_impl</*use_new_options=*/true>(*this, self, dim, index, src, reduce); } TORCH_PRECOMPUTE_META_FUNC(index_copy) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& source) { dim = maybe_wrap_dim(dim, self.dim()); const Tensor& result = maybe_get_output(0); // Memory overlap checks need to be done after resizing (if required) is done. // But it only makes sense to do these checks when result was defined, hence // the boolean variable `check_result` here. // For more details, see: https://github.com/pytorch/pytorch/pull/63312#discussion_r694794832 // and https://github.com/pytorch/pytorch/issues/63837 bool check_result = result.defined(); set_output(self.sizes(), self.options()); if (check_result) { at::assert_no_internal_overlap(result); at::assert_no_overlap(result, index); at::assert_no_overlap(result, source); } TORCH_CHECK_INDEX(index.dim() < 2, "index_copy_(): Index should have dimension 1 or 0 (got ", index.dim(), ")"); int64_t numIndices = index.numel(); if (source.dim() == 0 && numIndices != 1) { TORCH_CHECK_INDEX(false, "index_copy_(): When source is scalar, index should have one element (got ", numIndices, ")"); } else if ((source.dim() != self.dim()) && (source.dim() != 0 && self.dim() != 0)) { TORCH_CHECK_INDEX(false, "index_copy_(): When source and destination are not scalars, their dimensionality must match. Source dimensionality (", source.dim(), "), destination dimensionality (", self.dim(), ")"); } TORCH_CHECK(index.scalar_type() == ScalarType::Long, "index_copy_(): Expected a long tensor for index, but got ", index.scalar_type()); TORCH_CHECK(self.scalar_type() == source.scalar_type(), "index_copy_(): self and source expected to have the same dtype, but got (self) ", self.scalar_type(), " and (source) ", source.scalar_type()); TORCH_CHECK(self.device() == source.device() && self.device() == index.device(), "index_copy_(): self, index and source expected to be in the same device, but got (self) ", self.device(), ", (index) ", index.device(), ", and (source) ", source.device()); // Check that source and destination slices have the same size auto selfSlicedSizes = self.sizes().vec(); if (selfSlicedSizes.size() > 0) { selfSlicedSizes.erase(selfSlicedSizes.begin() + dim); } auto sourceSlicedSizes = source.sizes().vec(); if (sourceSlicedSizes.size() > 0) { sourceSlicedSizes.erase(sourceSlicedSizes.begin() + dim); } if (selfSlicedSizes.size() != sourceSlicedSizes.size() || !std::equal(selfSlicedSizes.begin(), selfSlicedSizes.end(), sourceSlicedSizes.begin())) { std::stringstream ss; ss << "index_copy_(): Source/destination tensor must have same slice shapes. "; ss << "Destination slice shape: " << selfSlicedSizes << " at dimension " << dim; ss << " and source slice shape: " << sourceSlicedSizes << " at dimension 0."; TORCH_CHECK(false, ss.str()); } TORCH_CHECK_INDEX(source.dim() == 0 || numIndices == source.size(dim), "index_copy_(): Number of indices (", numIndices, ") should be equal to source.size(dim) (", source.size(dim), ")"); return TORCH_PRECOMPUTE_STRUCT(index_copy)().set_dim(dim); } TORCH_PRECOMPUTE_META_FUNC(index_add) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& source, const Scalar& alpha) { dim = maybe_wrap_dim(dim, self.dim()); auto numel = index.numel(); TORCH_CHECK_INDEX(index.dim() <= 1, "index_add_(): Index is supposed to be a vector, but got dim: ", index.dim(), " with type: ", index.scalar_type(), " and size: ", index.sizes()); TORCH_CHECK(index.scalar_type() == ScalarType::Long || index.scalar_type() == ScalarType::Int, "index_add_(): Expected dtype int32/int64 for index but got: ", index.scalar_type()); TORCH_CHECK(self.scalar_type() == source.scalar_type(), "index_add_(): self (", self.scalar_type(), ") and source (", source.scalar_type(), ") must have the same scalar type"); TORCH_CHECK(dim == 0 || dim < source.dim(), "index_add_(): Indexing dim ", dim, " is out of bounds of the source tensor with dim ", source.dim()); TORCH_CHECK(numel == (source.dim() == 0 ? 1 : source.size(dim)), "index_add_(): Number of indices (", numel, ") should be equal to source.size(dim): (", source.size(dim), "), for dim: ", dim); auto& result = maybe_get_output(0); bool is_defined = result.defined(); set_output(self.sizes(), self.options()); if (is_defined) { at::assert_no_internal_overlap(result); at::assert_no_overlap(result, index); at::assert_no_overlap(result, source); } // A hack to run TensorIterator checks in the meta function. // See comment: https://github.com/pytorch/pytorch/pull/65993#discussion_r760307417 // TODO: (@krshrimali) Try inheriting from TensorIteratorBase instead. if (result.device() == kMeta) { auto selfSlice = result.select(dim, 0); auto sourceSlice = source.select(dim, 0); auto iter = TensorIterator::borrowing_binary_op(selfSlice, selfSlice, sourceSlice); } return TORCH_PRECOMPUTE_STRUCT(index_add)().set_dim(dim); } } // namespace meta namespace native { DEFINE_DISPATCH(index_stub); DEFINE_DISPATCH(index_fill_stub); DEFINE_DISPATCH(index_copy_stub); DEFINE_DISPATCH(index_put_stub); DEFINE_DISPATCH(index_put_with_sort_stub); DEFINE_DISPATCH(put_stub); DEFINE_DISPATCH(take_stub); DEFINE_DISPATCH(masked_fill_stub); REGISTER_NO_CPU_DISPATCH(index_put_with_sort_stub); DEFINE_DISPATCH(masked_select_serial_stub); DEFINE_DISPATCH(masked_select_stub); DEFINE_DISPATCH(masked_scatter_stub); DEFINE_DISPATCH(gather_stub); DEFINE_DISPATCH(scatter_stub); DEFINE_DISPATCH(scatter_fill_stub); DEFINE_DISPATCH(scatter_add_stub); DEFINE_DISPATCH(scatter_reduce_stub); DEFINE_DISPATCH(scatter_scalar_reduce_stub); DEFINE_DISPATCH(scatter_reduce_two_stub); static bool all_strides_match(TensorList tensors) { TORCH_CHECK(tensors.size() >= 1); auto strides = tensors[0].strides(); for (auto& tensor : tensors.slice(1)) { if (!strides.equals(tensor.strides())) { return false; } } return true; } static std::string shapes_as_str(TensorList tensors) { std::ostringstream os; bool first = true; for (auto& tensor : tensors) { if (tensor.defined()) { if (!first) { os << ", "; } os << tensor.sizes(); first = false; } } return os.str(); } // Replace indexed dimensions in src with stride 0 and the size of the result tensor. // The offset in these dimensions is computed by the kernel using the index tensor's // values and the stride of src. The new shape is not meaningful. It's used to make // the shape compatible with the result tensor. static Tensor restride_src(const Tensor& src, int64_t dims_before, int64_t dims_indexed, IntArrayRef replacement_shape) { auto shape = DimVector(src.sizes()); auto strides = DimVector(src.strides()); int64_t end = dims_before + dims_indexed; shape.erase(shape.begin() + dims_before, shape.begin() + end); strides.erase(strides.begin() + dims_before, strides.begin() + end); shape.insert(shape.begin() + dims_before, replacement_shape.begin(), replacement_shape.end()); strides.insert(strides.begin() + dims_before, replacement_shape.size(), 0); return src.as_strided(shape, strides); } // Add dimensions of size 1 to an index tensor so that it can be broadcast to the result // shape and iterated over element-wise like the result tensor and the restrided src. static Tensor reshape_indexer(const Tensor& index, int64_t dims_before, int64_t dims_after) { auto orig_shape = index.sizes(); auto shape = DimVector(); shape.append(dims_before, 1); shape.append(orig_shape.begin(), orig_shape.end()); shape.append(dims_after, 1); return index.reshape(shape); } AdvancedIndex::AdvancedIndex(const Tensor& src, TensorList indices_list) { int64_t element_size_bytes = src.element_size(); int64_t dims_before = 0, dims_after = 0, dims_indexed = 0; IntArrayRef replacement_shape; for (const auto dim : c10::irange(indices_list.size())) { if (!indices_list[dim].defined()) { if (dims_indexed == 0) { dims_before++; } else { dims_after++; } } else { dims_indexed++; replacement_shape = indices_list[dim].sizes(); indexed_sizes.push_back(src.size(dim)); indexed_strides.push_back(src.stride(dim) * element_size_bytes); } } // Check if the indexed subspace contains a dim of size 0, but the replacement // shape does not. This implies that an index is out of bounds, because there // is no number that's a valid index for an empty tensor. Normally, out of // bounds is handled in the indexing kernel, but this case fails earlier in // restride_src with an unhelpful error message. if (std::find(indexed_sizes.begin(), indexed_sizes.end(), 0) != indexed_sizes.end() && std::find(replacement_shape.begin(), replacement_shape.end(), 0) == replacement_shape.end()) { TORCH_CHECK_INDEX(false, "index is out of bounds for dimension with size 0"); } this->dims_before = dims_before; this->dims_after = dims_after; this->src = restride_src(src, dims_before, dims_indexed, replacement_shape); for (auto& index : indices_list) { if (index.defined()) { indices.push_back(reshape_indexer(index, dims_before, dims_after)); } } // For CUDA tensors, force all index tensors to have the same striding to // simplify the CUDA kernel. if (indices.size() >= 2 && this->src.device().type() == kCUDA) { if (!all_strides_match(indices)) { for (auto & indice : indices) { indice = indice.contiguous(); } } } } static std::tuple<bool, Tensor> canDispatchToMaskedFill(const Tensor& self, const torch::List<c10::optional<at::Tensor>>& indices, const Tensor& value){ if (!(value.numel() ==1 && value.device().is_cpu())){ return std::make_tuple(false,Tensor()); } int64_t num_ind = 0; Tensor mask; auto self_device = self.device(); for (const c10::optional<Tensor> i: indices) { if (!i.has_value() || !(*i).defined()){ num_ind++; } else { Tensor index = std::move(*i); if ((index.scalar_type() != kByte && index.scalar_type() != kBool) || index.device() != self_device || mask.defined()){ return std::make_tuple(false, Tensor()); } else { mask = index; for (const auto j : c10::irange(index.dim())) { int64_t srcIdx = num_ind + j; TORCH_CHECK_INDEX(index.size(j) == self.size(srcIdx), "The shape of the mask ", index.sizes(), " at index ", j, " does not match the shape of the indexed tensor ", self.sizes(), " at index ", srcIdx); } num_ind += mask.ndimension(); } } } for (const auto i : c10::irange(num_ind, self.ndimension())) { (void)i; //Suppress unused variable warning mask = mask.unsqueeze(-1); } return std::make_tuple(true, mask); } static AdvancedIndex make_info(Tensor self, const torch::List<c10::optional<at::Tensor>>& orig) { checkIndexTensorTypes(orig); // first expand BoolTensor (masks) or ByteTensor (masks) into 1 or more LongTensors auto indices = expandTensors(self, orig); // next broadcast all index tensors together try { indices = expand_outplace(indices); } catch (std::exception& e) { TORCH_CHECK_INDEX(false, "shape mismatch: indexing tensors could not be broadcast together" " with shapes ", shapes_as_str(indices)); } // add missing null Tensors so that it matches self.dim() while (indices.size() < (size_t)self.dim()) { indices.emplace_back(); } // if the non-null indices are not all adjacent, transpose self and indices // together so that they're adjacent at the front if (!hasContiguousSubspace(indices)) { std::tie(self, indices) = transposeToFront(self, indices); } // Ensure indices are on the same device as self for (auto & indice : indices) { if (indice.defined() && indice.device() != self.device()) { indice = indice.to(self.device()); } } return AdvancedIndex(self, indices); } static TensorIterator make_index_put_iterator(const AdvancedIndex& info, const Tensor& value) { TORCH_CHECK(is_expandable_to(value.sizes(), info.src.sizes()), "shape mismatch: value tensor of shape ", value.sizes(), " cannot be broadcast to indexing result of shape ", info.src.sizes()); TORCH_CHECK(value.scalar_type() == info.src.scalar_type(), "Index put requires the source and destination dtypes match, " "got ", info.src.scalar_type(), " for the destination " "and ", value.scalar_type(), " for the source."); TensorIteratorConfig config; // info.src is restrided by restride_src with 0 strided dimensions config.set_check_mem_overlap(false); config.resize_outputs(false); config.check_all_same_dtype(false); config.add_output(info.src); config.add_input(value); for (auto& index : info.indices) { config.add_input(index); } return config.build(); } static TensorIterator make_index_iterator(const AdvancedIndex& info) { TensorIteratorConfig config; config.set_check_mem_overlap(false) .check_all_same_dtype(false) .declare_static_dtype_and_device(info.src.scalar_type(), info.src.device()) .add_owned_output(Tensor()) .add_input(info.src); for (auto& index : info.indices) { config.add_input(index); } return config.build(); } static TensorIterator make_index_out_iterator(const AdvancedIndex& info, Tensor& result) { TensorIteratorConfig config; // info.src is a restrided view of result config.set_check_mem_overlap(false) .check_all_same_dtype(false) .add_output(result) .add_input(info.src); for (auto& index : info.indices) { config.add_input(index); } return config.build(); } Tensor index(const Tensor & self, const torch::List<c10::optional<Tensor>>& indices) { TORCH_CHECK_INDEX(indices.size() <= (size_t)self.dim(), "too many indices for tensor of dimension ", self.dim(), " (got ", indices.size(), ")"); auto info = make_info(self, indices); auto iter = make_index_iterator(info); index_stub(iter.device_type(), iter, info.indexed_sizes, info.indexed_strides); return iter.output(); } Tensor quantized_index(const Tensor & self, const torch::List<c10::optional<Tensor>>& indices) { TORCH_INTERNAL_ASSERT( self.qscheme() == c10::kPerTensorAffine || self.qscheme() == c10::kPerTensorSymmetric, "Indexing is only supported for per-Tensor quantized Tensors."); // For now, this is a naive implementation which does dq -> index -> q. // TODO(future PR): improve performance by removing the copies. const auto& self_dq = self.dequantize(); TORCH_CHECK_INDEX(indices.size() <= (size_t)self.dim(), "too many indices for tensor of dimension ", self.dim(), " (got ", indices.size(), ")"); auto info = make_info(self_dq, indices); auto iter = make_index_iterator(info); index_stub(iter.device_type(), iter, info.indexed_sizes, info.indexed_strides); at::Tensor res = iter.output(); return at::quantize_per_tensor( res, self.q_scale(), self.q_zero_point(), self.scalar_type()); } Tensor& index_out(Tensor& result, const Tensor & self, const torch::List<c10::optional<Tensor>>& indices) { TORCH_CHECK_INDEX(indices.size() <= (size_t)self.dim(), "too many indices for tensor of dimension ", self.dim(), " (got ", indices.size(), ")"); at::assert_no_internal_overlap(result); at::assert_no_overlap(result, self); // NOLINTNEXTLINE(performance-implicit-conversion-in-loop) for (const c10::optional<Tensor>& index: indices) { if (index.has_value()) { at::assert_no_overlap(result, *index); } } auto info = make_info(self, indices); auto iter = make_index_out_iterator(info, result); index_stub(iter.device_type(), iter, info.indexed_sizes, info.indexed_strides); return result; } Tensor & put_(Tensor & self, const Tensor& index, const Tensor & source, const bool accumulate) { // See note [Writing Nondeterministic Operations] // Nondeterministic when index contains duplicate entries and we do not accumulate // If we accumulate on GPU, we use atomicGPUAdd, which is non-deterministic if (!accumulate || (accumulate && self.device().type() == DeviceType::CUDA)) { at::globalContext().alertNotDeterministic("put_"); } // Type and device checks TORCH_CHECK(index.scalar_type() == ScalarType::Long, "put_(): Expected a long tensor for index, but got ", index.scalar_type()) TORCH_CHECK(self.scalar_type() == source.scalar_type(), "put_(): self and source expected to have the same dtype, but got self.dtype = ", self.scalar_type(), " and source.dtype = ", source.scalar_type()); TORCH_CHECK(self.device() == source.device() && self.device() == index.device(), "put_(): self, index and source expected to be in the same device, but got self.device = ", self.device(), ", index.device = ", index.device(), ", and source.device = ", source.device()); // index checks TORCH_CHECK_INDEX(source.numel() == index.numel(), "put_(): Expected source and index to have the same number of elements, but got source.numel() = ", source.numel(), ", index.numel() = ", index.numel()); TORCH_CHECK_INDEX(!(self.numel() == 0 && index.numel() != 0), "put_(): Tried to put elements into an empty tensor"); at::assert_no_internal_overlap(self); at::assert_no_overlap(self, index); at::assert_no_overlap(self, source); // Early return if (index.numel() == 0) { return self; } auto index_reshaped = index.reshape(source.sizes()); // Do not iterate over self, we will compute the offsets manually auto iter = TensorIteratorConfig() .set_check_mem_overlap(false) .check_all_same_dtype(false) .add_input(source) .add_input(index_reshaped) .build(); put_stub(iter.device_type(), iter, self, accumulate); return self; } Tensor put(const Tensor & self, const Tensor& index, const Tensor & source, const bool accumulate) { return self.clone(at::MemoryFormat::Preserve).put_(index, source, accumulate); } Tensor index_put(const Tensor & self, const torch::List<c10::optional<Tensor>>& indices, const Tensor & value, bool accumulate) { return self.clone(at::MemoryFormat::Preserve).index_put_(indices, value, accumulate); } Tensor & _index_put_impl_(Tensor & self, const torch::List<c10::optional<Tensor>>& indices, const Tensor & value, const bool accumulate, const bool unsafe) { TORCH_CHECK_INDEX(indices.size() <= (size_t)self.dim(), "too many indices for tensor of dimension ", self.dim(), " (got ", indices.size(), ")"); if (at::has_internal_overlap(self) == MemOverlap::YES) { TORCH_WARN( "Use of index_put_ on expanded tensors is deprecated. " "Please clone() the tensor before performing this operation. " "This also applies to advanced indexing e.g. tensor[indices] = tensor"); } if (!accumulate) { auto masked_fill_dispatch = canDispatchToMaskedFill(self, indices, value); if (std::get<0>(masked_fill_dispatch)) { return self.masked_fill_(std::get<1>(masked_fill_dispatch), value.item()); } } auto value_ = value; if (value.device() != self.device() && value.numel() == 1 && value.dim() == 0) { value_ = value.to(self.device()); } at::assert_no_overlap(self, value); // NOLINTNEXTLINE(performance-implicit-conversion-in-loop) for (const c10::optional<Tensor>& index: indices) { if (index.has_value()) { at::assert_no_overlap(self, *index); } } if (self.device().type() == DeviceType::CUDA && (accumulate || globalContext().deterministicAlgorithms())) { TORCH_CHECK(value_.device() == self.device(), "expected device ", self.device(), " but got device ", value_.device(), " for value tensor"); index_put_with_sort_stub(self.device().type(), self, indices, value_, accumulate, unsafe); return self; } auto info = make_info(self, indices); auto iter = make_index_put_iterator(info, value_); index_put_stub(iter.device_type(), iter, info.indexed_sizes, info.indexed_strides, accumulate); return self; } Tensor& take_out(const Tensor& self, const Tensor& index, Tensor& out) { // Type and device checks TORCH_CHECK(index.scalar_type() == ScalarType::Long, "take(): Expected a long tensor for index, but got ", index.scalar_type()) TORCH_CHECK(self.scalar_type() == out.scalar_type(), "take(): self and out expected to have the same dtype, but got self.dtype = ", self.scalar_type(), " and out.dtype = ", out.scalar_type()); TORCH_CHECK(self.device() == out.device() && self.device() == index.device(), "take(): self, index and out expected to be in the same device, but got self.device = ", self.device(), ", index.device = ", index.device(), ", and out.device = ", out.device()); // index checks TORCH_CHECK_INDEX(!(self.numel() == 0 && index.numel() != 0), "take(): tried to take from an empty tensor"); at::assert_no_internal_overlap(out); at::assert_no_overlap(out, index); at::assert_no_overlap(out, self); // Do not iterate over self, we will compute the offsets manually // out is resized inside tensor_iterator auto iter = TensorIteratorConfig() .set_check_mem_overlap(false) .check_all_same_dtype(false) .add_output(out) .add_input(index) .build(); // Early return after out has been resized if (index.numel() == 0) { return out; } take_stub(iter.device_type(), iter, self); return out; } Tensor take(const Tensor& self, const Tensor& index) { auto out = at::empty(index.sizes(), self.options()); at::native::take_out(self, index, out); return out; } Tensor & index_put_(Tensor & self, const torch::List<c10::optional<Tensor>>& indices, const Tensor & value, const bool accumulate) { return at::_index_put_impl_(self, indices, value, accumulate, /*unsafe=*/false); } TORCH_IMPL_FUNC(index_copy_out) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& source, const Tensor& result) { if (!result.is_same(self)) result.copy_(self); // See Note [Enabling Deterministic Operations] if (result.is_cuda() && globalContext().deterministicAlgorithms()){ torch::List<c10::optional<Tensor>> indices; indices.reserve(dim + 1); for (const auto i: c10::irange(dim)) { (void)i; indices.emplace_back(); } indices.emplace_back(index); result.index_put_(indices, source, false); return; } // Handle the case when self / source is 0-dim Tensor result_nonzero = result.dim() == 0 ? result.unsqueeze(0) : result; Tensor source_nonzero = source.dim() == 0 ? source.unsqueeze(0) : source; // The only difference between the following tensor iterator and that of index_fill_ is that // this one has also source as an input. We should refactor it when if constexpr is available (C++17) // Prepare `index` for TensorIterator. // It is restrided to be broadcastable over `self` in TensorIterator. auto index_sizes = std::vector<int64_t>(result_nonzero.dim(), 1); auto index_strides = std::vector<int64_t>(result_nonzero.dim(), 0); index_sizes[dim] = index.numel(); index_strides[dim] = (index.dim() > 0) ? index.stride(0) : 1; // `index` is 1d or scalar auto index_restrided = index.as_strided( index_sizes, index_strides); // Prepare `result` for TensorIterator. // Restride `result` to not advance in dimension `dim`. // We do not use squash_dim here because `index` will // need to advance in this dimension. // Note that self_sizes[dim] is set to index.numel(). // This is done so that self_sizes[dim] and index_sizes[dim] // match as required by TensorIterator (input shape should // strictly broadcast over output shape, i.e. // output.shape[i] >= input.shape[i] for i in range(dims)). auto result_sizes = result_nonzero.sizes().vec(); auto result_strides = result_nonzero.strides().vec(); result_sizes[dim] = index.numel(); result_strides[dim] = 0; auto result_restrided = result_nonzero.as_strided(result_sizes, result_strides); auto iter = TensorIteratorConfig() // We do not check for overlap because `result` is restrided // with zero stride. Zero strides trigger memory overlap assert // within TensorIterator. .set_check_mem_overlap(false) .check_all_same_dtype(false) .resize_outputs(false) .add_output(result_restrided) .add_input(index_restrided) .add_input(source_nonzero) .build(); auto result_dim_size = result_nonzero.size(dim); auto result_dim_stride = result_nonzero.stride(dim); index_copy_stub( iter.device_type(), iter, dim, result_dim_size, result_dim_stride); } TORCH_IMPL_FUNC(index_add_cpu_out) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& source, const Scalar& alpha, const Tensor& result) { if (!result.is_same(self)) result.copy_(self); auto numel = index.numel(); auto index_contig = index.contiguous(); if (result.dim() > 1) { // Equivalent to: // for (const auto i : c10::irange(numel)) { // auto selfSlice = self.select(dim, index_data[i]); // auto sourceSlice = source.select(dim, i); // selfSlice.add_(sourceSlice); // } // But much faster as this reuses the iterator from add_ if (numel == 0) { return; } auto selfSlice = result.select(dim, 0); auto sourceSlice = source.select(dim, 0); auto self_stride_bytes = result.stride(dim) * elementSize(result.scalar_type()); auto source_stride_bytes = source.stride(dim) * elementSize(source.scalar_type()); auto self_dim_size = result.size(dim); auto iter = TensorIterator::borrowing_binary_op(selfSlice, selfSlice, sourceSlice); AT_DISPATCH_INDEX_TYPES(index.scalar_type(), "index_add_cpu_", [&] () { auto index_data = index_contig.data_ptr<index_t>(); for (const auto i : c10::irange(numel)) { auto self_i = index_data[i]; TORCH_CHECK_INDEX((self_i >= 0) && (self_i < self_dim_size), "index out of range in self"); auto self_data = static_cast<char*>(selfSlice.data_ptr()) + self_i * self_stride_bytes; auto source_data = static_cast<char*>(sourceSlice.data_ptr()) + i * source_stride_bytes; iter.unsafe_replace_operand(0, self_data); iter.unsafe_replace_operand(1, self_data); iter.unsafe_replace_operand(2, source_data); add_stub(iter.device_type(), iter, alpha); } }); } else { TORCH_CHECK(source.dim() <= 1, "source.dim() (", source.dim(), ") must one or zero for given self.dim() (", self.dim(), ")"); // explicitly capture all required variables to work around windows build // TODO: fix this when windows can correctly capture variables in nested lambda AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Half, ScalarType::Bool, ScalarType::BFloat16, result.scalar_type(), "index_add_", [&result, &source, &dim, &index_contig, &numel, &alpha] { auto alpha_value = alpha.to<scalar_t>(); auto result_stride = result.dim() == 0 ? 1 : result.stride(dim); auto source_stride = source.dim() == 0 ? 1 : source.stride(dim); // TODO: Maybe TensorAccessor can be used here? auto* result_ptr = result.data_ptr<scalar_t>(); auto* source_ptr = source.data_ptr<scalar_t>(); AT_DISPATCH_INDEX_TYPES(index_contig.scalar_type(), "index_add_cpu_", [&index_contig, &numel, &result, &result_ptr, &result_stride, &source_ptr, &source_stride, &alpha_value] { auto index_data = index_contig.data_ptr<index_t>(); for (const auto i : c10::irange(numel)) { auto self_i = index_data[i]; TORCH_CHECK_INDEX((self_i >= 0) && (self_i < result.numel()), "index out of range in self"); scalar_t *self_ip = result_ptr + self_i * result_stride; *self_ip += *(source_ptr + i * source_stride) * alpha_value; } }); }); } } // Check that indices fall within dimension array size // Avoid redispatch call to min/max template <typename IndexType> static void check_indexarray_range( const IndexType* indices, int64_t n, IndexType indexing_axis_dim) { for (const auto i : c10::irange(n)) { auto idx = indices[i]; TORCH_CHECK( 0 <= idx && idx < indexing_axis_dim, "INDICES element is out of DATA bounds, id=", idx, " axis_dim=", indexing_axis_dim); } } Tensor & index_select_out_cpu_dim1_( Tensor & result_contig, const Tensor & self, const Tensor & index_contig) { auto self_contig = self.contiguous(); const caffe2::TypeMeta dataType = self_contig.dtype(); size_t item_bytesize = dataType.itemsize(); auto out = static_cast<char*>(result_contig.data_ptr()); auto src_base = static_cast<const char*>(self_contig.data_ptr()); auto self_sizes = self_contig.sizes(); auto outer_dims_product = c10::size_to_dim_(1, self_sizes); auto block_size = c10::size_from_dim_(2, self_sizes); auto block_bytesize = block_size * item_bytesize; auto src_indexing_axis_dim = self_sizes[1]; auto src_batch_bytesize = self_sizes[1] * block_bytesize; auto N = index_contig.numel(); auto gathered_batch_bytesize = N * block_bytesize; AT_DISPATCH_INDEX_TYPES( index_contig.scalar_type(), "batch_index_select_compute", [&]() { const auto* idxs = index_contig.data_ptr<index_t>(); check_indexarray_range<index_t>(idxs, N, src_indexing_axis_dim); // Special-case single-float copy for efficiency if (self.scalar_type() == ScalarType::Float && block_size == 1) { for (const auto batch : c10::irange(outer_dims_product)) { const float* src_floats = (const float*)(src_base + batch * src_batch_bytesize); float* dst_floats = (float*)(out + batch * gathered_batch_bytesize); for (const auto i : c10::irange(N)) { auto idx = idxs[i]; dst_floats[i] = src_floats[idx]; } } } else { // outer_dims_product specifies how many times we repeat inner dimensions, // so we just iterate over it to cover all outer dimensions. for (const auto batch : c10::irange(outer_dims_product)) { for (const auto i : c10::irange(N)) { auto idx = idxs[i]; auto src = src_base + batch * src_batch_bytesize + idx * block_bytesize; auto dst = out + batch * gathered_batch_bytesize + i * block_bytesize; memcpy(dst, src, block_bytesize); } } } }); return result_contig; } Tensor & index_select_out_cpu_(const Tensor & self, int64_t dim, const Tensor & index, Tensor & result) { if (self.is_quantized()) { TORCH_CHECK( self.qscheme() == kPerTensorAffine, "Only per_tensor quantized quantized tensors are supported by index_select.") } dim = maybe_wrap_dim(dim, self.dim()); auto numel = index.numel(); TORCH_CHECK_INDEX(index.dim() <= 1, "index_select(): Index is supposed to be a vector"); TORCH_CHECK(index.scalar_type() == ScalarType::Long || index.scalar_type() == ScalarType::Int, "index_select(): Expected dtype int32 or int64 for index"); TORCH_CHECK(self.scalar_type() == result.scalar_type(), "index_select(): self and result must have the same scalar type"); TORCH_CHECK(dim == 0 || dim < self.dim(), "index_select(): Indexing dim ", dim, " is out of bounds of tensor"); at::assert_no_internal_overlap(result); at::assert_no_overlap(result, self); at::assert_no_overlap(result, index); auto result_size = self.sizes().vec(); if (self.dim() > 0) { result_size[dim] = numel; } at::native::resize_output(result, result_size); auto index_contig = index.contiguous(); if (self.dim() > 1) { if (numel == 0 || self.numel() == 0) { return result; } if (dim == 1 && result.is_contiguous()) { // fast pass return index_select_out_cpu_dim1_(result, self, index_contig); } auto selfSlice = self.select(dim, 0); auto resultSlice = result.select(dim, 0); auto selfSlice_data = selfSlice.data_ptr(); auto resultSlice_data = resultSlice.data_ptr(); auto self_stride_bytes = self.stride(dim) * elementSize(self.scalar_type()); auto result_stride_bytes = result.stride(dim) * elementSize(result.scalar_type()); auto self_dim_size = self.size(dim); auto slice_size = selfSlice.numel(); auto iter = TensorIteratorConfig() .check_all_same_dtype(false) .resize_outputs(false) .add_output(resultSlice) .add_input(selfSlice) .build(); auto grain_size = at::internal::GRAIN_SIZE; auto outer_loop = // explicitly capture all required variables to work around windows build // TODO: fix this when windows can correctly capture variables in nested lambda [&index_contig, &iter, &self_dim_size, &selfSlice_data, &self_stride_bytes, &resultSlice_data, &result_stride_bytes](int64_t start, int64_t end) { auto sub_iter = TensorIterator(iter); AT_DISPATCH_INDEX_TYPES(index_contig.scalar_type(), "index_select_out_cpu_", [&index_contig, &start, &end, &sub_iter, &self_dim_size, &selfSlice_data, &self_stride_bytes, &resultSlice_data, &result_stride_bytes] () { auto index_data = index_contig.data_ptr<index_t>(); for (const auto i : c10::irange(start, end)) { auto self_i = index_data[i]; TORCH_CHECK_INDEX((self_i >= 0) && (self_i < self_dim_size), "index out of range in self"); auto self_data = static_cast<char*>(selfSlice_data) + self_i * self_stride_bytes; auto result_data = static_cast<char*>(resultSlice_data) + i * result_stride_bytes; sub_iter.unsafe_replace_operand(0, result_data); sub_iter.unsafe_replace_operand(1, self_data); copy_stub(sub_iter.device_type(), sub_iter, false); }; }); }; // parallel on inner loop in case the slice is large enough; // otherwise parallel on outer loop if (slice_size >= grain_size) { outer_loop(0, numel); } else { // use a fast loop when self and result are contiguous and of the same data type if (iter.is_contiguous() && self.scalar_type() == result.scalar_type()) { auto slice_size_bytes = slice_size * elementSize(self.scalar_type()); // explicitly capture all required variables to work around windows build // TODO: fix this when windows can correctly capture variables in nested lambda at::parallel_for(0, numel, grain_size / slice_size, [&index_contig, &slice_size_bytes, &self_dim_size, &selfSlice_data, &self_stride_bytes, &resultSlice_data, &result_stride_bytes](int64_t start, int64_t end) { AT_DISPATCH_INDEX_TYPES(index_contig.scalar_type(), "index_select_out_cpu_", [&index_contig, &slice_size_bytes, &self_dim_size, &selfSlice_data, &self_stride_bytes, &resultSlice_data, &result_stride_bytes, &start, &end] () { auto index_data = index_contig.data_ptr<index_t>(); for (const auto i : c10::irange(start, end)) { auto self_i = index_data[i]; TORCH_CHECK_INDEX((self_i >= 0) && (self_i < self_dim_size), "index out of range in self"); auto self_data = static_cast<char*>(selfSlice_data) + self_i * self_stride_bytes; auto result_data = static_cast<char*>(resultSlice_data) + i * result_stride_bytes; memcpy(result_data, self_data, slice_size_bytes); } }); }); } else { at::parallel_for(0, numel, grain_size / slice_size, outer_loop); } } } else { TORCH_CHECK(result.dim() <= 1, "result.dim() (", result.dim(), ") must one or zero for given self.dim() (", self.dim(), ")"); // explicitly capture all required variables to work around windows build // TODO: fix this when windows can correctly capture variables in nested lambda if(self.is_quantized()){ AT_DISPATCH_QINT_TYPES(self.scalar_type(), "index_select_quant", [&index_contig, &self, &result, &dim, &numel] { auto self_stride = self.dim() == 0 ? 1 : self.stride(dim); auto result_stride = result.dim() == 0 ? 1 : result.stride(dim); auto self_data_ptr = self.data_ptr<scalar_t>(); auto result_data_ptr = result.data_ptr<scalar_t>(); auto self_numel = self.numel(); AT_DISPATCH_INDEX_TYPES(index_contig.scalar_type(), "index_select_out_cpu_quant_", [&index_contig, &numel, &self_numel, &self_data_ptr, &self_stride, &result_data_ptr, &result_stride] { auto index_data = index_contig.data_ptr<index_t>(); for (const auto i : c10::irange(numel)) { auto self_i = index_data[i]; TORCH_CHECK_INDEX((self_i >= 0) && (self_i < self_numel), "index out of range in self"); scalar_t *self_ip = self_data_ptr + self_i * self_stride; *(result_data_ptr + i * result_stride) = *self_ip; } }); }); } else { AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Half, ScalarType::Bool, ScalarType::BFloat16, self.scalar_type(), "index_select", [&index_contig, &self, &result, &dim, &numel] { auto self_stride = self.dim() == 0 ? 1 : self.stride(dim); auto result_stride = result.dim() == 0 ? 1 : result.stride(dim); auto self_data_ptr = self.data_ptr<scalar_t>(); auto result_data_ptr = result.data_ptr<scalar_t>(); auto self_numel = self.numel(); AT_DISPATCH_INDEX_TYPES(index_contig.scalar_type(), "index_select_out_cpu_", [&index_contig, &numel, &self_numel, &self_data_ptr, &self_stride, &result_data_ptr, &result_stride] { auto index_data = index_contig.data_ptr<index_t>(); for (const auto i : c10::irange(numel)) { auto self_i = index_data[i]; TORCH_CHECK_INDEX((self_i >= 0) && (self_i < self_numel), "index out of range in self"); scalar_t *self_ip = self_data_ptr + self_i * self_stride; *(result_data_ptr + i * result_stride) = *self_ip; } }); }); } } return result; } Tensor index_select_cpu_(const Tensor & self, int64_t dim, const Tensor & index) { Tensor result = at::empty({0}, self.options()); return at::native::index_select_out_cpu_(self, dim, index, result); } Tensor index_select_quantized_cpu_(const Tensor & self, int64_t dim, const Tensor & index) { TORCH_CHECK(self.qscheme() == kPerTensorAffine, "Only per_tensor quantized quantized tensors are supported by index_select.") Tensor result = at::empty_quantized({0}, self); return at::native::index_select_out_cpu_(self, dim, index, result); } Tensor index_select_backward(const Tensor& grad, IntArrayRef self_sizes, int64_t dim, const Tensor& index) { return at::zeros(self_sizes, grad.options()).index_add_(dim, index, grad); } Tensor & index_fill_(Tensor & self, int64_t dim, const Tensor & index, const Scalar& source) { at::NoNamesGuard guard; TORCH_CHECK_INDEX( index.scalar_type() == ScalarType::Long, "index_fill_(): Expected dtype int64 for index."); at::assert_no_overlap(self, index); if (at::has_internal_overlap(self) == at::MemOverlap::YES) { TORCH_WARN( "Use of index_fill_ on expanded tensors is deprecated. " "Please clone() the tensor before performing this operation. " "This also applies to advanced indexing e.g. tensor[mask] = scalar"); } if (!self.is_complex() && source.isComplex()) { TORCH_CHECK(false, "index_fill_(): Converting complex Scalar to non-complex type is not supported"); } // Handle the case when `self` is 0-dim Tensor self_nonzero_dim = (self.dim() == 0) ? self.unsqueeze(-1) : self; dim = at::maybe_wrap_dim(dim, self_nonzero_dim); TORCH_CHECK(index.dim() <= 1, "Index has to be a vector/scalar"); // Prepare `index` for TensorIterator. // It is restrided to be broadcastable over `self` in TensorIterator. auto index_sizes = std::vector<int64_t>(self_nonzero_dim.dim(), 1); auto index_strides = std::vector<int64_t>(self_nonzero_dim.dim(), 0); index_sizes[dim] = index.numel(); index_strides[dim] = (index.dim() > 0) ? index.stride(0) : 1; // `index` is 1d or scalar auto index_restrided = index.as_strided( index_sizes, index_strides); // Prepare `self` for TensorIterator. // Restride `self` to not advance in dimension `dim`. // We do not use squash_dim here because `index` will // need to advance in this dimension. // Note that self_sizes[dim] is set to index.numel(). // This is done so that self_sizes[dim] and index_sizes[dim] // match as required by TensorIterator (input shape should // strictly broadcast over output shape, i.e. // output.shape[i] >= input.shape[i] for i in range(dims)). auto self_sizes = self_nonzero_dim.sizes().vec(); auto self_strides = self_nonzero_dim.strides().vec(); self_sizes[dim] = index.numel(); self_strides[dim] = 0; auto self_restrided = self_nonzero_dim.as_strided(self_sizes, self_strides); auto iter = TensorIteratorConfig() // We do not check for overlap because `self` is restrided // with zero stride. Zero strides trigger memory overlap assert // within TensorIterator. .set_check_mem_overlap(false) .check_all_same_dtype(false) .resize_outputs(false) .add_output(self_restrided) .add_input(index_restrided) .build(); auto self_dim_size = (self_nonzero_dim.sizes())[dim]; auto self_dim_stride = (self_nonzero_dim.strides())[dim]; index_fill_stub( iter.device_type(), iter, dim, self_dim_size, self_dim_stride, source); return self; } Tensor & index_fill_(Tensor & self, int64_t dim, const Tensor & index, const Tensor & source) { TORCH_CHECK(source.dim() == 0, "index_fill_ only supports a 0-dimensional value tensor, but got tensor " "with ", source.dim(), " dimension(s)."); return self.index_fill_(dim, index, source.item()); } Tensor index_fill(const Tensor & self, int64_t dim, const Tensor & index, const Scalar& source) { return self.clone(at::MemoryFormat::Preserve).index_fill_(dim, index, source); } Tensor index_fill(const Tensor & self, int64_t dim, const Tensor & index, const Tensor & source) { return self.clone(at::MemoryFormat::Preserve).index_fill_(dim, index, source); } // gather_out_cpu_cuda TORCH_IMPL_FUNC(gather_out) (const Tensor& self, int64_t dim, const Tensor& index, bool sparse_grad, const Tensor& result) { if (index.numel() == 0) return; dim = at::maybe_wrap_dim(dim, self.dim()); gather_stub(result.device().type(), result, self, dim, index); } Tensor gather_backward(const Tensor& grad, const Tensor& self, int64_t dim, const Tensor& index, bool sparse_grad) { if (sparse_grad) { return at::_gather_sparse_backward(self, dim, index, grad); } return grad.new_zeros(self.sizes()).scatter_add_(dim, index, grad); } template <bool use_new_options = false, typename T, typename ReduceStub, typename FillStub> void scatter_impl( const Tensor& self, int64_t dim, const Tensor& index, const T& src, const Tensor& out, ReduceStub& reduce_stub, FillStub& fill_stub, const c10::optional<c10::string_view> reduce = nullopt) { dim = at::maybe_wrap_dim(dim, self.dim()); auto mut_out = const_cast<Tensor&>(out); if (!self.is_same(mut_out)) { mut_out.copy_(self); } if (index.numel() == 0) return; if (reduce.has_value()) { auto op = meta::get_operator_enum(reduce.value(), use_new_options); reduce_stub(self.device().type(), mut_out, dim, index, src, op); } else { fill_stub(self.device().type(), mut_out, dim, index, src); } } TORCH_IMPL_FUNC(scatter_src_out) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src, const Tensor& out) { scatter_impl(self, dim, index, src, out, scatter_reduce_stub, scatter_stub); } TORCH_IMPL_FUNC(scatter_value_out) (const Tensor& self, int64_t dim, const Tensor& index, const Scalar& value, const Tensor& out) { scatter_impl(self, dim, index, value, out, scatter_scalar_reduce_stub, scatter_fill_stub); } TORCH_IMPL_FUNC(scatter_reduce_out) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src, const c10::string_view reduce, const Tensor& out) { scatter_impl(self, dim, index, src, out, scatter_reduce_stub, scatter_stub, reduce); } TORCH_IMPL_FUNC(scatter_value_reduce_out) (const Tensor& self, int64_t dim, const Tensor& index, const Scalar& value, const c10::string_view reduce, const Tensor& out) { scatter_impl(self, dim, index, value, out, scatter_scalar_reduce_stub, scatter_fill_stub, reduce); } TORCH_IMPL_FUNC(scatter_add) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src, const Tensor& out) { auto mut_out = const_cast<Tensor&>(out); dim = maybe_wrap_dim(dim, self.dim()); if (!self.is_same(mut_out)) { mut_out.copy_(self); } if (index.numel() == 0) return; if (globalContext().deterministicAlgorithms() && self.device().type() == DeviceType::CUDA && self.dim() == 1) { TORCH_CHECK(index.dim() == 1 && src.dim() == 1, "index and src should be 1D tensors when self is a 1D tensor, " "but their dims are ", index.dim(), " and ", src.dim(), ", respectively"); TORCH_CHECK(index.numel() == src.numel(), "index and src should have same number of elements for 1D tensors, " "but got ", index.numel(), " versus ", src.numel()); TORCH_CHECK(dim == 0, "dim should be zero for 1D self tensor, but got ", dim); torch::List<c10::optional<Tensor>> indices; indices.reserve(1); indices.push_back(index); mut_out.index_put_(indices, src, true); } else { scatter_add_stub(self.device().type(), mut_out, dim, index, src); } } TORCH_IMPL_FUNC(scatter_reduce_two) (const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src, const c10::string_view reduce, const Tensor& out) { // See issue https://github.com/pytorch/pytorch/issues/74770 TORCH_WARN_ONCE("scatter_reduce() is an early prototype and the API may change at any time."); scatter_impl</*use_new_options=*/true>(self, dim, index, src, out, scatter_reduce_two_stub, scatter_stub, reduce); if (meta::get_operator_enum(reduce, true) == SCATTER_GATHER_OP::REDUCE_MEAN) { auto ones = at::ones_like(src); auto count = at::ones_like(out); count.scatter_add_(dim, index, ones); if (out.is_floating_point() || out.is_complex()) { out.div_(count); } else { out.div_(count, "floor"); } } } Tensor masked_scatter(const Tensor & self, const Tensor & mask, const Tensor & source) { c10::MaybeOwned<Tensor> _mask, _self; std::tie(_mask, _self) = expand_outplace(mask, self); return _self->clone(at::MemoryFormat::Contiguous).masked_scatter_(*_mask, source); } static Tensor & masked_fill_impl_cpu(Tensor & self, const Tensor & mask, const Scalar& value) { NoNamesGuard guard; if (mask.dtype() == ScalarType::Byte) { TORCH_WARN("masked_fill_ received a mask with dtype torch.uint8, this behavior is now deprecated," \ "please use a mask with dtype torch.bool instead."); } if (at::has_internal_overlap(self) == MemOverlap::YES) { TORCH_WARN( "Use of masked_fill_ on expanded tensors is deprecated. " "Please clone() the tensor before performing this operation. " "This also applies to advanced indexing e.g. tensor[mask] = scalar"); } at::assert_no_partial_overlap(self, mask); auto iter = TensorIteratorConfig() .set_check_mem_overlap(false) // deprecated, but not a hard error .check_all_same_dtype(false) .resize_outputs(false) .add_output(self) .add_input(mask) .build(); masked_fill_stub(iter.device_type(), iter, value); return self; } Tensor & masked_fill__cpu(Tensor& self, const Tensor & mask, const Scalar& value) { auto maybe_outnames = namedinference::broadcast_to_outnames(self, mask, "masked_fill_"); masked_fill_impl_cpu(self, mask, value); namedinference::propagate_names_if_nonempty(self, maybe_outnames); return self; } Tensor & masked_fill__cpu(Tensor& self, const Tensor & mask, const Tensor & value) { auto maybe_outnames = namedinference::broadcast_to_outnames(self, mask, "masked_fill_"); TORCH_CHECK(value.dim() == 0, "masked_fill_ only supports a 0-dimensional value tensor, but got tensor " "with ", value.dim(), " dimension(s)."); masked_fill_impl_cpu(self, mask, value.item()); namedinference::propagate_names_if_nonempty(self, maybe_outnames); return self; } Tensor masked_fill(const Tensor & self, const Tensor & mask, const Scalar& source) { Tensor result; auto maybe_outnames = namedinference::broadcast_to_outnames(mask, self, "masked_fill"); { NoNamesGuard guard; c10::MaybeOwned<Tensor> _mask, _self; std::tie(_mask, _self) = expand_outplace(mask, self); result = _self->clone(at::MemoryFormat::Contiguous); result.masked_fill_(mask, source); } namedinference::propagate_names_if_nonempty(result, maybe_outnames); return result; } Tensor masked_fill(const Tensor & self, const Tensor & mask, const Tensor & source) { Tensor result; auto maybe_outnames = namedinference::broadcast_to_outnames(mask, self, "masked_fill"); { NoNamesGuard guard; c10::MaybeOwned<Tensor> _mask, _self; std::tie(_mask, _self) = expand_outplace(mask, self); result = _self->clone(at::MemoryFormat::Contiguous); result.masked_fill_(mask, source); } namedinference::propagate_names_if_nonempty(result, maybe_outnames); return result; } static Tensor & masked_select_out_impl_cpu(Tensor & result, const Tensor & self, const Tensor & mask) { NoNamesGuard guard; TORCH_CHECK(mask.scalar_type() == ScalarType::Byte || mask.scalar_type() == ScalarType::Bool, "masked_select: expected BoolTensor or ByteTensor for mask"); TORCH_CHECK(self.scalar_type() == result.scalar_type(), "masked_select(): self and result must have the same scalar type"); at::assert_no_internal_overlap(result); at::assert_no_overlap(result, self); at::assert_no_overlap(result, mask); if (mask.dtype() == at::ScalarType::Byte) { TORCH_WARN("masked_select received a mask with dtype torch.uint8, this behavior is now deprecated," \ "please use a mask with dtype torch.bool instead."); } c10::MaybeOwned<Tensor> _mask, _self; std::tie(_mask, _self) = expand_outplace(mask, self); auto shape = _self->sizes(); int64_t numel = _mask->sum().item().toLong(); at::native::resize_output(result, {numel}); if (numel == 0) { return result; } // Create strided view of result before feeding into TensorIterator auto strides = DimVector(shape.size(), 0); auto orig_stride = result.strides()[0]; auto result_strided = result.as_strided(shape, strides); // serial kernel // serial kernel requires that src is traversed in its logical order. However, TensorIterator might // have reordered dimensions so that src would be traversed in its physical order, producing wrong // answers. A sufficient condition that no reorder happened is that both _self and _mask is contiguous. // If it is not satisfied, use parallel kernel that handles permutations correctly bool use_serial_kernel = (self.numel() < at::internal::GRAIN_SIZE || at::get_num_threads() == 1 ) && _self->is_contiguous() && _mask->is_contiguous(); if (use_serial_kernel) { auto iter = TensorIteratorConfig() .set_check_mem_overlap(false) // result is intenionally zero-strided above .check_all_same_dtype(false) .resize_outputs(false) .add_output(result_strided) .add_input(*_self) .add_input(*_mask) .build(); masked_select_serial_stub(iter.device_type(), iter, orig_stride); return result; } // Use a prefix sum to record the output locations of the masked elements, // so as to parallel with TensorIterator. auto mask_long = at::empty(shape, self.options().dtype(at::kLong)).copy_(*_mask); auto mask_prefix_sum = at::empty(shape, self.options().dtype(at::kLong)); auto mask_long_data = mask_long.data_ptr<int64_t>(); auto mask_prefix_sum_data = mask_prefix_sum.data_ptr<int64_t>(); // TODO: Here can only use std::partial_sum for C++14, // use std::exclusive_scan when PyTorch upgrades to C++17, which have better peformance. // std::exclusive_scan(mask_long_data, mask_long_data + mask_long.numel(), mask_prefix_sum_data, 0); std::partial_sum(mask_long_data, mask_long_data + mask_long.numel(), mask_prefix_sum_data); auto iter = TensorIteratorConfig() .set_check_mem_overlap(false) // result is intenionally zero-strided above .check_all_same_dtype(false) .resize_outputs(false) .add_output(result_strided) .add_input(*_self) .add_input(*_mask) .add_input(mask_prefix_sum) .build(); masked_select_stub(iter.device_type(), iter, orig_stride); return result; } Tensor & masked_select_out_cpu(const Tensor & self, const Tensor & mask, Tensor & result) { namedinference::compute_broadcast_outnames(self, mask); return masked_select_out_impl_cpu(result, self, mask); } Tensor masked_select_cpu(const Tensor & self, const Tensor & mask) { Tensor result = at::empty({0}, self.options()); return at::native::masked_select_out_cpu(self, mask, result); } Tensor masked_select_backward(const Tensor& grad, const Tensor& input, const Tensor& mask) { // The following could just be written as `zeros_like(input).masked_scatter(mask, grad)`. // However, as an optimization, we call the in-place variant of masked_scatter. // Unfortunately, that doesn't allow for the broadcasting of the LHS, so we need // to explicitly broadcast here (the out-of-place variant of masked_scatter // implicitly handles broadcasting). auto result = at::zeros_like( input.expand(at::infer_size(input.sizes(), mask.sizes())), at::MemoryFormat::Preserve); return result.masked_scatter_(mask, grad); } namespace { inline std::tuple<Tensor, Tensor, int64_t> _take_along_dim_helper( const Tensor& self, const Tensor& indices, int64_t dim) { TORCH_CHECK( self.dim() == indices.dim(), "torch.take_along_dim(): input and indices should have the same number of dimensions, ", "but got ", self.dim(), " dimensions for input, and ", indices.dim(), " dimensions for indices") TORCH_CHECK( indices.scalar_type() == ScalarType::Long, "torch.take_along_dim(): dtype of indices should be Long but got ", indices.scalar_type()) dim = at::maybe_wrap_dim(dim, self.dim()); DimVector self_sizes{self.sizes()}; // update number of elements at dim as per indices self_sizes[dim] = indices.size(dim); auto broadcast_shape = infer_size(self_sizes, indices.sizes()); auto indices_broadcasted = at::broadcast_to(indices, broadcast_shape); DimVector indices_sizes{indices.sizes()}; // update number of elements at dim as per self indices_sizes[dim] = self.size(dim); broadcast_shape = infer_size(indices_sizes, self.sizes()); auto self_broadcasted = at::broadcast_to(self, broadcast_shape); return std::make_tuple(self_broadcasted, indices_broadcasted, dim); } static inline void checkDevice(CheckedFrom c, const Tensor& t, Device device) { TORCH_CHECK( !t.defined() || t.device() == device, "Expected tensor to have ", device, " Device, but got tensor with ", t.device(), " Device ", "(while checking arguments for ", c, ")"); } static inline void checkDevice(CheckedFrom c, at::ArrayRef<Tensor> tensors, Device device) { for (auto &t : tensors) { checkDevice(c, t, device); } } } // anonymous namespace Tensor take_along_dim(const Tensor& self, const Tensor& indices, c10::optional<int64_t> opt_dim) { checkDevice("torch.take_along_dim():", {self, indices}, self.device()); if (opt_dim.has_value()) { // NOLINTNEXTLINE(cppcoreguidelines-init-variables) int64_t dim; Tensor self_broadcasted, indices_broadcasted; std::tie(self_broadcasted, indices_broadcasted, dim) = _take_along_dim_helper(self, indices, opt_dim.value()); return self_broadcasted.gather(dim, indices_broadcasted); } // similar to `take`, but `take` doesn't support the same dtypes as `gather`. return self.view(-1).gather(0, indices.view(-1)); } Tensor& take_along_dim_out(const Tensor& self, const Tensor& indices, c10::optional<int64_t> opt_dim, Tensor& result) { checkDevice("torch.take_along_dim():", {self, indices, result}, self.device()); if (opt_dim.has_value()) { // NOLINTNEXTLINE(cppcoreguidelines-init-variables) int64_t dim; Tensor self_broadcasted, indices_broadcasted; std::tie(self_broadcasted, indices_broadcasted, dim) = _take_along_dim_helper(self, indices, opt_dim.value()); return at::gather_out(result, self_broadcasted, dim, indices_broadcasted); } // similar to `take`, but `take` doesn't support the same dtypes as `gather`. return at::gather_out(result, self.view(-1), 0, indices.view(-1)); } Tensor _gather_sparse_backward(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& grad){ // special case scalar input and/or index if (self.ndimension() == 0) return at::_sparse_coo_tensor_unsafe(at::empty({0,grad.numel()}, index.options()), grad, self.sizes()); if (grad.ndimension() == 0) return at::_sparse_coo_tensor_unsafe(index.view({1,1}), grad, self.sizes()); Tensor sparse_ind = at::empty({self.ndimension(), grad.numel()}, self.options().dtype(at::kLong)); int64_t n_above = grad.numel(); int64_t n_below = 1; if (dim < 0) dim += self.ndimension(); for (const auto i : c10::irange(self.ndimension())) { n_above /= grad.size(i); if (i == dim) { sparse_ind[i] = index.reshape(-1); } else { sparse_ind[i] = at::arange(grad.size(i),self.options().dtype(at::kLong)).unsqueeze(1).expand({grad.size(i), n_above}).reshape(-1).repeat(n_below); } n_below *= grad.size(i); } return at::_sparse_coo_tensor_unsafe(sparse_ind, grad.reshape(-1), self.sizes()); } template <typename scalar_t> int64_t count_nonzero_impl(TensorIteratorBase& iter, Range range) { int64_t num_nonzero = 0; auto loop = [&](char** data, const int64_t* strides, int64_t n) { constexpr int ilp_factor = 4; const char* ptr = data[0]; const auto stride = strides[0]; int64_t nonzero[ilp_factor] = {0}; int64_t i = 0; for (; i + (ilp_factor - 1) < n; i += ilp_factor) { c10::ForcedUnroll<ilp_factor>{}([&](int k) { const auto& val = *reinterpret_cast<const scalar_t*>(ptr + k * stride); if (val != scalar_t(0)) { ++nonzero[k]; } }); ptr += ilp_factor * stride; } for (; i < n; ++i) { const auto& val = *reinterpret_cast<const scalar_t*>(ptr); if (val != scalar_t(0)) { ++nonzero[0]; } ptr += stride; } for (const auto k : c10::irange(1, ilp_factor)) { nonzero[0] += nonzero[k]; } num_nonzero += nonzero[0]; }; iter.serial_for_each(loop, range); return num_nonzero; } Tensor count_nonzero_cuda(const Tensor& self, IntArrayRef dims){ return (self != 0).sum(dims); } Tensor count_nonzero_cpu(const Tensor& self, IntArrayRef dims){ if (dims.size() > 0) { return (self != 0).sum(dims); } // Optimized all-reduce auto iter = TensorIteratorConfig() .add_input(self) .build(); const auto num_threads = at::get_num_threads(); DimVector thread_count_nonzero(num_threads); AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( kHalf, kBFloat16, kBool, self.scalar_type(), "nonzero_count_cpu", [&] { at::parallel_for(0, iter.numel(), internal::GRAIN_SIZE, [&] (int64_t begin, int64_t end) { const auto tid = at::get_thread_num(); thread_count_nonzero[tid] = count_nonzero_impl<scalar_t>(iter, {begin, end}); }); }); for (const auto i : c10::irange(1, num_threads)) { thread_count_nonzero[0] += thread_count_nonzero[i]; } auto out = at::empty({}, self.options().dtype(kLong)); *out.data_ptr<int64_t>() = thread_count_nonzero[0]; return out; } Tensor count_nonzero(const Tensor& self, c10::optional<int64_t> dim) { if (dim) { return at::count_nonzero(self, IntArrayRef{*dim}); } return at::count_nonzero(self, IntArrayRef{}); } Tensor& nonzero_out_cpu(const Tensor& self, Tensor& result) { TORCH_CHECK(result.scalar_type() == kLong, "nonzero: Expected out tensor to have scalar type Long " "but got scalar type", result.scalar_type()); at::assert_no_internal_overlap(result); at::assert_no_overlap(result, self); auto iter = TensorIteratorConfig() .add_input(self) .enforce_linear_iteration() .build(); const auto numel = iter.numel(); const auto num_threads = at::get_num_threads(); DimVector thread_begin(num_threads, -1); DimVector thread_count_nonzero(num_threads + 1); // Pass 1: Count nonzero element per-thread AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( kHalf, kBFloat16, kBool, self.scalar_type(), "nonzero_count_cpu", [&] { at::parallel_for(0, numel, internal::GRAIN_SIZE, [&] (int64_t begin, int64_t end) { const auto tid = at::get_thread_num(); thread_begin[tid] = begin; thread_count_nonzero[tid + 1] = count_nonzero_impl<scalar_t>(iter, {begin, end}); }); }); // Convert thread-local counts to cumulative sum for (const auto i : c10::irange(1, thread_count_nonzero.size())) { thread_count_nonzero[i] += thread_count_nonzero[i - 1]; } const auto self_sizes = self.sizes(); const auto total_nonzero = thread_count_nonzero.back(); const int64_t ndim = self_sizes.size(); if (resize_output(result, {total_nonzero, ndim})) { // Default to fortran-contiguous output (see gh-46224) result.as_strided_({total_nonzero, ndim}, {1, total_nonzero}); } if (result.numel() == 0) { return result; } // Pass 2: Write indexes AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( kHalf, kBFloat16, kBool, self.scalar_type(), "nonzero_cpu", [&] { at::parallel_for(0, numel, internal::GRAIN_SIZE, [&] (int64_t begin, int64_t end) { auto tid = at::get_thread_num(); // Work needs to be distributed the same on both passes TORCH_INTERNAL_ASSERT_DEBUG_ONLY(begin == thread_begin[tid]); // +1 faster than additional condition check inside loop c10::SmallVector<int64_t, 33> sizes(ndim + 1, -1); std::copy(self_sizes.begin(), self_sizes.end(), sizes.begin() + 1); c10::SmallVector<int64_t, 33> current_idx(ndim + 1); if (begin > 0) { auto idx = begin; for (int64_t k = ndim; idx > 0 && k > 0; --k) { current_idx[k] = idx % sizes[k]; idx /= sizes[k]; } } auto out_accessor = result.accessor<int64_t, 2>(); auto out_ptr = out_accessor[thread_count_nonzero[tid]].data(); auto loop = [&](char** data, const int64_t* strides, int64_t n1, int64_t n2) { // Copy into local variables to improve compiler alias analysis int64_t* C10_RESTRICT local_idx = current_idx.data() + 1; const int64_t* C10_RESTRICT local_sizes = sizes.data() + 1; const auto in_stride = strides[0]; const auto out_stride1 = out_accessor.stride(1); const auto out_stride0 = out_accessor.stride(0) - ndim * out_stride1; const auto ndim = out_accessor.size(1); int64_t* out = out_ptr; for (const auto i : c10::irange(n2)) { const char* ptr = data[0] + i * strides[1]; for (const auto j : c10::irange(n1)) { (void)j; //Suppress unused variable warning const auto& val = *reinterpret_cast<const scalar_t*>(ptr); // If nonzero, write index if (val != scalar_t(0)) { for (const auto k : c10::irange(ndim)) { *out = local_idx[k]; out += out_stride1; } out += out_stride0; } ptr += in_stride; // Advance current index int64_t k = ndim - 1; ++local_idx[k]; while (C10_UNLIKELY(local_idx[k] == local_sizes[k])) { local_idx[k] = 0; --k; ++local_idx[k]; } } } out_ptr = out; }; iter.serial_for_each(loop, {begin, end}); TORCH_INTERNAL_ASSERT(out_ptr == out_accessor[thread_count_nonzero[tid + 1]].data()); }); }); return result; } Tensor nonzero_cpu(const Tensor& self) { auto result = at::empty({0}, self.options().dtype(kLong)); nonzero_out_cpu(self, result); return result; } std::vector<Tensor> nonzero_numpy(const Tensor& self) { // special case scalar for compatibility with numpy: // // >>> np.array(5).nonzero() // (array([0]),) // >>> np.array(0).nonzero() // (array([], dtype=int64),) if (self.dim() == 0) { return self.unsqueeze(0).nonzero().unbind(1); } return self.nonzero().unbind(1); } Tensor argwhere(const Tensor& self) { return self.nonzero(); } Tensor & masked_scatter__cpu(Tensor& self, const Tensor & mask, const Tensor & source) { at::assert_no_internal_overlap(self); TORCH_CHECK( self.scalar_type() == source.scalar_type(), "masked_scatter: expected self and source to have same dtypes but got", self.scalar_type(), " and ", source.scalar_type()); TORCH_CHECK(self.device().type() == at::kCPU, "device type of self (", self.device().type(), ") is not CPU"); TORCH_CHECK(mask.device().type() == at::kCPU, "device type of mask (", mask.device().type(), ") is not CPU"); TORCH_CHECK(source.device().type() == at::kCPU, "device type of source (", source.device().type(), ") is not CPU"); c10::MaybeOwned<Tensor> b_mask = expand_inplace(self, mask, "masked_scatter_"); if (b_mask->dtype() == ScalarType::Byte) { TORCH_WARN("masked_scatter_ received a mask with dtype torch.uint8, this behavior is now deprecated," \ "please use a mask with dtype torch.bool instead."); } auto src_cont = source.contiguous(); auto iter = TensorIteratorConfig() .set_check_mem_overlap(false) .check_all_same_dtype(false) .resize_outputs(false) .add_output(self) .add_input(*b_mask) .build(); masked_scatter_stub(iter.device_type(), iter, src_cont); return self; } }} // at::native
; A154118: Expansion of (1 - x + 5x^2)/((1-x)*(1-2x)). ; 1,2,9,23,51,107,219,443,891,1787,3579,7163,14331,28667,57339,114683,229371,458747,917499,1835003,3670011,7340027,14680059,29360123,58720251,117440507,234881019,469762043,939524091,1879048187,3758096379,7516192763,15032385531,30064771067,60129542139,120259084283,240518168571,481036337147,962072674299,1924145348603,3848290697211,7696581394427,15393162788859,30786325577723,61572651155451,123145302310907,246290604621819,492581209243643,985162418487291,1970324836974587,3940649673949179,7881299347898363,15762598695796731,31525197391593467,63050394783186939,126100789566373883,252201579132747771,504403158265495547,1008806316530991099,2017612633061982203,4035225266123964411,8070450532247928827,16140901064495857659,32281802128991715323,64563604257983430651,129127208515966861307,258254417031933722619,516508834063867445243,1033017668127734890491,2066035336255469780987,4132070672510939561979,8264141345021879123963,16528282690043758247931,33056565380087516495867,66113130760175032991739,132226261520350065983483,264452523040700131966971,528905046081400263933947,1057810092162800527867899,2115620184325601055735803,4231240368651202111471611,8462480737302404222943227,16924961474604808445886459,33849922949209616891772923,67699845898419233783545851,135399691796838467567091707,270799383593676935134183419,541598767187353870268366843,1083197534374707740536733691,2166395068749415481073467387,4332790137498830962146934779,8665580274997661924293869563,17331160549995323848587739131,34662321099990647697175478267,69324642199981295394350956539,138649284399962590788701913083,277298568799925181577403826171,554597137599850363154807652347,1109194275199700726309615304699,2218388550399401452619230609403 mov $1,1 lpb $0 sub $0,1 add $2,$1 add $1,$2 mov $2,5 lpe mov $0,$1
SECTION code_clib PUBLIC read_joypad1 PUBLIC _read_joypad1 ;============================================================== ; int read_joypad1() ;============================================================== ; Reads the joystick 1 ;============================================================== .read_joypad1 ._read_joypad1 in a, ($dc) ; Reads joystick 1 cpl ; Inverts all bits ld h, 0 ld l, a ; Puts the result in HL ret
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r15 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x5b83, %r13 nop nop nop nop sub %rdx, %rdx mov $0x6162636465666768, %rdi movq %rdi, (%r13) nop nop nop nop nop cmp $63083, %rbp lea addresses_normal_ht+0xa683, %rdx nop nop nop nop nop and $49063, %rsi and $0xffffffffffffffc0, %rdx movaps (%rdx), %xmm4 vpextrq $1, %xmm4, %rdi nop nop nop nop dec %rsi lea addresses_UC_ht+0xd32b, %rsi lea addresses_normal_ht+0x1a2fb, %rdi sub %rdx, %rdx mov $57, %rcx rep movsw nop nop nop nop nop add %r13, %r13 lea addresses_WT_ht+0x1763, %rcx nop nop nop xor %r10, %r10 movw $0x6162, (%rcx) nop nop add %rdx, %rdx lea addresses_WT_ht+0x8083, %r13 cmp $60989, %rdx movw $0x6162, (%r13) nop nop cmp %rbp, %rbp lea addresses_WC_ht+0x13653, %rsi lea addresses_D_ht+0x14863, %rdi add $42429, %r15 mov $16, %rcx rep movsl nop nop mfence lea addresses_D_ht+0xffb3, %rdi nop add %rdx, %rdx movb (%rdi), %r10b nop nop nop and %rdi, %rdi lea addresses_A_ht+0x1bc83, %rsi nop nop cmp %r15, %r15 mov $0x6162636465666768, %rcx movq %rcx, %xmm2 movups %xmm2, (%rsi) nop nop nop sub $28183, %r13 lea addresses_WC_ht+0x5c83, %r15 nop nop nop nop xor %rsi, %rsi movb (%r15), %cl sub $45525, %rdx lea addresses_A_ht+0xc686, %rsi lea addresses_D_ht+0x90df, %rdi nop nop xor %rdx, %rdx mov $56, %rcx rep movsb nop and $11051, %rdi lea addresses_normal_ht+0x4943, %r15 nop nop nop add %rsi, %rsi movw $0x6162, (%r15) nop nop nop nop nop sub %rdx, %rdx lea addresses_A_ht+0x10483, %r13 nop nop nop nop nop inc %r10 movb $0x61, (%r13) nop nop and $28978, %rcx lea addresses_WC_ht+0x86d3, %r15 nop nop nop nop xor %rsi, %rsi movw $0x6162, (%r15) nop nop nop nop sub %r10, %r10 lea addresses_WT_ht+0x12283, %rsi clflush (%rsi) nop nop nop nop sub $61109, %r15 mov $0x6162636465666768, %rcx movq %rcx, (%rsi) nop nop add %r13, %r13 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r15 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r9 push %rax push %rbp push %rcx push %rdx // Store mov $0x5c7, %rax nop nop nop sub $16929, %r14 movw $0x5152, (%rax) nop nop cmp %rdx, %rdx // Store lea addresses_US+0x1b483, %r14 nop nop xor $38019, %rcx mov $0x5152535455565758, %rbp movq %rbp, %xmm7 movups %xmm7, (%r14) nop nop inc %rbp // Load mov $0x483, %r9 nop add %rdx, %rdx movb (%r9), %al nop xor %rbp, %rbp // Store lea addresses_PSE+0x12853, %rax sub %r9, %r9 mov $0x5152535455565758, %r13 movq %r13, (%rax) nop nop xor %r9, %r9 // Store mov $0x77d4ca0000000fe3, %rbp nop nop nop nop nop and $59218, %rdx mov $0x5152535455565758, %r13 movq %r13, %xmm2 vmovups %ymm2, (%rbp) nop nop nop nop cmp $55442, %rbp // Store lea addresses_normal+0x70c, %r13 nop nop nop nop nop dec %r14 movw $0x5152, (%r13) nop nop cmp %rbp, %rbp // Store mov $0x6c94270000000203, %rdx sub $44266, %r13 movb $0x51, (%rdx) nop cmp %rcx, %rcx // Faulty Load lea addresses_US+0x1b483, %rbp nop cmp %rdx, %rdx mov (%rbp), %ax lea oracles, %r14 and $0xff, %rax shlq $12, %rax mov (%r14,%rax,1), %rax pop %rdx pop %rcx pop %rbp pop %rax pop %r9 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_US', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_P', 'congruent': 2}, 'OP': 'STOR'} {'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_US', 'congruent': 0}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_P', 'congruent': 11}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_PSE', 'congruent': 2}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_NC', 'congruent': 5}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal', 'congruent': 0}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_NC', 'congruent': 7}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_US', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 8, 'type': 'addresses_UC_ht', 'congruent': 8}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 16, 'type': 'addresses_normal_ht', 'congruent': 7}} {'dst': {'same': False, 'congruent': 3, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WT_ht', 'congruent': 2}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 2, 'type': 'addresses_WT_ht', 'congruent': 10}, 'OP': 'STOR'} {'dst': {'same': True, 'congruent': 4, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_WC_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_D_ht', 'congruent': 1}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A_ht', 'congruent': 11}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WC_ht', 'congruent': 11}} {'dst': {'same': False, 'congruent': 2, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 0, 'type': 'addresses_A_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal_ht', 'congruent': 5}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_A_ht', 'congruent': 11}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WC_ht', 'congruent': 4}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 8, 'type': 'addresses_WT_ht', 'congruent': 3}, 'OP': 'STOR'} {'58': 21829} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
//-------------------------------------------------------------------------- // Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved. // Copyright (C) 2002-2013 Sourcefire, Inc. // Copyright (C) 1998-2002 Martin Roesch <roesch@sourcefire.com> // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License Version 2 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <pcap.h> #include "framework/logger.h" #include "framework/module.h" #include "log/messages.h" #include "main/snort_config.h" #include "protocols/packet.h" #include "packet_io/sfdaq.h" #include "utils/util.h" using namespace snort; using namespace std; /* * <pcap file> ::= <pcap file hdr> [<pcap pkt hdr> <packet>]* * on 64 bit systems, some fields in the <pcap * hdr> are 8 bytes * but still stored on disk as 4 bytes. * eg: (sizeof(*pkth) = 24) > (dumped size = 16) * so we use PCAP_*_HDR_SZ defines in lieu of sizeof(). */ #define PCAP_FILE_HDR_SZ (24) #define PCAP_PKT_HDR_SZ (16) struct LtdConfig { string file; size_t limit; }; struct LtdContext { char* file; pcap_dumper_t* dumpd; time_t lastTime; size_t size; int log_cnt; }; static THREAD_LOCAL LtdContext context; static void TcpdumpRollLogFile(LtdConfig*); #define S_NAME "log_pcap" #define F_NAME "log.pcap" //------------------------------------------------------------------------- // module stuff //------------------------------------------------------------------------- static const Parameter s_params[] = { { "limit", Parameter::PT_INT, "0:", "0", "set maximum size in MB before rollover (0 is unlimited)" }, { nullptr, Parameter::PT_MAX, nullptr, nullptr, nullptr } }; #define s_help \ "log packet in pcap format" class TcpdumpModule : public Module { public: TcpdumpModule() : Module(S_NAME, s_help, s_params) { } bool set(const char*, Value&, SnortConfig*) override; bool begin(const char*, int, SnortConfig*) override; Usage get_usage() const override { return CONTEXT; } public: unsigned long limit; }; bool TcpdumpModule::set(const char*, Value& v, SnortConfig*) { if ( v.is("limit") ) limit = v.get_long() * 1024 * 1024; else return false; return true; } bool TcpdumpModule::begin(const char*, int, SnortConfig*) { limit = 0; return true; } //------------------------------------------------------------------------- // api stuff //------------------------------------------------------------------------- static inline size_t SizeOf(const DAQ_PktHdr_t* pkth) { return PCAP_PKT_HDR_SZ + pkth->caplen; } static void LogTcpdumpSingle( LtdConfig* data, Packet* p, const char*, Event*) { size_t dumpSize = SizeOf(p->pkth); if ( data->limit && (context.size + dumpSize > data->limit) ) TcpdumpRollLogFile(data); pcap_dump((uint8_t*)context.dumpd, reinterpret_cast<const struct pcap_pkthdr*>(p->pkth), p->pkt); context.size += dumpSize; if (!SnortConfig::line_buffered_logging()) // FIXIT-L misnomer { fflush( (FILE*)context.dumpd); } } static void LogTcpdumpStream( LtdConfig*, Packet*, const char*, Event*) { // FIXIT-L log reassembled stream data with original packet? // (take original packet headers and append reassembled data) } static void TcpdumpInitLogFile(LtdConfig*, bool no_timestamp) { string file; string filename = F_NAME; context.lastTime = time(nullptr); context.log_cnt = 0; if(!no_timestamp) { char timestamp[16]; snprintf(timestamp, sizeof(timestamp), ".%lu", context.lastTime); filename += timestamp; } get_instance_file(file, filename.c_str()); int dlt = SFDAQ::get_base_protocol(); // convert these flavors of raw to the generic // for compatibility with libpcap 1.0.0 if ( dlt == DLT_IPV4 || dlt == DLT_IPV6 ) dlt = DLT_RAW; pcap_t* pcap; pcap = pcap_open_dead(dlt, SFDAQ::get_snap_len()); if ( !pcap ) FatalError("%s: can't get pcap context\n", S_NAME); context.dumpd = pcap ? pcap_dump_open(pcap, file.c_str()) : nullptr; if (context.dumpd == nullptr) { FatalError("%s: can't open %s: %s\n", S_NAME, file.c_str(), pcap_geterr(pcap)); } pcap_close(pcap); context.file = snort_strdup(file.c_str()); context.size = PCAP_FILE_HDR_SZ; } static void TcpdumpRollLogFile(LtdConfig* data) { time_t now = time(nullptr); /* don't roll over any sooner than resolution * of filename discriminator */ if ( now <= context.lastTime ) return; /* close the output file */ if ( context.dumpd != nullptr ) { pcap_dump_close(context.dumpd); context.dumpd = nullptr; context.size = 0; snort_free(context.file); context.file = nullptr; } /* Have to add stamps now to distinguish files */ TcpdumpInitLogFile(data, false); } static void SpoLogTcpdumpCleanup(LtdConfig*) { /* * if we haven't written any data, dump the output file so there aren't * fragments all over the disk */ if (context.file && !context.log_cnt) { int ret = unlink(context.file); if ( ret ) ErrorMessage("Could not remove tcpdump output file %s: %s\n", context.file, get_error(errno)); snort_free(context.file); context.file = nullptr; } } //------------------------------------------------------------------------- // logger stuff //------------------------------------------------------------------------- class PcapLogger : public Logger { public: PcapLogger(TcpdumpModule*); ~PcapLogger() override; void open() override; void close() override; void reset() override; void log(Packet*, const char* msg, Event*) override; private: LtdConfig* config; }; PcapLogger::PcapLogger(TcpdumpModule* m) { config = new LtdConfig; config->limit = m->limit; } PcapLogger::~PcapLogger() { delete config; } void PcapLogger::open() { TcpdumpInitLogFile(config, SnortConfig::output_no_timestamp()); } void PcapLogger::close() { SpoLogTcpdumpCleanup(nullptr); if ( context.dumpd ) { pcap_dump_close(context.dumpd); context.dumpd = nullptr; } if ( context.file ) snort_free(context.file); } void PcapLogger::log(Packet* p, const char* msg, Event* event) { if(!context.dumpd) open(); context.log_cnt++; if (p->packet_flags & PKT_REBUILT_STREAM) LogTcpdumpStream(config, p, msg, event); else LogTcpdumpSingle(config, p, msg, event); } void PcapLogger::reset() { if(!context.dumpd) open(); else TcpdumpRollLogFile(config); } //------------------------------------------------------------------------- // api stuff //------------------------------------------------------------------------- static Module* mod_ctor() { return new TcpdumpModule; } static void mod_dtor(Module* m) { delete m; } static Logger* tcpdump_ctor(SnortConfig*, Module* mod) { return new PcapLogger((TcpdumpModule*)mod); } static void tcpdump_dtor(Logger* p) { delete p; } static LogApi tcpdump_api { { PT_LOGGER, sizeof(LogApi), LOGAPI_VERSION, 0, API_RESERVED, API_OPTIONS, S_NAME, s_help, mod_ctor, mod_dtor }, OUTPUT_TYPE_FLAG__LOG, tcpdump_ctor, tcpdump_dtor }; #ifdef BUILDING_SO SO_PUBLIC const BaseApi* snort_plugins[] = #else const BaseApi* log_pcap[] = #endif { &tcpdump_api.base, nullptr };
#ifndef _SELECTION_HPP #define _SELECTION_HPP #include <iterator> #include <vector> #include "partition.hpp" namespace cotl { /** * Select the rank-th small element from the range of the container. * This function will perform a partition on the range of the container * around the rank-th small element. * @param first range * @param last range * @param rank order statistic (start by 0) * (must in the range of [0, std::distance(first, last)); otherwise, UB) * @param compare comparsion function object which * returns 0 if the first argument is equal to the second argument and * returns negative value if the first argument is less than the second argument. * signature: Cmp(const Type &a, const Type &b); * @return range of elements that are eqaul to the rank-th small element */ template <typename RandomAccessIterator, typename Compare> std::pair<RandomAccessIterator, RandomAccessIterator> Select(RandomAccessIterator first, RandomAccessIterator last, size_t rank, Compare compare) { if (std::distance(first, last) <= 1) return std::make_pair(first, last); typename std::iterator_traits<RandomAccessIterator>::difference_type i, n_div_five_floor; n_div_five_floor = std::distance(first, last) / 5; std::vector<typename std::iterator_traits<RandomAccessIterator>::value_type> medians; medians.reserve(n_div_five_floor + 1); RandomAccessIterator group_first, group_last = first; for (i = 0; i < n_div_five_floor; ++i) { group_first = group_last; group_last = group_first + 5; cotl::InsertionSort(group_first, group_last, [&compare] (const typename std::iterator_traits<RandomAccessIterator>::value_type &a, const typename std::iterator_traits<RandomAccessIterator>::value_type &b) { return compare(a, b) < 0; }); medians.push_back(*(group_first + 2)); } if (group_last != last) { cotl::InsertionSort(group_last, last, [&compare] (const typename std::iterator_traits<RandomAccessIterator>::value_type &a, const typename std::iterator_traits<RandomAccessIterator>::value_type &b) { return compare(a, b) < 0; }); medians.push_back(*(group_last + ((std::distance(group_last, last) - 1) >> 1))); } typename std::iterator_traits<RandomAccessIterator>::value_type &median_of_medians = *(Select(medians.begin(), medians.end(), (std::distance(medians.begin(), medians.end()) - 1) >> 1, compare).first); std::pair<RandomAccessIterator, RandomAccessIterator> pivot_interval = cotl::Partition(first, last, [&median_of_medians, &compare] (const typename std::iterator_traits<RandomAccessIterator>::value_type &a) { return compare(a, median_of_medians); }); if (rank < std::distance(first, pivot_interval.first)) return Select(first, pivot_interval.first, rank, compare); else if (rank >= std::distance(first, pivot_interval.second)) return Select(pivot_interval.second, last, rank - std::distance(first, pivot_interval.second), compare); else return pivot_interval; } /** * Select the rank-th small element from the range of the container. * This function will perform a partition on the range of the container * around the rank-th small element. * @param first range * @param last range * @param weighted_rank weighted order statistic (start by 0) * (must in the range of [0, sum of weight); otherwise, UB) * @param weight weight function object which returns the weight of the argument. * signature: size_t Weight(const Type &a); * @param compare comparsion function object which * returns 0 if the first argument is equal to the second argument and * returns negative value if the first argument is less than the second argument. * signature: Cmp(const Type &a, const Type &b); * @return range of elements that are eqaul to the rank-th small element */ template <typename RandomAccessIterator, typename Compare, typename Weight> std::pair<RandomAccessIterator, RandomAccessIterator> WeightedSelect(RandomAccessIterator first, RandomAccessIterator last, size_t weighted_rank, Weight weight, Compare compare) { if (std::distance(first, last) <= 1) return std::make_pair(first, last); typename std::iterator_traits<RandomAccessIterator>::difference_type i, n_div_five_floor; n_div_five_floor = std::distance(first, last) / 5; std::vector<typename std::iterator_traits<RandomAccessIterator>::value_type> medians; medians.reserve(n_div_five_floor + 1); RandomAccessIterator group_first, group_last = first; for (i = 0; i < n_div_five_floor; ++i) { group_first = group_last; group_last = group_first + 5; cotl::InsertionSort(group_first, group_last, [&compare] (const typename std::iterator_traits<RandomAccessIterator>::value_type &a, const typename std::iterator_traits<RandomAccessIterator>::value_type &b) { return compare(a, b) < 0; }); medians.push_back(*(group_first + 2)); } if (group_last != last) { cotl::InsertionSort(group_last, last, [&compare] (const typename std::iterator_traits<RandomAccessIterator>::value_type &a, const typename std::iterator_traits<RandomAccessIterator>::value_type &b) { return compare(a, b) < 0; }); medians.push_back(*(group_last + ((std::distance(group_last, last) - 1) >> 1))); } typename std::iterator_traits<RandomAccessIterator>::value_type &median_of_medians = *(Select(medians.begin(), medians.end(), (std::distance(medians.begin(), medians.end()) - 1) >> 1, compare).first); std::pair<RandomAccessIterator, RandomAccessIterator> pivot_interval = cotl::Partition(first, last, [&median_of_medians, &compare] (const typename std::iterator_traits<RandomAccessIterator>::value_type &a) { return compare(a, median_of_medians); }); size_t weight_sum = 0; for (RandomAccessIterator it = first; it != pivot_interval.first; ++it) { weight_sum += weight(*it); } if (weighted_rank < weight_sum) return WeightedSelect(first, pivot_interval.first, weighted_rank, weight, compare); for (RandomAccessIterator it = pivot_interval.first; it != pivot_interval.second; ++it) { weight_sum += weight(*it); } if (weighted_rank >= weight_sum) return WeightedSelect(pivot_interval.second, last, weighted_rank - weight_sum, weight, compare); return pivot_interval; } } #endif
; A314838: Coordination sequence Gal.4.52.3 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,5,9,14,18,23,27,32,37,41,46,50,55,59,64,69,73,78,82,87,91,96,101,105,110,114,119,123,128,133,137,142,146,151,155,160,165,169,174,178,183,187,192,197,201,206,210,215,219,224 mul $0,4 trn $0,1 sub $0,3 mov $1,7 add $1,$0 mov $0,$1 div $1,7 add $1,$0 sub $1,3
; A054604: a(n) = Sum_{d|5} phi(d)*n^(5/d). ; 0,5,40,255,1040,3145,7800,16835,32800,59085,100040,161095,248880,371345,537880,759435,1048640,1419925,1889640,2476175,3200080,4084185,5153720,6436435,7962720,9765725,11881480,14349015,17210480,20511265 mov $1,$0 pow $1,4 add $1,4 mul $1,$0
; A312484: Coordination sequence Gal.5.81.5 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,4,8,14,18,22,26,32,36,40,44,48,54,58,62,66,72,76,80,84,88,94,98,102,106,112,116,120,124,128,134,138,142,146,152,156,160,164,168,174,178,182,186,192,196,200,204,208,214,218 mov $2,$0 mul $0,2 add $0,3 mov $1,$0 add $0,2 sub $1,2 lpb $0,1 sub $0,7 trn $0,2 trn $1,2 add $1,4 lpe lpb $2,1 add $1,2 sub $2,1 lpe sub $1,3
LDA 9100 MOV L,A MVI H,90 MOV A,M STA 9101 HLT
#include <iostream> using namespace std; int main () { const int arrSize = 5; int a[arrSize] = {0}; int x,i,k; for (i = 0; i < arrSize; i++) { cout << "Please enter a number:"; cin >> x; int j; for (j = 0;a[j]<x && j<i;j++){}; //j е точно индекса в масива, на //който трябва да запишем x //a[j] > x сменя реда //ще избутаме всички елементи отдясно //на индекса j с един надясно for (k=i;k>j;k--) a[k]=a[k-1]; a[j] = x; } for (i = 0; i < arrSize; i++) cout << "a[" << i << "]=" << a[i] << endl; }
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .text .p2align 4, 0x90 .globl _p8_DecryptCFB_RIJ128pipe_AES_NI _p8_DecryptCFB_RIJ128pipe_AES_NI: push %ebp mov %esp, %ebp push %ebx push %esi push %edi sub $(144), %esp movl (32)(%ebp), %eax movdqu (%eax), %xmm4 movdqu %xmm4, (%esp) movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (28)(%ebp), %edx subl $(4), (24)(%ebp) jl .Lshort_inputgas_1 .Lblks_loopgas_1: lea (,%edx,4), %eax xor %ecx, %ecx .L__0000gas_1: movl (%esi,%ecx), %ebx movl %ebx, (16)(%esp,%ecx) add $(4), %ecx cmp %eax, %ecx jl .L__0000gas_1 movl (20)(%ebp), %ecx movdqa (%ecx), %xmm4 lea (%edx,%edx,2), %ebx movdqu (%esp), %xmm0 movdqu (%esp,%edx), %xmm1 movdqu (%esp,%edx,2), %xmm2 movdqu (%esp,%ebx), %xmm3 lea (16)(%ecx), %ebx pxor %xmm4, %xmm0 pxor %xmm4, %xmm1 pxor %xmm4, %xmm2 pxor %xmm4, %xmm3 movdqa (%ebx), %xmm4 add $(16), %ebx movl (16)(%ebp), %eax sub $(1), %eax .Lcipher_loopgas_1: aesenc %xmm4, %xmm0 aesenc %xmm4, %xmm1 aesenc %xmm4, %xmm2 aesenc %xmm4, %xmm3 movdqa (%ebx), %xmm4 add $(16), %ebx dec %eax jnz .Lcipher_loopgas_1 aesenclast %xmm4, %xmm0 aesenclast %xmm4, %xmm1 aesenclast %xmm4, %xmm2 aesenclast %xmm4, %xmm3 lea (%edx,%edx,2), %ebx movdqu (16)(%esp), %xmm4 movdqu (16)(%esp,%edx), %xmm5 movdqu (16)(%esp,%edx,2), %xmm6 movdqu (16)(%esp,%ebx), %xmm7 pxor %xmm4, %xmm0 movdqu %xmm0, (80)(%esp) pxor %xmm5, %xmm1 movdqu %xmm1, (80)(%esp,%edx) pxor %xmm6, %xmm2 movdqu %xmm2, (80)(%esp,%edx,2) pxor %xmm7, %xmm3 movdqu %xmm3, (80)(%esp,%ebx) lea (,%edx,4), %eax xor %ecx, %ecx .L__0001gas_1: movl (80)(%esp,%ecx), %ebx movl %ebx, (%edi,%ecx) add $(4), %ecx cmp %eax, %ecx jl .L__0001gas_1 movdqu (%esp,%eax), %xmm0 movdqu %xmm0, (%esp) add %eax, %esi add %eax, %edi subl $(4), (24)(%ebp) jge .Lblks_loopgas_1 .Lshort_inputgas_1: addl $(4), (24)(%ebp) jz .Lquitgas_1 lea (,%edx,2), %ebx lea (%edx,%edx,2), %ecx cmpl $(2), (24)(%ebp) cmovl %edx, %ebx cmovg %ecx, %ebx xor %ecx, %ecx .L__0002gas_1: movb (%esi,%ecx), %al movb %al, (16)(%esp,%ecx) add $(1), %ecx cmp %ebx, %ecx jl .L__0002gas_1 movl (20)(%ebp), %ecx movl (16)(%ebp), %eax lea (,%eax,4), %esi lea (-144)(%ecx,%esi,4), %esi xor %eax, %eax .Lsingle_blk_loopgas_1: movdqu (%esp,%eax), %xmm0 pxor (%ecx), %xmm0 cmpl $(12), (16)(%ebp) jl .Lkey_128_sgas_1 jz .Lkey_192_sgas_1 .Lkey_256_sgas_1: aesenc (-64)(%esi), %xmm0 aesenc (-48)(%esi), %xmm0 .Lkey_192_sgas_1: aesenc (-32)(%esi), %xmm0 aesenc (-16)(%esi), %xmm0 .Lkey_128_sgas_1: aesenc (%esi), %xmm0 aesenc (16)(%esi), %xmm0 aesenc (32)(%esi), %xmm0 aesenc (48)(%esi), %xmm0 aesenc (64)(%esi), %xmm0 aesenc (80)(%esi), %xmm0 aesenc (96)(%esi), %xmm0 aesenc (112)(%esi), %xmm0 aesenc (128)(%esi), %xmm0 aesenclast (144)(%esi), %xmm0 movdqu (16)(%esp,%eax), %xmm1 pxor %xmm1, %xmm0 movdqu %xmm0, (80)(%esp,%eax) add %edx, %eax decl (24)(%ebp) jnz .Lsingle_blk_loopgas_1 xor %ecx, %ecx .L__0003gas_1: movb (80)(%esp,%ecx), %al movb %al, (%edi,%ecx) add $(1), %ecx cmp %ebx, %ecx jl .L__0003gas_1 .Lquitgas_1: add $(144), %esp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p8_DecryptCFB32_RIJ128pipe_AES_NI _p8_DecryptCFB32_RIJ128pipe_AES_NI: push %ebp mov %esp, %ebp push %ebx push %esi push %edi sub $(144), %esp movl (32)(%ebp), %eax movdqu (%eax), %xmm4 movdqu %xmm4, (%esp) movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (28)(%ebp), %edx subl $(4), (24)(%ebp) jl .Lshort_inputgas_2 .Lblks_loopgas_2: lea (,%edx,4), %eax xor %ecx, %ecx .L__0004gas_2: movdqu (%esi,%ecx), %xmm0 movdqu %xmm0, (16)(%esp,%ecx) add $(16), %ecx cmp %eax, %ecx jl .L__0004gas_2 movl (20)(%ebp), %ecx movdqa (%ecx), %xmm4 lea (%edx,%edx,2), %ebx movdqu (%esp), %xmm0 movdqu (%esp,%edx), %xmm1 movdqu (%esp,%edx,2), %xmm2 movdqu (%esp,%ebx), %xmm3 lea (16)(%ecx), %ebx pxor %xmm4, %xmm0 pxor %xmm4, %xmm1 pxor %xmm4, %xmm2 pxor %xmm4, %xmm3 movdqa (%ebx), %xmm4 add $(16), %ebx movl (16)(%ebp), %eax sub $(1), %eax .Lcipher_loopgas_2: aesenc %xmm4, %xmm0 aesenc %xmm4, %xmm1 aesenc %xmm4, %xmm2 aesenc %xmm4, %xmm3 movdqa (%ebx), %xmm4 add $(16), %ebx dec %eax jnz .Lcipher_loopgas_2 aesenclast %xmm4, %xmm0 aesenclast %xmm4, %xmm1 aesenclast %xmm4, %xmm2 aesenclast %xmm4, %xmm3 lea (%edx,%edx,2), %ebx movdqu (16)(%esp), %xmm4 movdqu (16)(%esp,%edx), %xmm5 movdqu (16)(%esp,%edx,2), %xmm6 movdqu (16)(%esp,%ebx), %xmm7 pxor %xmm4, %xmm0 movdqu %xmm0, (80)(%esp) pxor %xmm5, %xmm1 movdqu %xmm1, (80)(%esp,%edx) pxor %xmm6, %xmm2 movdqu %xmm2, (80)(%esp,%edx,2) pxor %xmm7, %xmm3 movdqu %xmm3, (80)(%esp,%ebx) lea (,%edx,4), %eax xor %ecx, %ecx .L__0005gas_2: movdqu (80)(%esp,%ecx), %xmm0 movdqu %xmm0, (%edi,%ecx) add $(16), %ecx cmp %eax, %ecx jl .L__0005gas_2 movdqu (%esp,%eax), %xmm0 movdqu %xmm0, (%esp) add %eax, %esi add %eax, %edi subl $(4), (24)(%ebp) jge .Lblks_loopgas_2 .Lshort_inputgas_2: addl $(4), (24)(%ebp) jz .Lquitgas_2 lea (,%edx,2), %ebx lea (%edx,%edx,2), %ecx cmpl $(2), (24)(%ebp) cmovl %edx, %ebx cmovg %ecx, %ebx xor %ecx, %ecx .L__0006gas_2: movl (%esi,%ecx), %eax movl %eax, (16)(%esp,%ecx) add $(4), %ecx cmp %ebx, %ecx jl .L__0006gas_2 movl (20)(%ebp), %ecx movl (16)(%ebp), %eax lea (,%eax,4), %esi lea (-144)(%ecx,%esi,4), %esi xor %eax, %eax .Lsingle_blk_loopgas_2: movdqu (%esp,%eax), %xmm0 pxor (%ecx), %xmm0 cmpl $(12), (16)(%ebp) jl .Lkey_128_sgas_2 jz .Lkey_192_sgas_2 .Lkey_256_sgas_2: aesenc (-64)(%esi), %xmm0 aesenc (-48)(%esi), %xmm0 .Lkey_192_sgas_2: aesenc (-32)(%esi), %xmm0 aesenc (-16)(%esi), %xmm0 .Lkey_128_sgas_2: aesenc (%esi), %xmm0 aesenc (16)(%esi), %xmm0 aesenc (32)(%esi), %xmm0 aesenc (48)(%esi), %xmm0 aesenc (64)(%esi), %xmm0 aesenc (80)(%esi), %xmm0 aesenc (96)(%esi), %xmm0 aesenc (112)(%esi), %xmm0 aesenc (128)(%esi), %xmm0 aesenclast (144)(%esi), %xmm0 movdqu (16)(%esp,%eax), %xmm1 pxor %xmm1, %xmm0 movdqu %xmm0, (80)(%esp,%eax) add %edx, %eax decl (24)(%ebp) jnz .Lsingle_blk_loopgas_2 xor %ecx, %ecx .L__0007gas_2: movl (80)(%esp,%ecx), %eax movl %eax, (%edi,%ecx) add $(4), %ecx cmp %ebx, %ecx jl .L__0007gas_2 .Lquitgas_2: add $(144), %esp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p8_DecryptCFB128_RIJ128pipe_AES_NI _p8_DecryptCFB128_RIJ128pipe_AES_NI: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (20)(%ebp), %ecx movl (24)(%ebp), %edx movl (28)(%ebp), %eax movdqu (%eax), %xmm0 sub $(64), %edx jl .Lshort_inputgas_3 .Lblks_loopgas_3: movdqa (%ecx), %xmm7 lea (16)(%ecx), %ebx movdqu (%esi), %xmm1 movdqu (16)(%esi), %xmm2 movdqu (32)(%esi), %xmm3 pxor %xmm7, %xmm0 pxor %xmm7, %xmm1 pxor %xmm7, %xmm2 pxor %xmm7, %xmm3 movdqa (%ebx), %xmm7 add $(16), %ebx movl (16)(%ebp), %eax sub $(1), %eax .Lcipher_loopgas_3: aesenc %xmm7, %xmm0 aesenc %xmm7, %xmm1 aesenc %xmm7, %xmm2 aesenc %xmm7, %xmm3 movdqa (%ebx), %xmm7 add $(16), %ebx dec %eax jnz .Lcipher_loopgas_3 aesenclast %xmm7, %xmm0 movdqu (%esi), %xmm4 aesenclast %xmm7, %xmm1 movdqu (16)(%esi), %xmm5 aesenclast %xmm7, %xmm2 movdqu (32)(%esi), %xmm6 aesenclast %xmm7, %xmm3 movdqu (48)(%esi), %xmm7 add $(64), %esi pxor %xmm4, %xmm0 movdqu %xmm0, (%edi) pxor %xmm5, %xmm1 movdqu %xmm1, (16)(%edi) pxor %xmm6, %xmm2 movdqu %xmm2, (32)(%edi) pxor %xmm7, %xmm3 movdqu %xmm3, (48)(%edi) add $(64), %edi movdqa %xmm7, %xmm0 sub $(64), %edx jge .Lblks_loopgas_3 .Lshort_inputgas_3: add $(64), %edx jz .Lquitgas_3 movl (16)(%ebp), %eax lea (,%eax,4), %ebx lea (-144)(%ecx,%ebx,4), %ebx .Lsingle_blk_loopgas_3: pxor (%ecx), %xmm0 cmp $(12), %eax jl .Lkey_128_sgas_3 jz .Lkey_192_sgas_3 .Lkey_256_sgas_3: aesenc (-64)(%ebx), %xmm0 aesenc (-48)(%ebx), %xmm0 .Lkey_192_sgas_3: aesenc (-32)(%ebx), %xmm0 aesenc (-16)(%ebx), %xmm0 .Lkey_128_sgas_3: aesenc (%ebx), %xmm0 aesenc (16)(%ebx), %xmm0 aesenc (32)(%ebx), %xmm0 aesenc (48)(%ebx), %xmm0 aesenc (64)(%ebx), %xmm0 aesenc (80)(%ebx), %xmm0 aesenc (96)(%ebx), %xmm0 aesenc (112)(%ebx), %xmm0 aesenc (128)(%ebx), %xmm0 aesenclast (144)(%ebx), %xmm0 movdqu (%esi), %xmm1 add $(16), %esi pxor %xmm1, %xmm0 movdqu %xmm0, (%edi) add $(16), %edi movdqa %xmm1, %xmm0 sub $(16), %edx jnz .Lsingle_blk_loopgas_3 .Lquitgas_3: pop %edi pop %esi pop %ebx pop %ebp ret
; A119789: Fibonacci Logarithms used to get a triangular array. ; 0,0,0,0,0,0,1,1,1,2,2,2,2,3,4,3,3,3,4,5,6,4,4,4,5,6,7,8,5,5,5,6,7,8,9,10,6,6,6,7,8,9,10,11,12,7,7,7,8,9,10,11,12,13,14,8,8,8,9,10,11,12,13,14,15,16 lpb $0 mov $1,$0 add $2,1 sub $0,$2 trn $0,1 trn $1,3 add $1,$2 lpe trn $1,2
// Range v3 library // // Copyright Eric Niebler 2014 // // Use, modification and distribution is subject to 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) // // Project home: https://github.com/ericniebler/range-v3 //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <memory> #include <algorithm> #include <range/v3/core.hpp> #include <range/v3/algorithm/mismatch.hpp> #include "../simple_test.hpp" #include "../test_utils.hpp" #include "../test_iterators.hpp" template<typename Iter, typename Sent = Iter> void test_iter() { int ia[] = {0, 1, 2, 2, 0, 1, 2, 3}; constexpr unsigned sa = ranges::size(ia); int ib[] = {0, 1, 2, 3, 0, 1, 2, 3}; using Pair = std::pair<Iter, Iter>; CHECK(ranges::mismatch(Iter(ia), Sent(ia + sa), Iter(ib)) == Pair{Iter(ia+3),Iter(ib+3)}); CHECK(ranges::mismatch(Iter(ia),Sent(ia + sa),Iter(ib),Sent(ib + sa)) == Pair{Iter(ia+3),Iter(ib+3)}); CHECK(ranges::mismatch(Iter(ia),Sent(ia + sa),Iter(ib),Sent(ib + 2)) == Pair{Iter(ia+2),Iter(ib+2)}); CHECK(ranges::mismatch(Iter(ia),Sent(ia + sa),Iter(ib),std::equal_to<int>()) == Pair{Iter(ia+3),Iter(ib+3)}); CHECK(ranges::mismatch(Iter(ia),Sent(ia + sa),Iter(ib),Sent(ib + sa),std::equal_to<int>()) == Pair{Iter(ia+3),Iter(ib+3)}); CHECK(ranges::mismatch(Iter(ia), Sent(ia + sa), Iter(ib), Sent(ib + 2), std::equal_to<int>()) == Pair{Iter(ia+2),Iter(ib+2)}); } template<typename Iter, typename Sent = Iter> void test_range() { int ia[] = {0, 1, 2, 2, 0, 1, 2, 3}; constexpr unsigned sa = ranges::size(ia); int ib[] = {0, 1, 2, 3, 0, 1, 2, 3}; using Pair = std::pair<Iter, Iter>; auto rng1 = ranges::make_iterator_range(Iter(ia), Sent(ia + sa)); CHECK(ranges::mismatch(rng1, Iter(ib)) == Pair{Iter(ia+3),Iter(ib+3)}); auto r1 = ranges::mismatch(std::move(rng1), Iter(ib)); CHECK(r1.first.get_unsafe() == Iter(ia+3)); CHECK(r1.second == Iter(ib+3)); auto rng2 = ranges::make_iterator_range(Iter(ia),Sent(ia + sa)); auto rng3 = ranges::make_iterator_range(Iter(ib),Sent(ib + sa)); CHECK(ranges::mismatch(rng2,rng3) == Pair{Iter(ia+3),Iter(ib+3)}); auto r2 = ranges::mismatch(std::move(rng2), std::move(rng3)); CHECK(r2.first.get_unsafe() == Iter(ia+3)); CHECK(r2.second.get_unsafe() == Iter(ib+3)); auto r3 = ranges::mismatch(rng2, std::move(rng3)); CHECK(r3.first == Iter(ia+3)); CHECK(r3.second.get_unsafe() == Iter(ib+3)); auto r4 = ranges::mismatch(std::move(rng2), rng3); CHECK(r4.first.get_unsafe() == Iter(ia+3)); CHECK(r4.second == Iter(ib+3)); auto rng4 = ranges::make_iterator_range(Iter(ia),Sent(ia + sa)); auto rng5 = ranges::make_iterator_range(Iter(ib),Sent(ib + 2)); CHECK(ranges::mismatch(rng4,rng5) == Pair{Iter(ia+2),Iter(ib+2)}); auto rng6 = ranges::make_iterator_range(Iter(ia),Sent(ia + sa)); CHECK(ranges::mismatch(rng6,Iter(ib),std::equal_to<int>()) == Pair{Iter(ia+3),Iter(ib+3)}); auto rng7 = ranges::make_iterator_range(Iter(ia),Sent(ia + sa)); auto rng8 = ranges::make_iterator_range(Iter(ib),Sent(ib + sa)); CHECK(ranges::mismatch(rng7,rng8,std::equal_to<int>()) == Pair{Iter(ia+3),Iter(ib+3)}); auto rng9 = ranges::make_iterator_range(Iter(ia), Sent(ia + sa)); auto rng10 = ranges::make_iterator_range(Iter(ib), Sent(ib + 2)); CHECK(ranges::mismatch(rng9,rng10,std::equal_to<int>()) == Pair{Iter(ia+2),Iter(ib+2)}); } struct S { int i; }; int main() { test_iter<input_iterator<const int*>>(); test_iter<forward_iterator<const int*>>(); test_iter<bidirectional_iterator<const int*>>(); test_iter<random_access_iterator<const int*>>(); test_iter<const int*>(); test_iter<input_iterator<const int*>, sentinel<const int*>>(); test_iter<forward_iterator<const int*>, sentinel<const int*>>(); test_iter<bidirectional_iterator<const int*>, sentinel<const int*>>(); test_iter<random_access_iterator<const int*>, sentinel<const int*>>(); test_range<input_iterator<const int*>>(); test_range<forward_iterator<const int*>>(); test_range<bidirectional_iterator<const int*>>(); test_range<random_access_iterator<const int*>>(); test_range<const int*>(); test_range<input_iterator<const int*>, sentinel<const int*>>(); test_range<forward_iterator<const int*>, sentinel<const int*>>(); test_range<bidirectional_iterator<const int*>, sentinel<const int*>>(); test_range<random_access_iterator<const int*>, sentinel<const int*>>(); // Works with projections? S s1[] = {S{1},S{2},S{3},S{4},S{-4},S{5},S{6},S{40},S{7},S{8},S{9}}; int const i1[] = {1,2,3,4,5,6,7,8,9}; std::pair<S const *, int const *> ps1 = ranges::mismatch(s1, i1, std::equal_to<int>(), &S::i); CHECK(ps1.first->i == -4); CHECK(*ps1.second == 5); S s2[] = {S{1},S{2},S{3},S{4},S{5},S{6},S{40},S{7},S{8},S{9}}; std::pair<S const *, S const *> ps2 = ranges::mismatch(s1, s2, std::equal_to<int>(), &S::i, &S::i); CHECK(ps2.first->i == -4); CHECK(ps2.second->i == 5); return test_result(); }
; Example 1.2: ; Prints a 16x16 sprite into the visual display JMP boot vslDisplay EQU 0x300 sprite: DB "\xFF\xFF\xFF\xFF\xFF\xC4\xC4\xC4" DB "\xC4\xC4\xFF\xFF\xFF\xFF\xFF\xFF" DB "\xFF\xFF\xFF\xFF\xC4\xC4\xC4\xC4" DB "\xC4\xC4\xC4\xC4\xC4\xFF\xFF\xFF" DB "\xFF\xFF\xFF\xFF\x8C\x8C\x8C\xF4" DB "\xF4\x8C\xF4\xFF\xFF\xFF\xFF\xFF" DB "\xFF\xFF\xFF\x8C\xF4\x8C\xF4\xF4" DB "\xF4\x8C\xF4\xF4\xF4\xFF\xFF\xFF" DB "\xFF\xFF\xFF\x8C\xF4\x8C\x8C\xF4" DB "\xF4\xF4\x8C\xF4\xF4\xF4\xFF\xFF" DB "\xFF\xFF\xFF\x8C\x8C\xF4\xF4\xF4" DB "\xF4\x8C\x8C\x8C\x8C\xFF\xFF\xFF" DB "\xFF\xFF\xFF\xFF\xFF\xF4\xF4\xF4" DB "\xF4\xF4\xF4\xF4\xFF\xFF\xFF\xFF" DB "\xFF\xFF\xFF\xFF\x8C\x8C\xC4\x8C" DB "\x8C\x8C\xFF\xFF\xFF\xFF\xFF\xFF" DB "\xFF\xFF\xFF\x8C\x8C\x8C\xC4\x8C" DB "\x8C\xC4\x8C\x8C\x8C\xFF\xFF\xFF" DB "\xFF\xFF\x8C\x8C\x8C\x8C\xC4\xC4" DB "\xC4\xC4\x8C\x8C\x8C\x8C\xFF\xFF" DB "\xFF\xFF\xF4\xF4\x8C\xC4\xF4\xC4" DB "\xC4\xF4\xC4\x8C\xF4\xF4\xFF\xFF" DB "\xFF\xFF\xF4\xF4\xF4\xC4\xC4\xC4" DB "\xC4\xC4\xC4\xF4\xF4\xF4\xFF\xFF" DB "\xFF\xFF\xF4\xF4\xC4\xC4\xC4\xC4" DB "\xC4\xC4\xC4\xC4\xF4\xF4\xFF\xFF" DB "\xFF\xFF\xFF\xFF\xC4\xC4\xC4\xFF" DB "\xFF\xC4\xC4\xC4\xFF\xFF\xFF\xFF" DB "\xFF\xFF\xFF\x8C\x8C\x8C\xFF\xFF" DB "\xFF\xFF\x8C\x8C\x8C\xFF\xFF\xFF" DB "\xFF\xFF\x8C\x8C\x8C\x8C\xFF\xFF" DB "\xFF\xFF\x8C\x8C\x8C\x8C\xFF\xFF" boot: MOV C, sprite ; C points to the sprite MOV D, vslDisplay ; D points to the fb .loop: MOVB AL, [C] ; Print all the pixels MOVB [D], AL INC C INC D CMP D, 0x400 JNZ .loop HLT
extern scanf extern printf section .data format db "%s",0 napis db "Wprowadz ciag znakow (bez spacji): ",0 licznik dd 0 format2 db "Ciag znakow zawiera %d liter 'a'.",10,0 section .bss tekst resb 500 section .text global main main: xor rax, rax mov rdi, napis call printf xor rax, rax mov rdi, format mov rsi, tekst call scanf mov ebx, 0 mov r8d, 0 _petla: cmp byte [tekst+ebx-1], "a" jne _dalej inc r8d _dalej: inc ebx cmp ebx, 500 jb _petla _koniec: mov [licznik], r8d xor rax, rax mov rdi, format2 mov rsi, [licznik] call printf mov rax, 1 mov rbx, 0 int 80h
// check atomic bneq r1 r0 .child lbi r19 1 slbi r19 0x0100 // r19 is at start pc lbi r21 1 slbi r21 0x0400 // r21 is pointing to heap addi r25 r21 2 // r25 = 0x10402 st r25 r0 0 // i: mem[0x10402] = 0 addi r20 r21 1 nt r26 r19 r21 nt r26 r19 r20 slp r0 addi r0 r0 0 ld r22 r21 0 addi r0 r0 0 beq r22 r0 -4 ld r23 r20 0 addi r0 r0 0 beq r23 r0 -7 st r0 r22 0 st r0 r23 1 kill r1 .child lbi r25 1 slbi r25 0x0402 addi r6 r0 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 addi r6 r6 1024 //16 * 1024 = 2**14 = 0x400 addi r26 r0 0 .loop adda r26 r26 r1 ld r10 r25 0 add r10 r10 r1 st r25 r10 0 addi r6 r6 -1 // Increment r6 by 1 bneq r6 r0 .loop st r4 r26 0 wk r0 kill r1 // return
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quic/core/quic_crypto_stream.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "quic/core/crypto/crypto_handshake.h" #include "quic/core/crypto/crypto_protocol.h" #include "quic/core/crypto/null_encrypter.h" #include "quic/core/quic_utils.h" #include "quic/platform/api/quic_socket_address.h" #include "quic/platform/api/quic_test.h" #include "quic/test_tools/crypto_test_utils.h" #include "quic/test_tools/quic_stream_peer.h" #include "quic/test_tools/quic_test_utils.h" using testing::_; using testing::InSequence; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::Return; namespace quic { namespace test { namespace { class MockQuicCryptoStream : public QuicCryptoStream, public QuicCryptoHandshaker { public: explicit MockQuicCryptoStream(QuicSession* session) : QuicCryptoStream(session), QuicCryptoHandshaker(this, session), params_(new QuicCryptoNegotiatedParameters) {} MockQuicCryptoStream(const MockQuicCryptoStream&) = delete; MockQuicCryptoStream& operator=(const MockQuicCryptoStream&) = delete; void OnHandshakeMessage(const CryptoHandshakeMessage& message) override { messages_.push_back(message); } std::vector<CryptoHandshakeMessage>* messages() { return &messages_; } ssl_early_data_reason_t EarlyDataReason() const override { return ssl_early_data_unknown; } bool encryption_established() const override { return false; } bool one_rtt_keys_available() const override { return false; } const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override { return *params_; } CryptoMessageParser* crypto_message_parser() override { return QuicCryptoHandshaker::crypto_message_parser(); } void OnPacketDecrypted(EncryptionLevel /*level*/) override {} void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnHandshakeDoneReceived() override {} void OnNewTokenReceived(absl::string_view /*token*/) override {} std::string GetAddressToken( const CachedNetworkParameters* /*cached_network_parameters*/) const override { return ""; } bool ValidateAddressToken(absl::string_view /*token*/) const override { return true; } const CachedNetworkParameters* PreviousCachedNetworkParams() const override { return nullptr; } void SetPreviousCachedNetworkParams( CachedNetworkParameters /*cached_network_params*/) override {} HandshakeState GetHandshakeState() const override { return HANDSHAKE_START; } void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> /*application_state*/) override {} std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { return nullptr; } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return nullptr; } bool ExportKeyingMaterial(absl::string_view /*label*/, absl::string_view /*context*/, size_t /*result_len*/, std::string* /*result*/) override { return false; } SSL* GetSsl() const override { return nullptr; } private: quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; std::vector<CryptoHandshakeMessage> messages_; }; class QuicCryptoStreamTest : public QuicTest { public: QuicCryptoStreamTest() : connection_(new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_CLIENT)), session_(connection_, /*create_mock_crypto_stream=*/false) { stream_ = new MockQuicCryptoStream(&session_); session_.SetCryptoStream(stream_); session_.Initialize(); message_.set_tag(kSHLO); message_.SetStringPiece(1, "abc"); message_.SetStringPiece(2, "def"); ConstructHandshakeMessage(); } QuicCryptoStreamTest(const QuicCryptoStreamTest&) = delete; QuicCryptoStreamTest& operator=(const QuicCryptoStreamTest&) = delete; void ConstructHandshakeMessage() { CryptoFramer framer; message_data_ = framer.ConstructHandshakeMessage(message_); } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; MockQuicSpdySession session_; MockQuicCryptoStream* stream_; CryptoHandshakeMessage message_; std::unique_ptr<QuicData> message_data_; }; TEST_F(QuicCryptoStreamTest, NotInitiallyConected) { EXPECT_FALSE(stream_->encryption_established()); EXPECT_FALSE(stream_->one_rtt_keys_available()); } TEST_F(QuicCryptoStreamTest, ProcessRawData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { stream_->OnStreamFrame(QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), /*fin=*/false, /*offset=*/0, message_data_->AsStringPiece())); } else { stream_->OnCryptoFrame(QuicCryptoFrame(ENCRYPTION_INITIAL, /*offset*/ 0, message_data_->AsStringPiece())); } ASSERT_EQ(1u, stream_->messages()->size()); const CryptoHandshakeMessage& message = (*stream_->messages())[0]; EXPECT_EQ(kSHLO, message.tag()); EXPECT_EQ(2u, message.tag_value_map().size()); EXPECT_EQ("abc", crypto_test_utils::GetValueForTag(message, 1)); EXPECT_EQ("def", crypto_test_utils::GetValueForTag(message, 2)); } TEST_F(QuicCryptoStreamTest, ProcessBadData) { std::string bad(message_data_->data(), message_data_->length()); const int kFirstTagIndex = sizeof(uint32_t) + // message tag sizeof(uint16_t) + // number of tag-value pairs sizeof(uint16_t); // padding EXPECT_EQ(1, bad[kFirstTagIndex]); bad[kFirstTagIndex] = 0x7F; // out of order tag EXPECT_CALL(*connection_, CloseConnection(QUIC_CRYPTO_TAGS_OUT_OF_ORDER, testing::_, testing::_)); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { stream_->OnStreamFrame(QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), /*fin=*/false, /*offset=*/0, bad)); } else { stream_->OnCryptoFrame( QuicCryptoFrame(ENCRYPTION_INITIAL, /*offset*/ 0, bad)); } } TEST_F(QuicCryptoStreamTest, NoConnectionLevelFlowControl) { EXPECT_FALSE( QuicStreamPeer::StreamContributesToConnectionFlowControl(stream_)); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); // Send [1350, 2700) in ENCRYPTION_ZERO_RTT. connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); // Lost [0, 1000). stream_->OnStreamFrameLost(0, 1000, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); // Lost [1200, 2000). stream_->OnStreamFrameLost(1200, 800, false); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1000, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); // Verify [1200, 2000) are sent in [1200, 1350) and [1350, 2000) because of // they are in different encryption levels. EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 150, 1200, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->OnCanWrite(); EXPECT_FALSE(stream_->HasPendingRetransmission()); // Verify connection's encryption level has restored. EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoDataInCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); InSequence s; // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); // Send [1350, 2700) in ENCRYPTION_ZERO_RTT. std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); // Lost [0, 1000). QuicCryptoFrame lost_frame(ENCRYPTION_INITIAL, 0, 1000); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); // Lost [1200, 2000). lost_frame = QuicCryptoFrame(ENCRYPTION_INITIAL, 1200, 150); stream_->OnCryptoFrameLost(&lost_frame); lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); // Verify [1200, 2000) are sent in [1200, 1350) and [1350, 2000) because of // they are in different encryption levels. EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 150, 1200)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 650, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); // Verify connection's encryption level has restored. EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); } // Regression test for handling the missing ENCRYPTION_HANDSHAKE in // quic_crypto_stream.cc. This test is essentially the same as // RetransmitCryptoDataInCryptoFrames, except it uses ENCRYPTION_HANDSHAKE in // place of ENCRYPTION_ZERO_RTT. TEST_F(QuicCryptoStreamTest, RetransmitEncryptionHandshakeLevelCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); InSequence s; // Send [0, 1000) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1000, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); // Send [1000, 2000) in ENCRYPTION_HANDSHAKE. std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_HANDSHAKE, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_EQ(ENCRYPTION_HANDSHAKE, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_HANDSHAKE, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_HANDSHAKE, data); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); // Lost [1000, 1200). QuicCryptoFrame lost_frame(ENCRYPTION_HANDSHAKE, 0, 200); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); // Verify [1000, 1200) is sent. EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_HANDSHAKE, 200, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); } TEST_F(QuicCryptoStreamTest, NeuterUnencryptedStreamData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); // Send [1350, 2700) in ENCRYPTION_ZERO_RTT. connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); // Lost [0, 1350). stream_->OnStreamFrameLost(0, 1350, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); // Neuters [0, 1350). stream_->NeuterUnencryptedStreamData(); EXPECT_FALSE(stream_->HasPendingRetransmission()); // Lost [0, 1350) again. stream_->OnStreamFrameLost(0, 1350, false); EXPECT_FALSE(stream_->HasPendingRetransmission()); // Lost [1350, 2000). stream_->OnStreamFrameLost(1350, 650, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_TRUE(stream_->HasPendingRetransmission()); } TEST_F(QuicCryptoStreamTest, NeuterUnencryptedCryptoData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); // Send [1350, 2700) in ENCRYPTION_ZERO_RTT. connection_->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); // Lost [0, 1350). QuicCryptoFrame lost_frame(ENCRYPTION_INITIAL, 0, 1350); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); // Neuters [0, 1350). stream_->NeuterUnencryptedStreamData(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); // Lost [0, 1350) again. stream_->OnCryptoFrameLost(&lost_frame); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); // Lost [1350, 2000), which starts at offset 0 at the ENCRYPTION_ZERO_RTT // level. lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); } TEST_F(QuicCryptoStreamTest, RetransmitStreamData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); // Send [1350, 2700) in ENCRYPTION_ZERO_RTT. connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); // Ack [2000, 2500). QuicByteCount newly_acked_length = 0; stream_->OnStreamFrameAcked(2000, 500, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length); EXPECT_EQ(500u, newly_acked_length); // Force crypto stream to send [1350, 2700) and only [1350, 1500) is consumed. EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_.ConsumeData( QuicUtils::GetCryptoStreamId(connection_->transport_version()), 150, 1350, NO_FIN, HANDSHAKE_RETRANSMISSION, absl::nullopt); })); EXPECT_FALSE(stream_->RetransmitStreamData(1350, 1350, false, HANDSHAKE_RETRANSMISSION)); // Verify connection's encryption level has restored. EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); // Force session to send [1350, 1500) again and all data is consumed. EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 200, 2500, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_TRUE(stream_->RetransmitStreamData(1350, 1350, false, HANDSHAKE_RETRANSMISSION)); // Verify connection's encryption level has restored. EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)).Times(0); // Force to send an empty frame. EXPECT_TRUE( stream_->RetransmitStreamData(0, 0, false, HANDSHAKE_RETRANSMISSION)); } TEST_F(QuicCryptoStreamTest, RetransmitStreamDataWithCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); // Send [1350, 2700) in ENCRYPTION_ZERO_RTT. std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); // Ack [2000, 2500). QuicCryptoFrame acked_frame(ENCRYPTION_ZERO_RTT, 650, 500); EXPECT_TRUE( stream_->OnCryptoFrameAcked(acked_frame, QuicTime::Delta::Zero())); // Retransmit only [1350, 1500). EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 150, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); QuicCryptoFrame frame_to_retransmit(ENCRYPTION_ZERO_RTT, 0, 150); stream_->RetransmitData(&frame_to_retransmit, HANDSHAKE_RETRANSMISSION); // Verify connection's encryption level has restored. EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); // Retransmit [1350, 2700) again and all data is sent. EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 650, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 200, 1150)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); frame_to_retransmit = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 1350); stream_->RetransmitData(&frame_to_retransmit, HANDSHAKE_RETRANSMISSION); // Verify connection's encryption level has restored. EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); // Force to send an empty frame. QuicCryptoFrame empty_frame(ENCRYPTION_FORWARD_SECURE, 0, 0); stream_->RetransmitData(&empty_frame, HANDSHAKE_RETRANSMISSION); } // Regression test for b/115926584. TEST_F(QuicCryptoStreamTest, HasUnackedCryptoData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(testing::Return(QuicConsumedData(0, false))); stream_->WriteOrBufferData(data, false, nullptr); EXPECT_FALSE(stream_->IsWaitingForAcks()); // Although there is no outstanding data, verify session has pending crypto // data. EXPECT_TRUE(session_.HasUnackedCryptoData()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->OnCanWrite(); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_.HasUnackedCryptoData()); } TEST_F(QuicCryptoStreamTest, HasUnackedCryptoDataWithCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_.HasUnackedCryptoData()); } // Regression test for bugfix of GetPacketHeaderSize. TEST_F(QuicCryptoStreamTest, CryptoMessageFramingOverhead) { for (const ParsedQuicVersion& version : AllSupportedVersionsWithQuicCrypto()) { SCOPED_TRACE(version); QuicByteCount expected_overhead = 48; if (version.HasIetfInvariantHeader()) { expected_overhead += 4; } if (version.HasLongHeaderLengths()) { expected_overhead += 3; } if (version.HasLengthPrefixedConnectionIds()) { expected_overhead += 1; } EXPECT_EQ(expected_overhead, QuicCryptoStream::CryptoMessageFramingOverhead( version.transport_version, TestConnectionId())); } } TEST_F(QuicCryptoStreamTest, WriteBufferedCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); InSequence s; // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); // Only consumed 1000 bytes. EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Return(1000)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); // Send [1350, 2700) in ENCRYPTION_ZERO_RTT and verify no write is attempted // because there is buffered data. EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); connection_->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 350, 1000)) .WillOnce(Return(350)); // Partial write of ENCRYPTION_ZERO_RTT data. EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Return(1000)); stream_->WriteBufferedCryptoFrames(); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 350, 1000)) .WillOnce(Return(350)); stream_->WriteBufferedCryptoFrames(); EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); } TEST_F(QuicCryptoStreamTest, LimitBufferedCryptoData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); std::string large_frame(2 * GetQuicFlag(FLAGS_quic_max_buffered_crypto_bytes), 'a'); // Set offset to 1 so that we guarantee the data gets buffered instead of // immediately processed. QuicStreamOffset offset = 1; stream_->OnCryptoFrame( QuicCryptoFrame(ENCRYPTION_INITIAL, offset, large_frame)); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoFramesAndPartialWrite) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); InSequence s; // Send [0, 1350) in ENCRYPTION_INITIAL. EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); // Lost [0, 1000). QuicCryptoFrame lost_frame(ENCRYPTION_INITIAL, 0, 1000); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); // Simulate connection is constrained by amplification restriction. EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Return(0)); stream_->WritePendingCryptoRetransmission(); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); // Connection gets unblocked. EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); } // Regression test for b/203199510 TEST_F(QuicCryptoStreamTest, EmptyCryptoFrame) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); QuicCryptoFrame empty_crypto_frame(ENCRYPTION_INITIAL, 0, nullptr, 0); stream_->OnCryptoFrame(empty_crypto_frame); } } // namespace } // namespace test } // namespace quic
; A313722: Coordination sequence Gal.6.248.4 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,5,10,15,20,24,30,34,39,44,49,54,59,64,69,74,78,84,88,93,98,103,108,113,118,123,128,132,138,142,147,152,157,162,167,172,177,182,186,192,196,201,206,211,216,221,226,231,236,240 mov $5,$0 mul $0,4 mov $4,$0 sub $0,1 div $0,11 add $0,1 mov $2,$4 mul $2,3 div $2,22 add $2,$0 mov $1,$2 mov $3,$5 mul $3,4 add $1,$3 mov $0,$1
extern _levels extern _tileMapX extern _xPos extern _yPos extern clearAttr extern displayPixelTile extern displayTile extern displayTile extern setTileAttr public _initItems public checkItemCollision public displayItems public displayPixelItems public removeItem public setCurrentItemTable include "defs.inc" defc ITEM_WIDTH=0x08 defc ITEM_HEIGHT=0x08 ; ; Flag bits: ; +---------------+ ; |7|6|5|4|3|2|1|0| ; +---------------+ ; | | | | | | | | ; | | | | | | | +-- Visible ; | | | | | | +---- Unused ; | | | | | +------ Unused ; | | | | +-------- Unused ; | | | +---------- Unused ; | | +------------ Unused ; | +-------------- Unused ; +---------------- End of table ; section CODE_2 ; ; Entry: ; hl - Pointer to the item table ; de - Pointer to the item list ; a - Tile ID of item being initialized ; ; This routine scans each level from top right to bottom left ; building up a table of items for each level. These tables ; are then used by animation routines and collision routines. ; defvars 0 ; Define the stack variables used { levelX ds.b 1 levelY ds.b 1 tileX ds.b 1 tileY ds.b 1 itemCount ds.b 1 SIZEOF_stackVars } _initItems: push af push bc push hl push ix push iy ; ; Save parameters passed in registers ; ld (itemID+1), a ld (currentItemTable), hl ; ; Build a stack frame for our variables ; ld (tempSP+1), sp ld ix, -SIZEOF_stackVars add ix, sp ld sp, ix ; ; Initialize memory variables ; ld (ix+levelY), MAX_LEVEL_Y ld (ix+itemCount), 0 ld hl, _levels levelYLoop: ld (ix+levelX), MAX_LEVEL_X levelXLoop: push hl ld hl, (currentItemTable) ld (hl), e inc hl ld (hl), d inc hl ld (currentItemTable), hl pop hl push hl ; Save level pointer ld (ix+tileY), 3 ld c, LEVEL_HEIGHT tileYLoop: ld (ix+tileX), 0 ld b, SCREEN_WIDTH tileXLoop: ld a, (hl) ; Get tile ID itemID: cp -1 call z, addItem inc hl inc (ix+tileX) djnz tileXLoop ; Next row in the tilemap push bc ld bc, SCREEN_WIDTH*MAX_LEVEL_X-SCREEN_WIDTH add hl, bc pop bc inc (ix+tileY) dec c jr nz, tileYLoop pop hl ; Restore level pointer ; ; Move the current level pointer to the next level to the right ; ld bc, SCREEN_WIDTH add hl, bc ; Flags, bit 7, end of list ld a, 0x80 ld (de), a inc de ; ; Decrement X counter and loop if not zero ; dec (ix+levelX) jr nz, levelXLoop ; ; Move the current level pointer to the next level down ; ld bc, -SCREEN_WIDTH*MAX_LEVEL_X add hl, bc ld bc, SCREEN_WIDTH*MAX_LEVEL_X*LEVEL_HEIGHT add hl, bc ; ; Decrement Y counter and loop if not zero ; dec (ix+levelY) jr nz, levelYLoop ; ; Restore the stack frame ; tempSP: ld sp, -1 pop iy pop ix pop hl pop bc pop af ret ; ; Add a coin to the coin table ; addItem: ; Flags, Bit0 = visible ld a, 1 ld (de), a inc de ; X screen position ld a, (ix+tileX) rlca ; x2 rlca ; x4 rlca ; x8 and %11111000 ld (de), a inc de ; Y screen position ld a, (ix+tileY) rlca ; x2 rlca ; x4 rlca ; x8 and %11111000 ld (de), a inc de ; Animation frame ld a, (ix+itemCount) inc (ix+itemCount) ld (de), a inc de ret ; ; Calculate the value of the current item table based ; on the values of tileMapX and tileMapY and save it ; to the memory location pointed to by 'hl'. ; ; Entry: ; hl - Pointer to current item table variable ; de - Pointer to item tables ; setCurrentItemTable: ld (currItemTab+2), hl ld hl, (_tileMapX) ; Get tileMapX & tileMapY ld a, h ax MAX_LEVEL_X*SIZEOF_ptr ld h, a ld a, l ax SIZEOF_ptr add h ld l, a ld h, 0 add hl, de ld e, (hl) inc hl ld d, (hl) currItemTab: ld (-1), de ret ; ; Display the visible items pointed to by hl. Typically ; called when the level changes to display the items ; which have not yet been collected or to display items ; in their new position if they are moving. ; ; Entry: ; hl - Pointer to item table ; a - Tile ID of item ; displayItems: ld d, a ; Save tile ID nextItem2: ld a, (hl) ; Flags or a ret m jr z, notVisible2 inc hl ld c, (hl) inc hl ld b, (hl) inc hl pixelToChar b, c inc hl ; Skip animation frame ld a, d ; Tile ID call displayTile ; Display tile call setTileAttr jr nextItem2 notVisible2: ld a, SIZEOF_item addhl jr nextItem2 ; ; Display the visible pixel aligned items pointed to by hl. ; ; Entry: ; hl - Pointer to item table ; a - Tile ID ; displayPixelItems: ld d, a ; Save tile ID nextItem5: ld a, (hl) ; Flags or a ret m jr z, notVisible5 inc hl ld c, (hl) inc hl ld b, (hl) inc hl inc hl ; Skip animation frame ld a, d ; Tile ID call displayPixelTile ; Display tile jr nextItem5 notVisible5: ld a, SIZEOF_item addhl jr nextItem5 ; ; Check if the player has collided with an item. And if so, ; remove the item and attrinute from the level and call ; the user provided sub-routine to update socres, etc. ; ; Entry: ; hl - Pointer to current item table ; de - Pointer to subroutine to call when collision is detected ; checkItemCollision: ld (itemCollision+1), de nextItem: ld a, (hl) or a ret m jr z, notVisible3 push hl inc hl ; ; Collision check here ; ld a, (hl) ; X byte position add 2 ; Left side pixel offset (indented a little) ld b, a add ITEM_WIDTH-5 ; Right side pixel offset (pulled in a little) ld c, a ld a, (_xPos) ; Player left side pixel position inc a cp c ; Compare with coin right side jr nc, noCollision ; 'nc' if 'c' <= 'a' add PLAYER_WIDTH-4 ; Get right side pixel position cp b ; Compare with coin left side jr c, noCollision ; 'c' if 'b' > 'a' inc hl ld a, (hl) ; Y byte position add 2 ; Top pixel offset pulled in a little ld b, a add ITEM_HEIGHT-5 ; Bottom pixel offset, pushed up a little ld c, a ld a, (_yPos) cp c ; Compare with bottom jr nc, noCollision ; 'nc' if 'c' <= 'a' add PLAYER_HEIGHT-1 ; Player bottom pixel position cp b ; Compare with top jr c, noCollision ; 'c' if 'b' > 'a' ld b, (hl) ; Y position srl b srl b srl b dec hl ; Back to the flags ld c, (hl) ; X position srl c srl c srl c dec hl ; hl points to item flags ; ; User provided function to update score, etc. ; itemCollision: call -1 noCollision: pop hl notVisible3: ld a, SIZEOF_item addhl jp nextItem ; ; Remove an item from the screen and change ; it's flags so that it is no longer visible. ; ; Entry: ; hl - Pointer to items flags ; b - Screen y character position ; c - screen x character position ; removeItem: ld (hl), 0 ; Zero flags and save in item table call clearAttr ; Remove the item and attribute ld a, ID_BLANK call displayTile ret section BSS_2 currentItemTable: ds 2
Total: 5.86s ROUTINE ======================== main.(*Graph).EdgeCount 10ms 10ms (flat, cum) 0.17% of Total . . 10cb150: MOVQ 0x8(SP), AX ;graph.go:310 . . 10cb155: MOVQ 0x20(AX), CX . . 10cb159: MOVQ 0x18(AX), AX . . 10cb15d: XORL DX, DX . . 10cb15f: XORL BX, BX . . 10cb161: JMP 0x10cb176 . . 10cb163: LEAQ 0x1(DX), SI . . 10cb167: LEAQ 0(DX)(DX*2), DI ;graph.go:311 . . 10cb16b: MOVQ 0x8(AX)(DI*8), DI 10ms 10ms 10cb170: ADDQ DI, BX ;main.(*Graph).EdgeCount graph.go:311 . . 10cb173: MOVQ SI, DX ;graph.go:310 . . 10cb176: CMPQ CX, DX . . 10cb179: JL 0x10cb163 . . 10cb17b: MOVQ BX, AX ;graph.go:314 . . 10cb17e: SHRQ $0x3f, BX . . 10cb182: ADDQ BX, AX . . 10cb185: SARQ $0x1, AX . . 10cb188: MOVQ AX, 0x10(SP) . . 10cb18d: RET . . 10cb18e: INT $0x3 ROUTINE ======================== main.(*Graph).buildAdjList 500ms 1.87s (flat, cum) 31.91% of Total . . 10ca460: MOVQ GS:0x30, CX ;graph.go:102 . . 10ca469: LEAQ -0x60(SP), AX . . 10ca46e: CMPQ 0x10(CX), AX . . 10ca472: JBE 0x10ca91e . . 10ca478: SUBQ $0xe0, SP . . 10ca47f: MOVQ BP, 0xd8(SP) . . 10ca487: LEAQ 0xd8(SP), BP . . 10ca48f: XORL AX, AX . . 10ca491: XORL CX, CX . . 10ca493: JMP 0x10ca73f ;graph.go:104 . . 10ca498: MOVQ 0x88(SP), R10 ;graph.go:110 . . 10ca4a0: LEAQ 0x1(R10), R9 . . 10ca4a4: MOVQ 0x78(SP), R10 . . 10ca4a9: MOVQ 0x70(SP), R11 . . 10ca4ae: MOVQ 0x98(SP), R12 . . 10ca4b6: MOVQ 0x68(SP), R13 . . 10ca4bb: MOVQ 0xc0(SP), R14 . . 10ca4c3: MOVQ R10, AX . . 10ca4c6: MOVQ 0x50(SP), CX ;graph.go:107 . . 10ca4cb: MOVQ R11, DX ;graph.go:111 . . 10ca4ce: MOVQ 0xe8(SP), BX . . 10ca4d6: MOVQ R12, SI . . 10ca4d9: MOVQ R13, DI . . 10ca4dc: MOVQ R14, R8 ;graph.go:110 . . 10ca4df: CMPQ AX, R9 . . 10ca4e2: JGE 0x10ca736 410ms 410ms 10ca4e8: MOVQ 0(R8)(R9*8), R10 ;main.(*Graph).buildAdjList graph.go:110 . . 10ca4ec: MOVQ 0x8(BX), R11 ;graph.go:111 . . 10ca4f0: MOVQ 0(BX), R12 . . 10ca4f3: CMPQ R11, R10 . . 10ca4f6: JAE 0x10ca912 . . 10ca4fc: MOVQ R9, 0x88(SP) ;graph.go:110 . . 10ca504: MOVQ R10, 0x58(SP) . . 10ca509: LEAQ 0(R10)(R10*2), AX ;graph.go:111 . . 10ca50d: MOVQ AX, 0x80(SP) . . 10ca515: MOVQ 0(R12)(AX*8), CX 30ms 30ms 10ca519: MOVQ 0x10(R12)(AX*8), BX ;main.(*Graph).buildAdjList graph.go:111 . . 10ca51e: MOVQ 0x8(R12)(AX*8), R8 ;graph.go:111 10ms 10ms 10ca523: MOVQ SI, 0(SP) ;main.(*Graph).buildAdjList graph.go:111 . . 10ca527: MOVQ DI, 0x8(SP) ;graph.go:111 . . 10ca52c: MOVQ DX, 0x10(SP) . . 10ca531: MOVQ CX, 0x18(SP) . . 10ca536: MOVQ R8, 0x20(SP) . . 10ca53b: MOVQ BX, 0x28(SP) . 140ms 10ca540: CALL main.distance(SB) ;main.(*Graph).buildAdjList graph.go:111 . . 10ca545: CMPQ $0x1, 0x30(SP) ;graph.go:111 10ms 10ms 10ca54b: JNE 0x10ca71c ;main.(*Graph).buildAdjList graph.go:111 . . 10ca551: MOVQ 0xe8(SP), DX ;graph.go:112 . . 10ca559: MOVQ 0x18(DX), BX . . 10ca55d: MOVQ 0x20(DX), CX . . 10ca561: MOVQ 0x60(SP), AX . . 10ca566: CMPQ CX, AX . . 10ca569: JAE 0x10ca90d . . 10ca56f: MOVQ 0x90(SP), SI . . 10ca577: MOVQ 0x10(BX)(SI*8), DI 20ms 20ms 10ca57c: MOVQ 0x8(BX)(SI*8), R8 ;main.(*Graph).buildAdjList graph.go:112 . . 10ca581: MOVQ 0(BX)(SI*8), R9 ;graph.go:112 . . 10ca585: LEAQ 0x1(R8), R10 . . 10ca589: LEAQ 0(BX)(SI*8), R11 . . 10ca58d: CMPQ DI, R10 . . 10ca590: JA 0x10ca685 . . 10ca596: LEAQ 0x1(R8), DI . . 10ca59a: MOVQ DI, 0x8(BX)(SI*8) . . 10ca59f: MOVQ 0x58(SP), BX . . 10ca5a4: MOVQ BX, 0(R9)(R8*8) . . 10ca5a8: MOVQ 0x20(DX), CX ;graph.go:113 . . 10ca5ac: MOVQ 0x18(DX), DI . . 10ca5b0: CMPQ CX, BX . . 10ca5b3: JAE 0x10ca905 . . 10ca5b9: MOVQ 0x80(SP), BX . . 10ca5c1: MOVQ 0(DI)(BX*8), R8 10ms 10ms 10ca5c5: MOVQ 0x10(DI)(BX*8), R9 ;main.(*Graph).buildAdjList graph.go:113 . . 10ca5ca: MOVQ 0x8(DI)(BX*8), R10 ;graph.go:113 . . 10ca5cf: LEAQ 0x1(R10), R11 . . 10ca5d3: LEAQ 0(DI)(BX*8), R12 . . 10ca5d7: CMPQ R9, R11 . . 10ca5da: JA 0x10ca5ee . . 10ca5dc: LEAQ 0x1(R10), R9 . . 10ca5e0: MOVQ R9, 0x8(DI)(BX*8) . . 10ca5e5: MOVQ AX, 0(R8)(R10*8) . . 10ca5e9: JMP 0x10ca498 . . 10ca5ee: MOVQ R12, 0xb8(SP) 10ms 10ms 10ca5f6: MOVQ DI, 0xb0(SP) ;main.(*Graph).buildAdjList graph.go:113 . . 10ca5fe: LEAQ type.*+85856(SB), AX ;graph.go:113 . . 10ca605: MOVQ AX, 0(SP) . . 10ca609: MOVQ R8, 0x8(SP) . . 10ca60e: MOVQ R10, 0x10(SP) . . 10ca613: MOVQ R9, 0x18(SP) . . 10ca618: MOVQ R11, 0x20(SP) . 140ms 10ca61d: CALL runtime.growslice(SB) ;main.(*Graph).buildAdjList graph.go:113 . . 10ca622: MOVQ 0x28(SP), AX ;graph.go:113 . . 10ca627: MOVQ 0x30(SP), CX . . 10ca62c: MOVQ 0x38(SP), DX . . 10ca631: MOVQ 0x80(SP), BX . . 10ca639: MOVQ 0xb0(SP), SI . . 10ca641: MOVQ DX, 0x10(SI)(BX*8) . . 10ca646: CMPL $0x0, runtime.writeBarrier(SB) . . 10ca64d: JNE 0x10ca676 . . 10ca64f: MOVQ AX, 0(SI)(BX*8) . . 10ca653: MOVQ 0xe8(SP), DX ;graph.go:111 . . 10ca65b: MOVQ SI, DI ;graph.go:113 . . 10ca65e: MOVQ CX, R10 . . 10ca661: MOVQ AX, R8 . . 10ca664: MOVQ 0x60(SP), AX . . 10ca669: MOVQ 0x90(SP), SI ;graph.go:112 . . 10ca671: JMP 0x10ca5dc ;graph.go:113 . . 10ca676: MOVQ 0xb8(SP), DI . . 10ca67e: CALL runtime.gcWriteBarrier(SB) . . 10ca683: JMP 0x10ca653 . . 10ca685: MOVQ BX, 0xa8(SP) ;graph.go:112 . . 10ca68d: MOVQ R11, 0xa0(SP) . . 10ca695: LEAQ type.*+85856(SB), AX . . 10ca69c: MOVQ AX, 0(SP) . . 10ca6a0: MOVQ R9, 0x8(SP) . . 10ca6a5: MOVQ R8, 0x10(SP) . . 10ca6aa: MOVQ DI, 0x18(SP) . . 10ca6af: MOVQ R10, 0x20(SP) . 220ms 10ca6b4: CALL runtime.growslice(SB) ;main.(*Graph).buildAdjList graph.go:112 . . 10ca6b9: MOVQ 0x28(SP), AX ;graph.go:112 . . 10ca6be: MOVQ 0x30(SP), CX . . 10ca6c3: MOVQ 0x38(SP), DX . . 10ca6c8: MOVQ 0x90(SP), BX . . 10ca6d0: MOVQ 0xa8(SP), SI . . 10ca6d8: MOVQ DX, 0x10(SI)(BX*8) . . 10ca6dd: CMPL $0x0, runtime.writeBarrier(SB) . . 10ca6e4: JNE 0x10ca70d . . 10ca6e6: MOVQ AX, 0(SI)(BX*8) . . 10ca6ea: MOVQ 0xe8(SP), DX ;graph.go:113 . . 10ca6f2: MOVQ SI, BX ;graph.go:112 . . 10ca6f5: MOVQ 0x90(SP), SI . . 10ca6fd: MOVQ CX, R8 . . 10ca700: MOVQ AX, R9 . . 10ca703: MOVQ 0x60(SP), AX ;graph.go:113 . . 10ca708: JMP 0x10ca596 ;graph.go:112 . . 10ca70d: MOVQ 0xa0(SP), DI . . 10ca715: CALL runtime.gcWriteBarrier(SB) . . 10ca71a: JMP 0x10ca6ea . . 10ca71c: MOVQ 0x60(SP), AX ;graph.go:104 . . 10ca721: MOVQ 0xe8(SP), DX ;graph.go:111 . . 10ca729: MOVQ 0x90(SP), SI ;graph.go:112 . . 10ca731: JMP 0x10ca498 ;graph.go:110 . . 10ca736: MOVQ 0x60(SP), DX ;graph.go:104 . . 10ca73b: LEAQ 0x1(DX), AX . . 10ca73f: MOVQ 0xe8(SP), DX . . 10ca747: MOVQ 0x8(DX), BX . . 10ca74b: MOVQ 0(DX), SI . . 10ca74e: CMPQ BX, AX . . 10ca751: JGE 0x10ca860 . . 10ca757: MOVQ AX, 0x60(SP) . . 10ca75c: MOVQ CX, 0x50(SP) ;graph.go:107 . . 10ca761: LEAQ 0(AX)(AX*2), CX ;graph.go:105 . . 10ca765: MOVQ CX, 0x90(SP) . . 10ca76d: MOVQ 0x10(SI)(CX*8), DX . . 10ca772: MOVQ DX, 0x70(SP) . . 10ca777: MOVQ 0x8(SI)(CX*8), BX . . 10ca77c: MOVQ BX, 0x68(SP) . . 10ca781: MOVQ 0(SI)(CX*8), SI . . 10ca785: MOVQ SI, 0x98(SP) . . 10ca78d: MOVQ 0xf0(SP), DI ;graph.go:106 . . 10ca795: MOVQ DI, 0(SP) . . 10ca799: MOVQ SI, 0x8(SP) . . 10ca79e: MOVQ BX, 0x10(SP) . . 10ca7a3: MOVQ DX, 0x18(SP) . 190ms 10ca7a8: CALL main.(*index).nearCount(SB) ;main.(*Graph).buildAdjList graph.go:106 . . 10ca7ad: MOVQ 0x20(SP), AX ;graph.go:106 . . 10ca7b2: MOVQ AX, 0x78(SP) . . 10ca7b7: LEAQ type.*+85856(SB), CX ;graph.go:108 . . 10ca7be: MOVQ CX, 0(SP) . . 10ca7c2: MOVQ AX, 0x8(SP) . . 10ca7c7: MOVQ AX, 0x10(SP) . 170ms 10ca7cc: CALL runtime.makeslice(SB) ;main.(*Graph).buildAdjList graph.go:108 . . 10ca7d1: MOVQ 0x18(SP), AX ;graph.go:108 . . 10ca7d6: MOVQ AX, 0xc0(SP) . . 10ca7de: MOVQ 0xf0(SP), CX ;graph.go:109 . . 10ca7e6: MOVQ CX, 0(SP) . . 10ca7ea: MOVQ 0x98(SP), DX . . 10ca7f2: MOVQ DX, 0x8(SP) . . 10ca7f7: MOVQ 0x68(SP), BX . . 10ca7fc: MOVQ BX, 0x10(SP) . . 10ca801: MOVQ 0x70(SP), SI . . 10ca806: MOVQ SI, 0x18(SP) . . 10ca80b: MOVQ AX, 0x20(SP) . . 10ca810: MOVQ 0x78(SP), DI . . 10ca815: MOVQ DI, 0x28(SP) . . 10ca81a: MOVQ DI, 0x30(SP) . 510ms 10ca81f: CALL main.(*index).near(SB) ;main.(*Graph).buildAdjList graph.go:109 . . 10ca824: MOVQ 0x78(SP), AX ;graph.go:107 . . 10ca829: MOVQ 0x50(SP), CX . . 10ca82e: ADDQ AX, CX . . 10ca831: MOVQ CX, 0x50(SP) . . 10ca836: MOVQ 0x70(SP), DX ;graph.go:110 . . 10ca83b: MOVQ 0xe8(SP), BX . . 10ca843: MOVQ 0x98(SP), SI . . 10ca84b: MOVQ 0x68(SP), DI . . 10ca850: MOVQ 0xc0(SP), R8 . . 10ca858: XORL R9, R9 . . 10ca85b: JMP 0x10ca4df . . 10ca860: XORPS X0, X0 ;graph.go:117 . . 10ca863: CVTSI2SDQ CX, X0 . . 10ca868: XORPS X1, X1 . . 10ca86b: CVTSI2SDQ BX, X1 . . 10ca870: DIVSD X1, X0 . . 10ca874: MOVSD_XMM X0, 0(SP) . . 10ca879: CALL runtime.convT64(SB) . . 10ca87e: MOVQ 0x8(SP), AX . . 10ca883: XORPS X0, X0 . . 10ca886: MOVUPS X0, 0xc8(SP) . . 10ca88e: LEAQ type.*+84128(SB), CX . . 10ca895: MOVQ CX, 0xc8(SP) . . 10ca89d: MOVQ AX, 0xd0(SP) . . 10ca8a5: MOVQ os.Stdout(SB), AX ;print.go:213 . . 10ca8ac: LEAQ go.itab.*os.File,io.Writer(SB), CX . . 10ca8b3: MOVQ CX, 0(SP) . . 10ca8b7: MOVQ AX, 0x8(SP) . . 10ca8bc: LEAQ go.string.*+3293(SB), AX . . 10ca8c3: MOVQ AX, 0x10(SP) . . 10ca8c8: MOVQ $0xa, 0x18(SP) . . 10ca8d1: LEAQ 0xc8(SP), AX . . 10ca8d9: MOVQ AX, 0x20(SP) . . 10ca8de: MOVQ $0x1, 0x28(SP) . . 10ca8e7: MOVQ $0x1, 0x30(SP) . . 10ca8f0: CALL fmt.Fprintf(SB) . . 10ca8f5: MOVQ 0xd8(SP), BP . . 10ca8fd: ADDQ $0xe0, SP . . 10ca904: RET . . 10ca905: MOVQ BX, AX ;graph.go:113 . . 10ca908: CALL runtime.panicIndex(SB) . . 10ca90d: CALL runtime.panicIndex(SB) ;graph.go:112 . . 10ca912: MOVQ R10, AX ;graph.go:111 . . 10ca915: MOVQ R11, CX . . 10ca918: CALL runtime.panicIndex(SB) . . 10ca91d: NOPL . . 10ca91e: CALL runtime.morestack_noctxt(SB) ;graph.go:102 . . 10ca923: JMP main.(*Graph).buildAdjList(SB) . . 10ca928: INT $0x3 . . 10ca929: INT $0x3 . . 10ca92a: INT $0x3 . . 10ca92b: INT $0x3 . . 10ca92c: INT $0x3 . . 10ca92d: INT $0x3 . . 10ca92e: INT $0x3 ROUTINE ======================== main.(*index).add 120ms 730ms (flat, cum) 12.46% of Total . . 10cc020: MOVQ GS:0x30, CX ;index.go:31 . . 10cc029: LEAQ -0x18(SP), AX . . 10cc02e: CMPQ 0x10(CX), AX . . 10cc032: JBE 0x10cc326 . . 10cc038: SUBQ $0x98, SP . . 10cc03f: MOVQ BP, 0x90(SP) . . 10cc047: LEAQ 0x90(SP), BP . . 10cc04f: MOVQ 0xa0(SP), BX ;index.go:34 . . 10cc057: MOVQ 0x38(BX), DX . . 10cc05b: MOVQ 0x28(BX), SI . . 10cc05f: MOVQ 0xb8(SP), DI . . 10cc067: LEAQ -0x1(DI), CX . . 10cc06b: CMPQ DX, CX . . 10cc06e: JA 0x10cc320 . . 10cc074: MOVQ CX, 0x58(SP) . . 10cc079: MOVQ DX, 0x50(SP) . . 10cc07e: MOVQ SI, 0x78(SP) . . 10cc083: MOVQ 0xb0(SP), R8 ;index.go:35 . . 10cc08b: XORL AX, AX . . 10cc08d: JMP 0x10cc0e2 . . 10cc08f: LEAQ 0x1(R8), R10 ;index.go:41 . . 10cc093: MOVQ R10, 0x8(BX)(SI*8) . . 10cc098: MOVQ 0xa8(SP), R10 . . 10cc0a0: MOVQ R10, 0(R9)(R8*8) . . 10cc0a4: MOVQ 0x78(SP), R9 ;index.go:35 . . 10cc0a9: MOVQ 0x50(SP), R11 . . 10cc0ae: MOVQ 0x58(SP), R12 . . 10cc0b3: MOVQ 0xb8(SP), R13 . . 10cc0bb: MOVQ 0xb0(SP), R14 . . 10cc0c3: MOVQ 0x68(SP), R15 . . 10cc0c8: MOVQ R12, CX ;index.go:125 . . 10cc0cb: MOVQ R11, DX ;index.go:124 . . 10cc0ce: MOVQ 0xa0(SP), BX ;index.go:38 . . 10cc0d6: MOVQ R9, SI ;index.go:125 . . 10cc0d9: MOVQ R13, DI ;index.go:35 . . 10cc0dc: MOVQ R14, R8 ;index.go:126 . . 10cc0df: MOVQ R15, AX ;index.go:35 . . 10cc0e2: CMPQ DI, AX . . 10cc0e5: JGE 0x10cc2f3 . 30ms 10cc0eb: NOPL ;main.(*index).add index.go:36 . . 10cc0ec: CMPQ DX, AX ;index.go:124 . . 10cc0ef: JA 0x10cc318 . . 10cc0f5: CMPQ CX, AX ;index.go:125 . . 10cc0f8: JA 0x10cc313 . . 10cc0fe: MOVQ AX, 0x48(SP) ;index.go:35 . . 10cc103: SUBQ AX, CX ;index.go:125 . . 10cc106: MOVQ CX, 0x40(SP) . . 10cc10b: SUBQ AX, DX . . 10cc10e: NEGQ DX . . 10cc111: SARQ $0x3f, DX . . 10cc115: ANDQ AX, DX . . 10cc118: ADDQ SI, DX . . 10cc11b: MOVQ DX, 0x70(SP) . . 10cc120: CMPQ R8, SI ;index.go:126 . . 10cc123: JE 0x10cc138 . . 10cc125: MOVQ SI, 0(SP) . . 10cc129: MOVQ R8, 0x8(SP) . . 10cc12e: MOVQ AX, 0x10(SP) . . 10cc133: CALL runtime.memmove(SB) . . 10cc138: MOVQ 0x48(SP), AX ;index.go:127 . . 10cc13d: INCQ AX . . 10cc140: MOVQ AX, 0x68(SP) . . 10cc145: MOVQ 0xb8(SP), CX . . 10cc14d: SUBQ AX, CX . . 10cc150: MOVQ 0x40(SP), BX . . 10cc155: CMPQ CX, BX . . 10cc158: CMOVG CX, BX 10ms 10ms 10cc15c: MOVQ 0xc0(SP), CX ;main.skipOneCopy index.go:127 . . 10cc164: SUBQ AX, CX ;index.go:127 . . 10cc167: NEGQ CX . . 10cc16a: SARQ $0x3f, CX . . 10cc16e: ANDQ AX, CX . . 10cc171: MOVQ 0xb0(SP), DI . . 10cc179: ADDQ DI, CX . . 10cc17c: MOVQ 0x70(SP), R8 . . 10cc181: CMPQ R8, CX . . 10cc184: JNE 0x10cc2db . . 10cc18a: MOVQ 0xa0(SP), AX ;index.go:38 . . 10cc192: MOVQ 0(AX), CX . . 10cc195: MOVQ 0x8(AX), DX . . 10cc199: MOVQ 0x20(CX), CX . . 10cc19d: MOVQ DX, 0(SP) . 20ms 10cc1a1: CALL CX ;main.(*index).add index.go:38 . . 10cc1a3: MOVQ 0xa0(SP), AX ;index.go:39 . . 10cc1ab: MOVQ 0(AX), CX . . 10cc1ae: MOVQ 0x8(AX), DX . . 10cc1b2: MOVQ 0x40(CX), CX . . 10cc1b6: MOVQ DX, 0(SP) . . 10cc1ba: MOVQ 0x78(SP), DX . . 10cc1bf: MOVQ DX, 0x8(SP) . . 10cc1c4: MOVQ 0x58(SP), BX . . 10cc1c9: MOVQ BX, 0x10(SP) . . 10cc1ce: MOVQ 0x50(SP), SI . . 10cc1d3: MOVQ SI, 0x18(SP) . 30ms 10cc1d8: CALL CX ;main.(*index).add index.go:39 . . 10cc1da: MOVQ 0xa0(SP), AX ;index.go:40 . . 10cc1e2: MOVQ 0(AX), CX . . 10cc1e5: MOVQ 0x8(AX), DX . . 10cc1e9: MOVQ 0x38(CX), CX . . 10cc1ed: MOVQ DX, 0(SP) . 20ms 10cc1f1: CALL CX ;main.(*index).add index.go:40 . . 10cc1f3: MOVQ 0x8(SP), AX ;index.go:40 . . 10cc1f8: MOVQ 0xa0(SP), CX . . 10cc200: MOVQ 0x40(CX), DX . . 10cc204: TESTQ DX, DX . . 10cc207: JE 0x10cc30e . . 10cc20d: MOVQ DX, BX . . 10cc210: XORL DX, DX . . 10cc212: DIVQ BX 20ms 20ms 10cc215: MOVQ 0x10(CX), BX ;main.(*index).add index.go:41 . . 10cc219: MOVQ 0x18(CX), SI ;index.go:41 . . 10cc21d: CMPQ SI, DX . . 10cc220: JAE 0x10cc303 . . 10cc226: LEAQ 0(DX)(DX*2), SI . . 10cc22a: MOVQ 0x10(BX)(SI*8), DI 90ms 90ms 10cc22f: MOVQ 0x8(BX)(SI*8), R8 ;main.(*index).add index.go:41 . . 10cc234: MOVQ 0(BX)(SI*8), R9 ;index.go:41 . . 10cc238: LEAQ 0x1(R8), R10 . . 10cc23c: LEAQ 0(BX)(SI*8), R11 . . 10cc240: CMPQ DI, R10 . . 10cc243: JBE 0x10cc08f . . 10cc249: MOVQ BX, 0x88(SP) . . 10cc251: MOVQ SI, 0x60(SP) . . 10cc256: MOVQ R11, 0x80(SP) . . 10cc25e: LEAQ type.*+85856(SB), AX . . 10cc265: MOVQ AX, 0(SP) . . 10cc269: MOVQ R9, 0x8(SP) . . 10cc26e: MOVQ R8, 0x10(SP) . . 10cc273: MOVQ DI, 0x18(SP) . . 10cc278: MOVQ R10, 0x20(SP) . 490ms 10cc27d: CALL runtime.growslice(SB) ;main.(*index).add index.go:41 . . 10cc282: MOVQ 0x28(SP), AX ;index.go:41 . . 10cc287: MOVQ 0x30(SP), CX . . 10cc28c: MOVQ 0x38(SP), DX . . 10cc291: MOVQ 0x60(SP), BX . . 10cc296: MOVQ 0x88(SP), SI . . 10cc29e: MOVQ DX, 0x10(SI)(BX*8) . . 10cc2a3: CMPL $0x0, runtime.writeBarrier(SB) . . 10cc2aa: JNE 0x10cc2cc . . 10cc2ac: MOVQ AX, 0(SI)(BX*8) . . 10cc2b0: MOVQ CX, R8 . . 10cc2b3: MOVQ AX, R9 . . 10cc2b6: MOVQ 0xa0(SP), CX ;index.go:38 . . 10cc2be: MOVQ BX, DX ;index.go:41 . . 10cc2c1: MOVQ SI, BX . . 10cc2c4: MOVQ DX, SI . . 10cc2c7: JMP 0x10cc08f . . 10cc2cc: MOVQ 0x80(SP), DI . . 10cc2d4: CALL runtime.gcWriteBarrier(SB) . . 10cc2d9: JMP 0x10cc2b0 . . 10cc2db: MOVQ R8, 0(SP) ;index.go:127 . . 10cc2df: MOVQ CX, 0x8(SP) . . 10cc2e4: MOVQ BX, 0x10(SP) . 20ms 10cc2e9: CALL runtime.memmove(SB) ;main.skipOneCopy index.go:127 . . 10cc2ee: JMP 0x10cc18a ;index.go:127 . . 10cc2f3: MOVQ 0x90(SP), BP . . 10cc2fb: ADDQ $0x98, SP . . 10cc302: RET . . 10cc303: MOVQ DX, AX ;index.go:41 . . 10cc306: MOVQ SI, CX . . 10cc309: CALL runtime.panicIndexU(SB) . . 10cc30e: CALL runtime.panicdivide(SB) ;index.go:40 . . 10cc313: CALL runtime.panicSliceB(SB) ;index.go:125 . . 10cc318: MOVQ AX, CX ;index.go:124 . . 10cc31b: CALL runtime.panicSliceAcap(SB) . . 10cc320: CALL runtime.panicSliceAcap(SB) ;index.go:34 . . 10cc325: NOPL . . 10cc326: CALL runtime.morestack_noctxt(SB) ;index.go:31 . . 10cc32b: ? . . 10cc32c: LOCK CLD . . 10cc32e: ? ROUTINE ======================== main.(*index).near 40ms 510ms (flat, cum) 8.70% of Total . . 10cc6c0: MOVQ GS:0x30, CX ;index.go:97 . . 10cc6c9: LEAQ 0xfffffe70(SP), AX . . 10cc6d1: CMPQ 0x10(CX), AX . . 10cc6d5: JBE 0x10ccafa . . 10cc6db: SUBQ $0x210, SP . . 10cc6e2: MOVQ BP, 0x208(SP) . . 10cc6ea: LEAQ 0x208(SP), BP . . 10cc6f2: LEAQ 0x78(SP), DI ;index.go:98 . . 10cc6f7: XORPS X0, X0 . . 10cc6fa: MOVQ BP, -0x10(SP) . . 10cc6ff: LEAQ -0x10(SP), BP . . 10cc704: CALL 0x105866e . . 10cc709: MOVQ 0(BP), BP . . 10cc70d: MOVQ 0x228(SP), AX ;index.go:99 . . 10cc715: LEAQ 0x1(AX), CX . . 10cc719: CMPQ $0x30, CX . . 10cc71d: JA 0x10ccaef . . 10cc723: MOVQ CX, 0x60(SP) . . 10cc728: MOVQ 0x218(SP), AX ;index.go:100 . . 10cc730: MOVQ 0(AX), CX . . 10cc733: MOVQ 0x8(AX), DX . . 10cc737: MOVQ 0x20(CX), CX . . 10cc73b: MOVQ DX, 0(SP) . . 10cc73f: CALL CX . . 10cc741: MOVQ 0x218(SP), AX ;index.go:101 . . 10cc749: MOVQ 0(AX), CX . . 10cc74c: MOVQ 0x8(AX), DX . . 10cc750: MOVQ 0x40(CX), CX . . 10cc754: MOVQ DX, 0(SP) . . 10cc758: MOVQ 0x220(SP), DX . . 10cc760: MOVQ DX, 0x8(SP) . . 10cc765: MOVQ 0x228(SP), BX . . 10cc76d: MOVQ BX, 0x10(SP) . . 10cc772: MOVQ 0x230(SP), SI . . 10cc77a: MOVQ SI, 0x18(SP) . . 10cc77f: CALL CX . . 10cc781: MOVQ 0x218(SP), AX ;index.go:102 . . 10cc789: MOVQ 0(AX), CX . . 10cc78c: MOVQ 0x8(AX), DX . . 10cc790: MOVQ 0x38(CX), CX . . 10cc794: MOVQ DX, 0(SP) . 10ms 10cc798: CALL CX ;main.(*index).near index.go:102 . . 10cc79a: MOVQ 0x8(SP), AX ;index.go:102 . . 10cc79f: MOVQ 0x218(SP), CX . . 10cc7a7: MOVQ 0x40(CX), DX . . 10cc7ab: TESTQ DX, DX . . 10cc7ae: JE 0x10ccaea . . 10cc7b4: MOVQ DX, BX . . 10cc7b7: XORL DX, DX . . 10cc7b9: DIVQ BX 10ms 10ms 10cc7bc: MOVQ 0x60(SP), BX ;main.(*index).near index.go:102 . . 10cc7c1: TESTQ BX, BX ;index.go:102 . . 10cc7c4: JBE 0x10ccae0 . . 10cc7ca: MOVQ DX, 0x78(SP) . . 10cc7cf: MOVQ 0x28(CX), SI ;index.go:103 . . 10cc7d3: MOVQ 0x38(CX), DX . . 10cc7d7: MOVQ 0x228(SP), DI . . 10cc7df: LEAQ -0x1(DI), R8 . . 10cc7e3: CMPQ DX, R8 . . 10cc7e6: JA 0x10ccad8 . . 10cc7ec: MOVQ R8, 0x68(SP) . . 10cc7f1: MOVQ SI, 0x200(SP) . . 10cc7f9: MOVQ DX, 0x48(SP) . . 10cc7fe: MOVQ 0x220(SP), R9 ;index.go:104 . . 10cc806: XORL AX, AX . . 10cc808: JMP 0x10cc84a . . 10cc80a: MOVQ AX, R10 ;index.go:109 . . 10cc80d: SHLQ $0x3, AX . . 10cc811: MOVQ DX, 0x78(SP)(AX*1) . . 10cc816: MOVQ 0x228(SP), R11 ;index.go:104 . . 10cc81e: MOVQ 0x200(SP), R12 . . 10cc826: MOVQ 0x48(SP), R13 . . 10cc82b: MOVQ 0x68(SP), R14 . . 10cc830: MOVQ 0x220(SP), R15 . . 10cc838: MOVQ R13, DX ;index.go:124 . . 10cc83b: MOVQ R12, SI ;index.go:125 . . 10cc83e: MOVQ R11, DI ;index.go:104 . . 10cc841: MOVQ R14, R8 ;index.go:125 . . 10cc844: MOVQ R15, R9 ;index.go:126 . . 10cc847: MOVQ R10, AX ;index.go:104 . . 10cc84a: CMPQ DI, AX . . 10cc84d: JGE 0x10cc9b6 . . 10cc853: NOPL ;index.go:105 . . 10cc854: CMPQ DX, AX ;index.go:124 . . 10cc857: JA 0x10ccad0 . . 10cc85d: CMPQ R8, AX ;index.go:125 . . 10cc860: JA 0x10ccac8 . . 10cc866: MOVQ AX, 0x40(SP) ;index.go:104 . . 10cc86b: SUBQ AX, R8 ;index.go:125 . . 10cc86e: MOVQ R8, 0x38(SP) . . 10cc873: SUBQ AX, DX . . 10cc876: NEGQ DX . . 10cc879: SARQ $0x3f, DX . . 10cc87d: ANDQ AX, DX . . 10cc880: ADDQ SI, DX . . 10cc883: MOVQ DX, 0x1f8(SP) . . 10cc88b: CMPQ R9, SI ;index.go:126 . . 10cc88e: JE 0x10cc8a3 . . 10cc890: MOVQ SI, 0(SP) . . 10cc894: MOVQ R9, 0x8(SP) . . 10cc899: MOVQ AX, 0x10(SP) . . 10cc89e: CALL runtime.memmove(SB) . . 10cc8a3: MOVQ 0x40(SP), AX ;index.go:127 . . 10cc8a8: INCQ AX . . 10cc8ab: MOVQ AX, 0x70(SP) . . 10cc8b0: MOVQ 0x228(SP), CX . . 10cc8b8: SUBQ AX, CX . . 10cc8bb: MOVQ 0x38(SP), BX . . 10cc8c0: CMPQ CX, BX . . 10cc8c3: CMOVG CX, BX . . 10cc8c7: MOVQ 0x230(SP), CX . . 10cc8cf: SUBQ AX, CX . . 10cc8d2: NEGQ CX . . 10cc8d5: SARQ $0x3f, CX . . 10cc8d9: ANDQ AX, CX . . 10cc8dc: MOVQ 0x220(SP), DI . . 10cc8e4: ADDQ DI, CX . . 10cc8e7: MOVQ 0x1f8(SP), R8 . . 10cc8ef: CMPQ R8, CX . . 10cc8f2: JNE 0x10cc99e 10ms 10ms 10cc8f8: MOVQ 0x218(SP), AX ;main.(*index).near index.go:107 . . 10cc900: MOVQ 0(AX), CX ;index.go:107 . . 10cc903: MOVQ 0x8(AX), DX . . 10cc907: MOVQ 0x20(CX), CX . . 10cc90b: MOVQ DX, 0(SP) . . 10cc90f: CALL CX . . 10cc911: MOVQ 0x218(SP), AX ;index.go:108 . . 10cc919: MOVQ 0(AX), CX . . 10cc91c: MOVQ 0x8(AX), DX . . 10cc920: MOVQ 0x40(CX), CX . . 10cc924: MOVQ DX, 0(SP) . . 10cc928: MOVQ 0x200(SP), DX . . 10cc930: MOVQ DX, 0x8(SP) . . 10cc935: MOVQ 0x68(SP), BX . . 10cc93a: MOVQ BX, 0x10(SP) . . 10cc93f: MOVQ 0x48(SP), SI . . 10cc944: MOVQ SI, 0x18(SP) . 20ms 10cc949: CALL CX ;main.(*index).near index.go:108 . . 10cc94b: MOVQ 0x218(SP), AX ;index.go:109 . . 10cc953: MOVQ 0(AX), CX . . 10cc956: MOVQ 0x8(AX), DX . . 10cc95a: MOVQ 0x38(CX), CX . . 10cc95e: MOVQ DX, 0(SP) . 40ms 10cc962: CALL CX ;main.(*index).near index.go:109 . . 10cc964: MOVQ 0x8(SP), AX ;index.go:109 . . 10cc969: MOVQ 0x218(SP), CX . . 10cc971: MOVQ 0x40(CX), DX . . 10cc975: TESTQ DX, DX . . 10cc978: JE 0x10ccac3 . . 10cc97e: MOVQ DX, BX . . 10cc981: XORL DX, DX . . 10cc983: DIVQ BX 20ms 20ms 10cc986: MOVQ 0x70(SP), AX ;main.(*index).near index.go:109 . . 10cc98b: MOVQ 0x60(SP), BX ;index.go:109 . . 10cc990: CMPQ BX, AX . . 10cc993: JB 0x10cc80a . . 10cc999: JMP 0x10ccabb . . 10cc99e: MOVQ R8, 0(SP) ;index.go:127 . . 10cc9a2: MOVQ CX, 0x8(SP) . . 10cc9a7: MOVQ BX, 0x10(SP) . . 10cc9ac: CALL runtime.memmove(SB) . . 10cc9b1: JMP 0x10cc8f8 . . 10cc9b6: MOVQ 0x248(SP), DX ;index.go:113 . . 10cc9be: MOVQ 0x240(SP), SI . . 10cc9c6: MOVQ 0x238(SP), DI . . 10cc9ce: XORL AX, AX . . 10cc9d0: XORL R8, R8 . . 10cc9d3: JMP 0x10cc9e1 . . 10cc9d5: INCQ AX . . 10cc9d8: MOVQ R11, DX ;index.go:117 . . 10cc9db: MOVQ SI, R8 . . 10cc9de: MOVQ R10, SI . . 10cc9e1: CMPQ BX, AX ;index.go:113 . . 10cc9e4: JGE 0x10cca95 . . 10cc9ea: MOVQ 0x78(SP)(AX*8), R9 ;index.go:114 . . 10cc9ef: MOVQ 0x10(CX), R10 ;index.go:115 . . 10cc9f3: MOVQ 0x18(CX), R11 . . 10cc9f7: CMPQ R11, R9 . . 10cc9fa: JAE 0x10ccab0 . . 10cca00: LEAQ 0(R9)(R9*2), R9 . . 10cca04: MOVQ 0x8(R10)(R9*8), R11 . . 10cca09: MOVQ 0(R10)(R9*8), R9 . . 10cca0d: CMPQ SI, R8 ;index.go:117 . . 10cca10: JA 0x10ccaa5 . . 10cca16: MOVQ SI, R10 . . 10cca19: SUBQ R8, SI . . 10cca1c: CMPQ R11, SI . . 10cca1f: CMOVG R11, SI . . 10cca23: MOVQ DX, R11 . . 10cca26: SUBQ R8, DX . . 10cca29: NEGQ DX . . 10cca2c: SHLQ $0x3, R8 . . 10cca30: SARQ $0x3f, DX . . 10cca34: ANDQ DX, R8 . . 10cca37: LEAQ 0(DI)(R8*1), DX . . 10cca3b: CMPQ R9, DX . . 10cca3e: JE 0x10cc9d5 . . 10cca40: MOVQ AX, 0x58(SP) ;index.go:113 . . 10cca45: MOVQ SI, 0x50(SP) ;index.go:117 . . 10cca4a: MOVQ DX, 0(SP) . . 10cca4e: MOVQ R9, 0x8(SP) . . 10cca53: SHLQ $0x3, SI . . 10cca57: MOVQ SI, 0x10(SP) . 400ms 10cca5c: CALL runtime.memmove(SB) ;main.(*index).near index.go:117 . . 10cca61: MOVQ 0x58(SP), AX ;index.go:113 . . 10cca66: MOVQ 0x218(SP), CX ;index.go:115 . . 10cca6e: MOVQ 0x60(SP), BX ;index.go:113 . . 10cca73: MOVQ 0x50(SP), SI ;index.go:117 . . 10cca78: MOVQ 0x238(SP), DI . . 10cca80: MOVQ 0x240(SP), R10 . . 10cca88: MOVQ 0x248(SP), R11 . . 10cca90: JMP 0x10cc9d5 . . 10cca95: MOVQ 0x208(SP), BP . . 10cca9d: ADDQ $0x210, SP . . 10ccaa4: RET . . 10ccaa5: MOVQ R8, AX . . 10ccaa8: MOVQ SI, CX . . 10ccaab: CALL runtime.panicSliceB(SB) . . 10ccab0: MOVQ R9, AX ;index.go:115 . . 10ccab3: MOVQ R11, CX . . 10ccab6: CALL runtime.panicIndexU(SB) . . 10ccabb: MOVQ BX, CX ;index.go:109 . . 10ccabe: CALL runtime.panicIndex(SB) . . 10ccac3: CALL runtime.panicdivide(SB) . . 10ccac8: MOVQ R8, CX ;index.go:125 . . 10ccacb: CALL runtime.panicSliceB(SB) . . 10ccad0: MOVQ AX, CX ;index.go:124 . . 10ccad3: CALL runtime.panicSliceAcap(SB) . . 10ccad8: MOVQ R8, CX ;index.go:103 . . 10ccadb: CALL runtime.panicSliceAcap(SB) . . 10ccae0: XORL AX, AX ;index.go:102 . . 10ccae2: MOVQ BX, CX . . 10ccae5: CALL runtime.panicIndex(SB) . . 10ccaea: CALL runtime.panicdivide(SB) . . 10ccaef: MOVL $0x30, DX ;index.go:99 . . 10ccaf4: CALL runtime.panicSliceAlen(SB) . . 10ccaf9: NOPL . . 10ccafa: CALL runtime.morestack_noctxt(SB) ;index.go:97 . . 10ccaff: JMP main.(*index).near(SB) . . 10ccb04: INT $0x3 . . 10ccb05: INT $0x3 . . 10ccb06: INT $0x3 . . 10ccb07: INT $0x3 . . 10ccb08: INT $0x3 . . 10ccb09: INT $0x3 . . 10ccb0a: INT $0x3 . . 10ccb0b: INT $0x3 . . 10ccb0c: INT $0x3 . . 10ccb0d: INT $0x3 . . 10ccb0e: INT $0x3 ROUTINE ======================== main.(*index).nearCount 100ms 200ms (flat, cum) 3.41% of Total . . 10cc330: MOVQ GS:0x30, CX ;index.go:59 . . 10cc339: LEAQ 0xfffffe80(SP), AX . . 10cc341: CMPQ 0x10(CX), AX . . 10cc345: JBE 0x10cc6b3 . . 10cc34b: SUBQ $0x200, SP . . 10cc352: MOVQ BP, 0x1f8(SP) . . 10cc35a: LEAQ 0x1f8(SP), BP . . 10cc362: LEAQ 0x68(SP), DI ;index.go:60 . . 10cc367: XORPS X0, X0 . . 10cc36a: MOVQ BP, -0x10(SP) . . 10cc36f: LEAQ -0x10(SP), BP . . 10cc374: CALL 0x105866e . . 10cc379: MOVQ 0(BP), BP . . 10cc37d: MOVQ 0x218(SP), AX ;index.go:61 . . 10cc385: LEAQ 0x1(AX), CX . . 10cc389: CMPQ $0x30, CX . . 10cc38d: JA 0x10cc6a8 . . 10cc393: MOVQ CX, 0x50(SP) . . 10cc398: MOVQ 0x208(SP), AX ;index.go:62 . . 10cc3a0: MOVQ 0(AX), CX . . 10cc3a3: MOVQ 0x8(AX), DX . . 10cc3a7: MOVQ 0x20(CX), CX . . 10cc3ab: MOVQ DX, 0(SP) . . 10cc3af: CALL CX . . 10cc3b1: MOVQ 0x208(SP), AX ;index.go:63 . . 10cc3b9: MOVQ 0(AX), CX . . 10cc3bc: MOVQ 0x8(AX), DX . . 10cc3c0: MOVQ 0x40(CX), CX . . 10cc3c4: MOVQ DX, 0(SP) . . 10cc3c8: MOVQ 0x210(SP), DX . . 10cc3d0: MOVQ DX, 0x8(SP) . . 10cc3d5: MOVQ 0x218(SP), BX . . 10cc3dd: MOVQ BX, 0x10(SP) . . 10cc3e2: MOVQ 0x220(SP), SI . . 10cc3ea: MOVQ SI, 0x18(SP) . 10ms 10cc3ef: CALL CX ;main.(*index).nearCount index.go:63 . . 10cc3f1: MOVQ 0x208(SP), AX ;index.go:64 . . 10cc3f9: MOVQ 0(AX), CX . . 10cc3fc: MOVQ 0x8(AX), DX . . 10cc400: MOVQ 0x38(CX), CX . . 10cc404: MOVQ DX, 0(SP) . . 10cc408: CALL CX . . 10cc40a: MOVQ 0x8(SP), AX . . 10cc40f: MOVQ 0x208(SP), CX . . 10cc417: MOVQ 0x40(CX), DX . . 10cc41b: TESTQ DX, DX . . 10cc41e: JE 0x10cc6a3 . . 10cc424: MOVQ DX, BX . . 10cc427: XORL DX, DX . . 10cc429: DIVQ BX 10ms 10ms 10cc42c: MOVQ 0x50(SP), BX ;main.(*index).nearCount index.go:64 . . 10cc431: TESTQ BX, BX ;index.go:64 . . 10cc434: JBE 0x10cc699 . . 10cc43a: MOVQ DX, 0x68(SP) . . 10cc43f: MOVQ 0x38(CX), DX ;index.go:65 . . 10cc443: MOVQ 0x28(CX), SI . . 10cc447: MOVQ 0x218(SP), DI . . 10cc44f: LEAQ -0x1(DI), R8 . . 10cc453: CMPQ DX, R8 . . 10cc456: JA 0x10cc691 . . 10cc45c: MOVQ R8, 0x58(SP) . . 10cc461: MOVQ DX, 0x48(SP) . . 10cc466: MOVQ SI, 0x1f0(SP) . . 10cc46e: MOVQ 0x210(SP), R9 ;index.go:66 . . 10cc476: XORL AX, AX . . 10cc478: JMP 0x10cc4ba . . 10cc47a: MOVQ AX, R10 ;index.go:71 . . 10cc47d: SHLQ $0x3, AX . . 10cc481: MOVQ DX, 0x68(SP)(AX*1) . . 10cc486: MOVQ 0x218(SP), R11 ;index.go:66 . . 10cc48e: MOVQ 0x1f0(SP), R12 . . 10cc496: MOVQ 0x48(SP), R13 . . 10cc49b: MOVQ 0x58(SP), R14 . . 10cc4a0: MOVQ 0x210(SP), R15 . . 10cc4a8: MOVQ R13, DX ;index.go:124 . . 10cc4ab: MOVQ R12, SI ;index.go:125 . . 10cc4ae: MOVQ R11, DI ;index.go:66 . . 10cc4b1: MOVQ R14, R8 ;index.go:125 . . 10cc4b4: MOVQ R15, R9 ;index.go:126 . . 10cc4b7: MOVQ R10, AX ;index.go:66 . . 10cc4ba: CMPQ DI, AX . . 10cc4bd: JGE 0x10cc623 . 10ms 10cc4c3: NOPL ;main.(*index).nearCount index.go:67 . . 10cc4c4: CMPQ DX, AX ;index.go:124 . . 10cc4c7: JA 0x10cc689 . . 10cc4cd: CMPQ R8, AX ;index.go:125 . . 10cc4d0: JA 0x10cc681 . . 10cc4d6: MOVQ AX, 0x40(SP) ;index.go:66 . . 10cc4db: SUBQ AX, R8 ;index.go:125 . . 10cc4de: MOVQ R8, 0x38(SP) . . 10cc4e3: SUBQ AX, DX . . 10cc4e6: NEGQ DX 10ms 10ms 10cc4e9: SARQ $0x3f, DX ;main.skipOneCopy index.go:125 . . 10cc4ed: ANDQ AX, DX ;index.go:125 . . 10cc4f0: ADDQ SI, DX . . 10cc4f3: MOVQ DX, 0x1e8(SP) . . 10cc4fb: CMPQ R9, SI ;index.go:126 . . 10cc4fe: JE 0x10cc513 . . 10cc500: MOVQ SI, 0(SP) . . 10cc504: MOVQ R9, 0x8(SP) . . 10cc509: MOVQ AX, 0x10(SP) . . 10cc50e: CALL runtime.memmove(SB) . . 10cc513: MOVQ 0x40(SP), AX ;index.go:127 . . 10cc518: INCQ AX . . 10cc51b: MOVQ AX, 0x60(SP) . . 10cc520: MOVQ 0x218(SP), CX . . 10cc528: SUBQ AX, CX . . 10cc52b: MOVQ 0x38(SP), BX . . 10cc530: CMPQ CX, BX . . 10cc533: CMOVG CX, BX . . 10cc537: MOVQ 0x220(SP), CX . . 10cc53f: SUBQ AX, CX . . 10cc542: NEGQ CX . . 10cc545: SARQ $0x3f, CX . . 10cc549: ANDQ AX, CX . . 10cc54c: MOVQ 0x210(SP), DI . . 10cc554: ADDQ DI, CX . . 10cc557: MOVQ 0x1e8(SP), R8 . . 10cc55f: CMPQ R8, CX . . 10cc562: JNE 0x10cc60b . . 10cc568: MOVQ 0x208(SP), AX ;index.go:69 . . 10cc570: MOVQ 0(AX), CX . . 10cc573: MOVQ 0x8(AX), DX . . 10cc577: MOVQ 0x20(CX), CX . . 10cc57b: MOVQ DX, 0(SP) . 10ms 10cc57f: CALL CX ;main.(*index).nearCount index.go:69 . . 10cc581: MOVQ 0x208(SP), AX ;index.go:70 . . 10cc589: MOVQ 0(AX), CX . . 10cc58c: MOVQ 0x8(AX), DX . . 10cc590: MOVQ 0x40(CX), CX . . 10cc594: MOVQ DX, 0(SP) . . 10cc598: MOVQ 0x1f0(SP), DX . . 10cc5a0: MOVQ DX, 0x8(SP) . . 10cc5a5: MOVQ 0x58(SP), BX . . 10cc5aa: MOVQ BX, 0x10(SP) . . 10cc5af: MOVQ 0x48(SP), SI . . 10cc5b4: MOVQ SI, 0x18(SP) . . 10cc5b9: CALL CX . . 10cc5bb: MOVQ 0x208(SP), AX ;index.go:71 . . 10cc5c3: MOVQ 0(AX), CX . . 10cc5c6: MOVQ 0x8(AX), DX . . 10cc5ca: MOVQ 0x38(CX), CX . . 10cc5ce: MOVQ DX, 0(SP) . 70ms 10cc5d2: CALL CX ;main.(*index).nearCount index.go:71 . . 10cc5d4: MOVQ 0x8(SP), AX ;index.go:71 . . 10cc5d9: MOVQ 0x208(SP), CX . . 10cc5e1: MOVQ 0x40(CX), DX . . 10cc5e5: TESTQ DX, DX . . 10cc5e8: JE 0x10cc67c . . 10cc5ee: MOVQ DX, BX . . 10cc5f1: XORL DX, DX . . 10cc5f3: DIVQ BX 10ms 10ms 10cc5f6: MOVQ 0x60(SP), AX ;main.(*index).nearCount index.go:71 . . 10cc5fb: MOVQ 0x50(SP), BX ;index.go:71 . . 10cc600: CMPQ BX, AX . . 10cc603: JB 0x10cc47a . . 10cc609: JMP 0x10cc674 . . 10cc60b: MOVQ R8, 0(SP) ;index.go:127 . . 10cc60f: MOVQ CX, 0x8(SP) . . 10cc614: MOVQ BX, 0x10(SP) . . 10cc619: CALL runtime.memmove(SB) . . 10cc61e: JMP 0x10cc568 . . 10cc623: XORL AX, AX . . 10cc625: XORL DX, DX . . 10cc627: JMP 0x10cc638 ;index.go:75 . . 10cc629: INCQ AX . . 10cc62c: LEAQ 0(R8)(R8*2), SI ;index.go:76 . . 10cc630: MOVQ 0x8(DI)(SI*8), SI 50ms 50ms 10cc635: ADDQ SI, DX ;main.(*index).nearCount index.go:77 10ms 10ms 10cc638: CMPQ BX, AX ;main.(*index).nearCount index.go:75 . . 10cc63b: JGE 0x10cc651 ;index.go:75 . . 10cc63d: MOVQ 0x18(CX), SI ;index.go:76 . . 10cc641: MOVQ 0x10(CX), DI . . 10cc645: MOVQ 0x68(SP)(AX*8), R8 10ms 10ms 10cc64a: CMPQ SI, R8 ;main.(*index).nearCount index.go:76 . . 10cc64d: JB 0x10cc629 ;index.go:76 . . 10cc64f: JMP 0x10cc669 . . 10cc651: MOVQ DX, 0x228(SP) ;index.go:80 . . 10cc659: MOVQ 0x1f8(SP), BP . . 10cc661: ADDQ $0x200, SP . . 10cc668: RET . . 10cc669: MOVQ R8, AX ;index.go:76 . . 10cc66c: MOVQ SI, CX . . 10cc66f: CALL runtime.panicIndexU(SB) . . 10cc674: MOVQ BX, CX ;index.go:71 . . 10cc677: CALL runtime.panicIndex(SB) . . 10cc67c: CALL runtime.panicdivide(SB) . . 10cc681: MOVQ R8, CX ;index.go:125 . . 10cc684: CALL runtime.panicSliceB(SB) . . 10cc689: MOVQ AX, CX ;index.go:124 . . 10cc68c: CALL runtime.panicSliceAcap(SB) . . 10cc691: MOVQ R8, CX ;index.go:65 . . 10cc694: CALL runtime.panicSliceAcap(SB) . . 10cc699: XORL AX, AX ;index.go:64 . . 10cc69b: MOVQ BX, CX . . 10cc69e: CALL runtime.panicIndex(SB) . . 10cc6a3: CALL runtime.panicdivide(SB) . . 10cc6a8: MOVL $0x30, DX ;index.go:61 . . 10cc6ad: CALL runtime.panicSliceAlen(SB) . . 10cc6b2: NOPL . . 10cc6b3: CALL runtime.morestack_noctxt(SB) ;index.go:59 . . 10cc6b8: JMP main.(*index).nearCount(SB) . . 10cc6bd: INT $0x3 . . 10cc6be: INT $0x3 ROUTINE ======================== main.LoadDictionary 60ms 2.87s (flat, cum) 48.98% of Total . . 10c9ce0: MOVQ GS:0x30, CX ;graph.go:39 . . 10c9ce9: LEAQ 0xfffffec0(SP), AX . . 10c9cf1: CMPQ 0x10(CX), AX . . 10c9cf5: JBE 0x10ca44f . . 10c9cfb: SUBQ $0x1c0, SP . . 10c9d02: MOVQ BP, 0x1b8(SP) . . 10c9d0a: LEAQ 0x1b8(SP), BP . . 10c9d12: MOVQ $0x0, 0x1f0(SP) . . 10c9d1e: LEAQ go.string.*+6061(SB), AX ;graph.go:40 . . 10c9d25: MOVQ AX, 0(SP) . . 10c9d29: MOVQ $0xe, 0x8(SP) . . 10c9d32: CALL main.newTimer(SB) . . 10c9d37: MOVQ 0x10(SP), AX . . 10c9d3c: MOVL $0x0, 0x68(SP) . . 10c9d44: MOVQ AX, 0x80(SP) . . 10c9d4c: LEAQ 0x68(SP), AX . . 10c9d51: MOVQ AX, 0(SP) . . 10c9d55: CALL runtime.deferprocStack(SB) . . 10c9d5a: TESTL AX, AX . . 10c9d5c: JNE 0x10ca430 . . 10c9d62: NOPL ;graph.go:41 . . 10c9d63: MOVQ 0x1c8(SP), AX ;file.go:280 . . 10c9d6b: MOVQ AX, 0(SP) . . 10c9d6f: MOVQ 0x1d0(SP), AX . . 10c9d77: MOVQ AX, 0x8(SP) . . 10c9d7c: MOVQ $0x0, 0x10(SP) . . 10c9d85: MOVL $0x0, 0x18(SP) . . 10c9d8d: CALL os.OpenFile(SB) . . 10c9d92: MOVQ 0x20(SP), AX . . 10c9d97: MOVQ AX, 0x118(SP) . . 10c9d9f: MOVQ 0x30(SP), CX . . 10c9da4: MOVQ 0x28(SP), DX . . 10c9da9: TESTQ DX, DX ;graph.go:42 . . 10c9dac: JE 0x10c9df2 . . 10c9dae: JE 0x10c9db4 ;graph.go:43 . . 10c9db0: MOVQ 0x8(DX), DX . . 10c9db4: XORPS X0, X0 . . 10c9db7: MOVUPS X0, 0x128(SP) . . 10c9dbf: MOVQ DX, 0x128(SP) . . 10c9dc7: MOVQ CX, 0x130(SP) . . 10c9dcf: LEAQ 0x128(SP), AX . . 10c9dd7: MOVQ AX, 0(SP) . . 10c9ddb: MOVQ $0x1, 0x8(SP) . . 10c9de4: MOVQ $0x1, 0x10(SP) . . 10c9ded: CALL log.Fatal(SB) . . 10c9df2: MOVL $0x18, 0xa0(SP) ;graph.go:45 . . 10c9dfd: LEAQ go.func.*+289(SB), AX . . 10c9e04: MOVQ AX, 0xb8(SP) . . 10c9e0c: MOVQ 0x118(SP), AX . . 10c9e14: MOVQ AX, 0xd0(SP) . . 10c9e1c: LEAQ 0xa0(SP), CX . . 10c9e24: MOVQ CX, 0(SP) . . 10c9e28: CALL runtime.deferprocStack(SB) . . 10c9e2d: TESTL AX, AX . . 10c9e2f: JNE 0x10ca41a . . 10c9e35: LEAQ type.*+157408(SB), AX ;graph.go:47 . . 10c9e3c: MOVQ AX, 0(SP) . . 10c9e40: CALL runtime.newobject(SB) . . 10c9e45: MOVQ 0x8(SP), AX . . 10c9e4a: MOVQ AX, 0x120(SP) . . 10c9e52: LEAQ type.*+141536(SB), CX ;graph.go:48 . . 10c9e59: MOVQ CX, 0(SP) . . 10c9e5d: XORPS X0, X0 . . 10c9e60: MOVUPS X0, 0x8(SP) . . 10c9e65: CALL runtime.makeslice(SB) . . 10c9e6a: MOVQ 0x18(SP), AX . . 10c9e6f: CMPL $0x0, runtime.writeBarrier(SB) ;graph.go:47 . . 10c9e76: JNE 0x10ca3d5 . . 10c9e7c: XORPS X0, X0 . . 10c9e7f: MOVQ 0x120(SP), CX . . 10c9e87: MOVUPS X0, 0(CX) . . 10c9e8a: MOVUPS X0, 0x10(CX) . . 10c9e8e: MOVUPS X0, 0x20(CX) . . 10c9e92: MOVQ AX, 0(CX) . . 10c9e95: NOPL ;graph.go:53 . . 10c9e96: LEAQ 0x138(SP), DI ;scan.go:87 . . 10c9e9e: MOVQ BP, -0x10(SP) . . 10c9ea3: LEAQ -0x10(SP), BP . . 10c9ea8: CALL 0x10586ba . . 10c9ead: MOVQ 0(BP), BP . . 10c9eb1: LEAQ 0x138(SP), DI . . 10c9eb9: MOVQ BP, -0x10(SP) . . 10c9ebe: LEAQ -0x10(SP), BP . . 10c9ec3: CALL 0x10586ba . . 10c9ec8: MOVQ 0(BP), BP . . 10c9ecc: LEAQ go.itab.*os.File,io.Reader(SB), AX . . 10c9ed3: MOVQ AX, 0x138(SP) . . 10c9edb: MOVQ 0x118(SP), AX . . 10c9ee3: MOVQ AX, 0x140(SP) . . 10c9eeb: LEAQ go.func.*+1(SB), AX . . 10c9ef2: MOVQ AX, 0x148(SP) . . 10c9efa: MOVQ $0x10000, 0x150(SP) . . 10c9f06: XORL AX, AX . . 10c9f08: JMP 0x10c9f0d ;graph.go:54 . . 10c9f0a: MOVQ SI, AX ;graph.go:74 . . 10c9f0d: MOVQ AX, 0x48(SP) . . 10c9f12: LEAQ 0x138(SP), CX ;graph.go:54 . . 10c9f1a: MOVQ CX, 0(SP) . 40ms 10c9f1e: CALL bufio.(*Scanner).Scan(SB) ;main.LoadDictionary graph.go:54 . . 10c9f23: CMPB $0x0, 0x8(SP) ;graph.go:54 . . 10c9f28: JE 0x10ca06b . . 10c9f2e: NOPL ;graph.go:55 . . 10c9f2f: MOVQ 0x160(SP), AX ;scan.go:106 . . 10c9f37: MOVQ AX, 0x40(SP) . . 10c9f3c: MOVQ 0x158(SP), CX . . 10c9f44: MOVQ CX, 0x100(SP) . . 10c9f4c: LEAQ type.*+88864(SB), DX ;graph.go:56 . . 10c9f53: MOVQ DX, 0(SP) . . 10c9f57: MOVQ AX, 0x8(SP) . . 10c9f5c: MOVQ AX, 0x10(SP) . . 10c9f61: CALL runtime.makeslice(SB) . . 10c9f66: MOVQ 0x18(SP), AX . . 10c9f6b: MOVQ AX, 0x110(SP) . . 10c9f73: MOVQ 0x100(SP), CX ;graph.go:57 . . 10c9f7b: CMPQ CX, AX . . 10c9f7e: JE 0x10c9f98 . . 10c9f80: MOVQ AX, 0(SP) . . 10c9f84: MOVQ CX, 0x8(SP) . . 10c9f89: MOVQ 0x40(SP), CX . . 10c9f8e: MOVQ CX, 0x10(SP) . . 10c9f93: CALL runtime.memmove(SB) . . 10c9f98: MOVQ 0x120(SP), CX ;graph.go:58 . . 10c9fa0: MOVQ 0x10(CX), DX . . 10c9fa4: MOVQ 0x8(CX), BX . . 10c9fa8: LEAQ 0x1(BX), SI . . 10c9fac: MOVQ 0(CX), R8 . . 10c9faf: CMPQ DX, SI . . 10c9fb2: JA 0x10ca00b . . 10c9fb4: LEAQ 0x1(BX), DX . . 10c9fb8: MOVQ DX, 0x8(CX) . . 10c9fbc: LEAQ 0(BX)(BX*2), DX . . 10c9fc0: MOVQ 0x40(SP), BX 40ms 40ms 10c9fc5: MOVQ BX, 0x8(R8)(DX*8) ;main.LoadDictionary graph.go:58 . . 10c9fca: MOVQ BX, 0x10(R8)(DX*8) ;graph.go:58 . . 10c9fcf: MOVQ 0x48(SP), SI ;graph.go:59 . . 10c9fd4: CMPQ SI, BX . . 10c9fd7: CMOVG BX, SI ;graph.go:74 . . 10c9fdb: LEAQ 0(R8)(DX*8), DI ;graph.go:58 . . 10c9fdf: CMPL $0x0, runtime.writeBarrier(SB) . . 10c9fe6: JNE 0x10c9ff9 . . 10c9fe8: MOVQ 0x110(SP), AX . . 10c9ff0: MOVQ AX, 0(R8)(DX*8) . . 10c9ff4: JMP 0x10c9f0a . . 10c9ff9: MOVQ 0x110(SP), AX . . 10ca001: CALL runtime.gcWriteBarrier(SB) . . 10ca006: JMP 0x10c9f0a . . 10ca00b: LEAQ type.*+141536(SB), AX . . 10ca012: MOVQ AX, 0(SP) . . 10ca016: MOVQ R8, 0x8(SP) . . 10ca01b: MOVQ BX, 0x10(SP) . . 10ca020: MOVQ DX, 0x18(SP) . . 10ca025: MOVQ SI, 0x20(SP) . 80ms 10ca02a: CALL runtime.growslice(SB) ;main.LoadDictionary graph.go:58 . . 10ca02f: MOVQ 0x28(SP), AX ;graph.go:58 . . 10ca034: MOVQ 0x30(SP), CX . . 10ca039: MOVQ 0x38(SP), DX . . 10ca03e: MOVQ 0x120(SP), DI . . 10ca046: MOVQ DX, 0x10(DI) . . 10ca04a: CMPL $0x0, runtime.writeBarrier(SB) . . 10ca051: JNE 0x10ca064 . . 10ca053: MOVQ AX, 0(DI) . . 10ca056: MOVQ CX, BX . . 10ca059: MOVQ AX, R8 . . 10ca05c: MOVQ DI, CX . . 10ca05f: JMP 0x10c9fb4 . . 10ca064: CALL runtime.gcWriteBarrier(SB) . . 10ca069: JMP 0x10ca056 . . 10ca06b: MOVQ 0x1e8(SP), AX ;graph.go:64 . . 10ca073: TESTQ AX, AX . . 10ca076: JNE 0x10ca377 . . 10ca07c: MOVQ 0x120(SP), AX ;graph.go:68 . . 10ca084: MOVQ 0x8(AX), CX . . 10ca088: MOVQ CX, 0x60(SP) . . 10ca08d: LEAQ type.*+77216(SB), DX . . 10ca094: MOVQ DX, 0(SP) . . 10ca098: MOVQ CX, 0x8(SP) . . 10ca09d: MOVQ CX, 0x10(SP) . . 10ca0a2: CALL runtime.makeslice(SB) . . 10ca0a7: MOVQ 0x18(SP), AX . . 10ca0ac: MOVQ 0x60(SP), CX . . 10ca0b1: MOVQ 0x120(SP), DX . . 10ca0b9: MOVQ CX, 0x20(DX) . . 10ca0bd: MOVQ CX, 0x28(DX) . . 10ca0c1: CMPL $0x0, runtime.writeBarrier(SB) . . 10ca0c8: JNE 0x10ca369 . . 10ca0ce: MOVQ AX, 0x18(DX) . . 10ca0d2: XORL AX, AX . . 10ca0d4: JMP 0x10ca0e5 ;graph.go:69 . . 10ca0d6: LEAQ 0x1(SI), BX . . 10ca0da: MOVQ 0x60(SP), CX 10ms 10ms 10ca0df: MOVQ AX, DX ;main.LoadDictionary graph.go:70 . . 10ca0e2: MOVQ BX, AX ;graph.go:69 . . 10ca0e5: CMPQ CX, AX . . 10ca0e8: JGE 0x10ca166 . . 10ca0ea: MOVQ AX, 0x50(SP) . . 10ca0ef: LEAQ type.*+85856(SB), AX ;graph.go:70 . . 10ca0f6: MOVQ AX, 0(SP) . . 10ca0fa: XORPS X0, X0 . . 10ca0fd: MOVUPS X0, 0x8(SP) . . 10ca102: CALL runtime.makeslice(SB) . . 10ca107: MOVQ 0x120(SP), AX . . 10ca10f: MOVQ 0x20(AX), CX . . 10ca113: MOVQ 0x18(AX), DX . . 10ca117: MOVQ 0x18(SP), BX . . 10ca11c: MOVQ 0x50(SP), SI . . 10ca121: CMPQ CX, SI . . 10ca124: JAE 0x10ca446 . . 10ca12a: LEAQ 0(SI)(SI*2), CX . . 10ca12e: MOVQ $0x0, 0x8(DX)(CX*8) . . 10ca137: MOVQ $0x0, 0x10(DX)(CX*8) . . 10ca140: LEAQ 0(DX)(CX*8), DI . . 10ca144: CMPL $0x0, runtime.writeBarrier(SB) . . 10ca14b: JNE 0x10ca153 . . 10ca14d: MOVQ BX, 0(DX)(CX*8) . . 10ca151: JMP 0x10ca0d6 . . 10ca153: MOVQ AX, CX ;graph.go:47 . . 10ca156: MOVQ BX, AX ;graph.go:70 . . 10ca159: CALL runtime.gcWriteBarrier(SB) . . 10ca15e: MOVQ CX, AX . . 10ca161: JMP 0x10ca0d6 . . 10ca166: LEAQ go.string.*+3453(SB), AX ;graph.go:73 . . 10ca16d: MOVQ AX, 0(SP) . . 10ca171: MOVQ $0xa, 0x8(SP) . . 10ca17a: CALL main.newTimer(SB) . . 10ca17f: MOVQ 0x10(SP), AX . . 10ca184: MOVQ AX, 0xe8(SP) . . 10ca18c: MOVQ $0x800000, 0(SP) ;graph.go:74 . . 10ca194: MOVQ 0x48(SP), CX . . 10ca199: MOVQ CX, 0x8(SP) . 120ms 10ca19e: CALL main.newIndex(SB) ;main.LoadDictionary graph.go:74 . . 10ca1a3: MOVQ 0x10(SP), AX ;graph.go:74 . . 10ca1a8: MOVQ AX, 0xf8(SP) . . 10ca1b0: MOVQ 0x120(SP), CX ;graph.go:75 . . 10ca1b8: MOVQ 0x8(CX), DX . . 10ca1bc: MOVQ 0(CX), BX . . 10ca1bf: TESTQ DX, DX . . 10ca1c2: JLE 0x10ca22b . . 10ca1c4: MOVQ DX, 0x60(SP) . . 10ca1c9: XORL SI, SI . . 10ca1cb: JMP 0x10ca1e4 . . 10ca1cd: MOVQ 0x108(SP), DX . . 10ca1d5: LEAQ 0x18(DX), BX . . 10ca1d9: MOVQ AX, SI . . 10ca1dc: MOVQ 0xf8(SP), AX ;graph.go:76 . . 10ca1e4: MOVQ BX, 0x108(SP) ;graph.go:75 . . 10ca1ec: MOVQ SI, 0x58(SP) . . 10ca1f1: MOVQ 0x8(BX), CX . . 10ca1f5: MOVQ 0(BX), DX . . 10ca1f8: MOVQ 0x10(BX), DI 10ms 10ms 10ca1fc: MOVQ AX, 0(SP) ;main.LoadDictionary graph.go:76 . . 10ca200: MOVQ SI, 0x8(SP) ;graph.go:76 . . 10ca205: MOVQ DX, 0x10(SP) . . 10ca20a: MOVQ CX, 0x18(SP) . . 10ca20f: MOVQ DI, 0x20(SP) . 700ms 10ca214: CALL main.(*index).add(SB) ;main.LoadDictionary graph.go:76 . . 10ca219: MOVQ 0x58(SP), AX ;graph.go:75 . . 10ca21e: INCQ AX . . 10ca221: MOVQ 0x60(SP), CX . . 10ca226: CMPQ CX, AX . . 10ca229: JL 0x10ca1cd . . 10ca22b: MOVQ 0xe8(SP), DX ;graph.go:78 . . 10ca233: MOVQ 0(DX), AX . . 10ca236: CALL AX . . 10ca238: MOVZX 0x1d8(SP), AX ;graph.go:39 . . 10ca240: TESTL AL, AL . . 10ca242: JNE 0x10ca353 ;graph.go:80 . . 10ca248: LEAQ go.string.*+4782(SB), AX ;graph.go:87 . . 10ca24f: MOVQ AX, 0(SP) . . 10ca253: MOVQ $0xc, 0x8(SP) . . 10ca25c: CALL main.newTimer(SB) . . 10ca261: MOVQ 0x10(SP), AX . . 10ca266: MOVQ AX, 0xf0(SP) . . 10ca26e: MOVQ 0x120(SP), CX ;graph.go:88 . . 10ca276: MOVQ CX, 0(SP) . . 10ca27a: MOVQ 0xf8(SP), DX . . 10ca282: MOVQ DX, 0x8(SP) . 1.87s 10ca287: CALL main.(*Graph).buildAdjList(SB) ;main.LoadDictionary graph.go:88 . . 10ca28c: MOVQ 0xf0(SP), DX ;graph.go:89 . . 10ca294: MOVQ 0(DX), AX . . 10ca297: CALL AX . . 10ca299: MOVQ 0x1e8(SP), AX ;graph.go:64 . . 10ca2a1: TESTQ AX, AX . . 10ca2a4: JNE 0x10ca2eb ;graph.go:91 . . 10ca2a6: MOVZX 0x1d8(SP), AX ;graph.go:39 . . 10ca2ae: TESTL AL, AL . . 10ca2b0: JNE 0x10ca2d8 ;graph.go:95 . . 10ca2b2: MOVQ 0x120(SP), AX ;graph.go:99 . . 10ca2ba: MOVQ AX, 0x1f0(SP) . . 10ca2c2: NOPL . . 10ca2c3: CALL runtime.deferreturn(SB) . . 10ca2c8: MOVQ 0x1b8(SP), BP . . 10ca2d0: ADDQ $0x1c0, SP . . 10ca2d7: RET . . 10ca2d8: MOVQ 0x120(SP), AX ;graph.go:96 . . 10ca2e0: MOVQ AX, 0(SP) . . 10ca2e4: CALL main.adjListStats(SB) . . 10ca2e9: JMP 0x10ca2b2 . . 10ca2eb: MOVQ $0x0, 0(SP) ;graph.go:92 . . 10ca2f3: MOVQ 0x1e0(SP), CX . . 10ca2fb: MOVQ CX, 0x8(SP) . . 10ca300: MOVQ AX, 0x10(SP) . . 10ca305: LEAQ go.string.*+2067(SB), AX . . 10ca30c: MOVQ AX, 0x18(SP) . . 10ca311: MOVQ $0x8, 0x20(SP) . . 10ca31a: CALL runtime.concatstring2(SB) . . 10ca31f: MOVQ 0x28(SP), AX . . 10ca324: MOVQ 0x30(SP), CX . . 10ca329: MOVQ 0x120(SP), DX . . 10ca331: MOVQ DX, 0(SP) . . 10ca335: MOVQ AX, 0x8(SP) . . 10ca33a: MOVQ CX, 0x10(SP) . . 10ca33f: CALL main.(*Graph).dumpAdjList(SB) . . 10ca344: MOVZX 0x1d8(SP), AX ;graph.go:39 . . 10ca34c: TESTL AL, AL . . 10ca34e: JMP 0x10ca2b0 ;graph.go:92 . . 10ca353: MOVQ 0xf8(SP), AX ;graph.go:81 . . 10ca35b: MOVQ AX, 0(SP) . . 10ca35f: CALL main.(*index).printStats(SB) . . 10ca364: JMP 0x10ca248 ;graph.go:87 . . 10ca369: LEAQ 0x18(DX), DI ;graph.go:68 . . 10ca36d: CALL runtime.gcWriteBarrier(SB) . . 10ca372: JMP 0x10ca0d2 . . 10ca377: MOVQ $0x0, 0(SP) ;graph.go:65 . . 10ca37f: MOVQ 0x1e0(SP), CX . . 10ca387: MOVQ CX, 0x8(SP) . . 10ca38c: MOVQ AX, 0x10(SP) . . 10ca391: LEAQ go.string.*+5422(SB), DX . . 10ca398: MOVQ DX, 0x18(SP) . . 10ca39d: MOVQ $0xd, 0x20(SP) . . 10ca3a6: CALL runtime.concatstring2(SB) . . 10ca3ab: MOVQ 0x30(SP), AX . . 10ca3b0: MOVQ 0x28(SP), CX . . 10ca3b5: MOVQ 0x120(SP), DX . . 10ca3bd: MOVQ DX, 0(SP) . . 10ca3c1: MOVQ CX, 0x8(SP) . . 10ca3c6: MOVQ AX, 0x10(SP) . . 10ca3cb: CALL main.(*Graph).dumpVertices(SB) . . 10ca3d0: JMP 0x10ca07c . . 10ca3d5: MOVQ AX, 0x110(SP) ;graph.go:48 . . 10ca3dd: LEAQ type.*+157408(SB), AX ;graph.go:47 . . 10ca3e4: MOVQ AX, 0(SP) . . 10ca3e8: MOVQ 0x120(SP), AX . . 10ca3f0: MOVQ AX, 0x8(SP) . . 10ca3f5: CALL runtime.typedmemclr(SB) . . 10ca3fa: MOVQ 0x120(SP), DI . . 10ca402: MOVQ 0x110(SP), AX . . 10ca40a: CALL runtime.gcWriteBarrier(SB) . . 10ca40f: MOVQ DI, CX ;graph.go:68 . . 10ca412: XORPS X0, X0 ;graph.go:48 . . 10ca415: JMP 0x10c9e95 ;graph.go:47 . . 10ca41a: NOPL ;graph.go:45 . . 10ca41b: CALL runtime.deferreturn(SB) . . 10ca420: MOVQ 0x1b8(SP), BP . . 10ca428: ADDQ $0x1c0, SP . . 10ca42f: RET . . 10ca430: NOPL ;graph.go:40 . . 10ca431: CALL runtime.deferreturn(SB) . . 10ca436: MOVQ 0x1b8(SP), BP . . 10ca43e: ADDQ $0x1c0, SP . . 10ca445: RET . . 10ca446: MOVQ SI, AX ;graph.go:70 . . 10ca449: CALL runtime.panicIndex(SB) . . 10ca44e: NOPL . . 10ca44f: CALL runtime.morestack_noctxt(SB) ;graph.go:39 . . 10ca454: JMP main.LoadDictionary(SB) . . 10ca459: INT $0x3 . . 10ca45a: INT $0x3 . . 10ca45b: INT $0x3 . . 10ca45c: INT $0x3 . . 10ca45d: INT $0x3 . . 10ca45e: INT $0x3 ROUTINE ======================== main.distance 140ms 140ms (flat, cum) 2.39% of Total . . 10cb0c0: SUBQ $0x18, SP ;graph.go:284 . . 10cb0c4: MOVQ BP, 0x10(SP) . . 10cb0c9: LEAQ 0x10(SP), BP . . 10cb0ce: MOVQ 0x28(SP), CX ;graph.go:290 . . 10cb0d3: MOVQ 0x40(SP), DX . . 10cb0d8: CMPQ DX, CX 20ms 20ms 10cb0db: MOVQ CX, BX ;main.distance graph.go:293 . . 10cb0de: CMOVG DX, CX ;graph.go:293 . . 10cb0e2: MOVQ BX, SI ;graph.go:285 . . 10cb0e5: SUBQ DX, BX . . 10cb0e8: MOVQ DX, DI ;graph.go:287 . . 10cb0eb: SUBQ SI, DX . . 10cb0ee: TESTQ BX, BX ;graph.go:286 . . 10cb0f1: CMOVL DX, BX ;graph.go:295 10ms 10ms 10cb0f5: MOVQ 0x38(SP), DX ;main.distance graph.go:286 . . 10cb0fa: MOVQ 0x20(SP), R8 ;graph.go:286 . . 10cb0ff: XORL AX, AX . . 10cb101: JMP 0x10cb116 . . 10cb103: MOVZX 0(DX)(AX*1), R10 ;graph.go:294 80ms 80ms 10cb108: LEAQ 0x1(BX), R11 ;main.distance graph.go:295 . . 10cb10c: CMPL R10, R9 ;graph.go:294 20ms 20ms 10cb10f: CMOVNE R11, BX ;main.distance graph.go:295 . . 10cb113: INCQ AX ;graph.go:293 . . 10cb116: CMPQ CX, AX . . 10cb119: JGE 0x10cb12c . . 10cb11b: CMPQ SI, AX ;graph.go:294 . . 10cb11e: JAE 0x10cb143 . . 10cb120: MOVZX 0(R8)(AX*1), R9 10ms 10ms 10cb125: CMPQ DI, AX ;main.distance graph.go:294 . . 10cb128: JB 0x10cb103 ;graph.go:294 . . 10cb12a: JMP 0x10cb13b . . 10cb12c: MOVQ BX, 0x50(SP) ;graph.go:299 . . 10cb131: MOVQ 0x10(SP), BP . . 10cb136: ADDQ $0x18, SP . . 10cb13a: RET . . 10cb13b: MOVQ DI, CX ;graph.go:294 . . 10cb13e: CALL runtime.panicIndex(SB) . . 10cb143: MOVQ SI, CX . . 10cb146: CALL runtime.panicIndex(SB) . . 10cb14b: NOPL . . 10cb14c: INT $0x3 . . 10cb14d: INT $0x3 . . 10cb14e: INT $0x3 ROUTINE ======================== main.main 0 2.91s (flat, cum) 49.66% of Total . . 10cd380: MOVQ GS:0x30, CX ;main.go:24 . . 10cd389: LEAQ 0xfffffd98(SP), AX . . 10cd391: CMPQ 0x10(CX), AX . . 10cd395: JBE 0x10ce07f . . 10cd39b: SUBQ $0x2e8, SP . . 10cd3a2: MOVQ BP, 0x2e0(SP) . . 10cd3aa: LEAQ 0x2e0(SP), BP . . 10cd3b2: MOVQ os.Args+8(SB), CX ;main.go:25 . . 10cd3b9: MOVQ os.Args(SB), DX ;flag.go:996 . . 10cd3c0: MOVQ os.Args+16(SB), BX . . 10cd3c7: CMPQ $0x1, CX . . 10cd3cb: JB 0x10ce074 . . 10cd3d1: MOVQ flag.CommandLine(SB), AX . . 10cd3d8: MOVQ AX, 0(SP) . . 10cd3dc: LEAQ -0x1(BX), AX . . 10cd3e0: MOVQ AX, BX . . 10cd3e3: NEGQ AX . . 10cd3e6: SARQ $0x3f, AX . . 10cd3ea: ANDQ $0x10, AX . . 10cd3ee: ADDQ DX, AX . . 10cd3f1: MOVQ AX, 0x8(SP) . . 10cd3f6: LEAQ -0x1(CX), AX . . 10cd3fa: MOVQ AX, 0x10(SP) . . 10cd3ff: MOVQ BX, 0x18(SP) . . 10cd404: CALL flag.(*FlagSet).Parse(SB) . . 10cd409: MOVQ main.cpuprofile(SB), AX ;main.go:27 . . 10cd410: MOVQ 0(AX), CX . . 10cd413: MOVQ 0x8(AX), AX . . 10cd417: TESTQ AX, AX . . 10cd41a: JNE 0x10cdf17 . . 10cd420: MOVQ main.traceprofile(SB), AX ;main.go:37 . . 10cd427: MOVQ 0(AX), CX . . 10cd42a: MOVQ 0x8(AX), AX . . 10cd42e: TESTQ AX, AX . . 10cd431: JNE 0x10cddb5 . . 10cd437: MOVQ main.dump(SB), AX ;main.go:47 . . 10cd43e: MOVQ 0x8(AX), CX . . 10cd442: MOVQ 0(AX), AX . . 10cd445: TESTQ CX, CX . . 10cd448: JNE 0x10cdda2 . . 10cd44e: XORPS X0, X0 ;main.go:51 . . 10cd451: MOVUPS X0, 0x250(SP) . . 10cd459: LEAQ type.*+88544(SB), AX . . 10cd460: MOVQ AX, 0x250(SP) . . 10cd468: LEAQ internal/bytealg.IndexString.args_stackmap+640(SB), CX . . 10cd46f: MOVQ CX, 0x258(SP) . . 10cd477: MOVQ os.Stdout(SB), CX ;print.go:274 . . 10cd47e: LEAQ go.itab.*os.File,io.Writer(SB), DX . . 10cd485: MOVQ DX, 0(SP) . . 10cd489: MOVQ CX, 0x8(SP) . . 10cd48e: LEAQ 0x250(SP), CX . . 10cd496: MOVQ CX, 0x10(SP) . . 10cd49b: MOVQ $0x1, 0x18(SP) . . 10cd4a4: MOVQ $0x1, 0x20(SP) . . 10cd4ad: CALL fmt.Fprintln(SB) . . 10cd4b2: MOVQ main.dict(SB), AX ;main.go:52 . . 10cd4b9: MOVQ main.perfStats(SB), CX . . 10cd4c0: MOVQ main.dump(SB), DX . . 10cd4c7: MOVQ 0x8(AX), BX . . 10cd4cb: MOVQ 0(AX), AX . . 10cd4ce: MOVZX 0(CX), CX . . 10cd4d1: MOVQ 0(DX), SI . . 10cd4d4: MOVQ 0x8(DX), DX . . 10cd4d8: MOVQ AX, 0(SP) . . 10cd4dc: MOVQ BX, 0x8(SP) . . 10cd4e1: MOVB CL, 0x10(SP) . . 10cd4e5: MOVQ SI, 0x18(SP) . . 10cd4ea: MOVQ DX, 0x20(SP) . 2.87s 10cd4ef: CALL main.LoadDictionary(SB) ;main.main main.go:52 . . 10cd4f4: MOVQ 0x28(SP), AX ;main.go:52 . . 10cd4f9: MOVQ AX, 0x1d0(SP) . . 10cd501: MOVQ 0x8(AX), CX ;graph.go:304 . . 10cd505: MOVQ CX, 0x78(SP) . . 10cd50a: MOVQ AX, 0(SP) ;main.go:53 . 10ms 10cd50e: CALL main.(*Graph).EdgeCount(SB) ;main.main main.go:53 . . 10cd513: MOVQ 0x8(SP), AX ;main.go:53 . . 10cd518: MOVQ AX, 0x70(SP) . . 10cd51d: MOVQ 0x78(SP), CX . . 10cd522: MOVQ CX, 0(SP) . . 10cd526: CALL runtime.convT64(SB) . . 10cd52b: MOVQ 0x8(SP), AX . . 10cd530: MOVQ AX, 0x1f8(SP) . . 10cd538: MOVQ 0x70(SP), CX . . 10cd53d: MOVQ CX, 0(SP) . . 10cd541: CALL runtime.convT64(SB) . . 10cd546: MOVQ 0x8(SP), AX . . 10cd54b: XORPS X0, X0 . . 10cd54e: MOVUPS X0, 0x2c0(SP) . . 10cd556: MOVUPS X0, 0x2d0(SP) . . 10cd55e: LEAQ type.*+85856(SB), CX . . 10cd565: MOVQ CX, 0x2c0(SP) . . 10cd56d: MOVQ 0x1f8(SP), DX . . 10cd575: MOVQ DX, 0x2c8(SP) . . 10cd57d: MOVQ CX, 0x2d0(SP) . . 10cd585: MOVQ AX, 0x2d8(SP) . . 10cd58d: MOVQ os.Stdout(SB), AX ;print.go:213 . . 10cd594: LEAQ go.itab.*os.File,io.Writer(SB), CX . . 10cd59b: MOVQ CX, 0(SP) . . 10cd59f: MOVQ AX, 0x8(SP) . . 10cd5a4: LEAQ go.string.*+11013(SB), AX . . 10cd5ab: MOVQ AX, 0x10(SP) . . 10cd5b0: MOVQ $0x14, 0x18(SP) . . 10cd5b9: LEAQ 0x2c0(SP), AX . . 10cd5c1: MOVQ AX, 0x20(SP) . . 10cd5c6: MOVQ $0x2, 0x28(SP) . . 10cd5cf: MOVQ $0x2, 0x30(SP) . . 10cd5d8: CALL fmt.Fprintf(SB) . . 10cd5dd: MOVQ main.dictStats(SB), AX ;main.go:55 . . 10cd5e4: CMPB $0x0, 0(AX) . . 10cd5e7: JNE 0x10cdd81 . . 10cd5ed: MOVQ main.src(SB), AX ;main.go:59 . . 10cd5f4: MOVQ 0(AX), CX . . 10cd5f7: MOVQ 0x8(AX), AX . . 10cd5fb: TESTQ AX, AX . . 10cd5fe: JE 0x10cd612 . . 10cd600: MOVQ main.dest(SB), DX . . 10cd607: CMPQ $0x0, 0x8(DX) . . 10cd60c: JNE 0x10cd81e . . 10cd612: MOVQ main.printGraph(SB), AX ;main.go:83 . . 10cd619: CMPB $0x0, 0(AX) . . 10cd61c: JNE 0x10cd808 . . 10cd622: MOVQ main.memprofile(SB), AX ;main.go:87 . . 10cd629: CMPQ $0x0, 0x8(AX) . . 10cd62e: JNE 0x10cd646 . . 10cd630: NOPL ;main.go:98 . . 10cd631: CALL runtime.deferreturn(SB) . . 10cd636: MOVQ 0x2e0(SP), BP . . 10cd63e: ADDQ $0x2e8, SP . . 10cd645: RET . . 10cd646: CALL runtime.GC(SB) ;main.go:88 . . 10cd64b: MOVQ main.memprofile(SB), AX ;main.go:89 . . 10cd652: MOVQ 0(AX), CX . . 10cd655: MOVQ 0x8(AX), AX . . 10cd659: MOVQ CX, 0(SP) ;file.go:289 . . 10cd65d: MOVQ AX, 0x8(SP) . . 10cd662: MOVQ $0x602, 0x10(SP) . . 10cd66b: MOVL $0x1b6, 0x18(SP) . . 10cd673: CALL os.OpenFile(SB) . . 10cd678: MOVQ 0x20(SP), AX . . 10cd67d: MOVQ AX, 0x1f0(SP) . . 10cd685: MOVQ 0x28(SP), CX . . 10cd68a: MOVQ 0x30(SP), DX . . 10cd68f: TESTQ CX, CX ;main.go:90 . . 10cd692: JE 0x10cd6fe . . 10cd694: JE 0x10cd69a ;main.go:91 . . 10cd696: MOVQ 0x8(CX), CX . . 10cd69a: XORPS X0, X0 . . 10cd69d: MOVUPS X0, 0x260(SP) . . 10cd6a5: MOVUPS X0, 0x270(SP) . . 10cd6ad: LEAQ type.*+88544(SB), AX . . 10cd6b4: MOVQ AX, 0x260(SP) . . 10cd6bc: LEAQ internal/bytealg.IndexString.args_stackmap+672(SB), BX . . 10cd6c3: MOVQ BX, 0x268(SP) . . 10cd6cb: MOVQ CX, 0x270(SP) . . 10cd6d3: MOVQ DX, 0x278(SP) . . 10cd6db: LEAQ 0x260(SP), CX . . 10cd6e3: MOVQ CX, 0(SP) . . 10cd6e7: MOVQ $0x2, 0x8(SP) . . 10cd6f0: MOVQ $0x2, 0x10(SP) . . 10cd6f9: CALL log.Fatal(SB) . . 10cd6fe: MOVL $0x18, 0xf0(SP) ;main.go:93 . . 10cd709: LEAQ go.func.*+289(SB), AX . . 10cd710: MOVQ AX, 0x108(SP) . . 10cd718: MOVQ 0x1f0(SP), AX . . 10cd720: MOVQ AX, 0x120(SP) . . 10cd728: LEAQ 0xf0(SP), CX . . 10cd730: MOVQ CX, 0(SP) . . 10cd734: CALL runtime.deferprocStack(SB) . . 10cd739: TESTL AX, AX . . 10cd73b: JNE 0x10cd7f2 . 10ms 10cd741: NOPL ;runtime/pprof.WriteHeapProfile pprof.go:522 . . 10cd742: LEAQ go.itab.*os.File,io.Writer(SB), AX ;pprof.go:533 . . 10cd749: MOVQ AX, 0(SP) . . 10cd74d: MOVQ 0x1f0(SP), AX . . 10cd755: MOVQ AX, 0x8(SP) . . 10cd75a: MOVQ $0x0, 0x10(SP) . . 10cd763: XORPS X0, X0 . . 10cd766: MOVUPS X0, 0x18(SP) ;runtime/pprof.writeHeap pprof.go:533 . 10ms 10cd76b: CALL runtime/pprof.writeHeapInternal(SB) . . 10cd770: MOVQ 0x28(SP), AX ;pprof.go:533 . . 10cd775: MOVQ 0x30(SP), CX . 10ms 10cd77a: TESTQ AX, AX ;main.main main.go:94 . . 10cd77d: JE 0x10cd630 ;main.go:94 . . 10cd783: JE 0x10cd789 ;main.go:95 . . 10cd785: MOVQ 0x8(AX), AX . . 10cd789: XORPS X0, X0 . . 10cd78c: MOVUPS X0, 0x260(SP) . . 10cd794: MOVUPS X0, 0x270(SP) . . 10cd79c: LEAQ type.*+88544(SB), DX . . 10cd7a3: MOVQ DX, 0x260(SP) . . 10cd7ab: LEAQ internal/bytealg.IndexString.args_stackmap+688(SB), DX . . 10cd7b2: MOVQ DX, 0x268(SP) . . 10cd7ba: MOVQ AX, 0x270(SP) . . 10cd7c2: MOVQ CX, 0x278(SP) . . 10cd7ca: LEAQ 0x260(SP), AX . . 10cd7d2: MOVQ AX, 0(SP) . . 10cd7d6: MOVQ $0x2, 0x8(SP) . . 10cd7df: MOVQ $0x2, 0x10(SP) . . 10cd7e8: CALL log.Fatal(SB) . . 10cd7ed: JMP 0x10cd630 . . 10cd7f2: NOPL ;main.go:93 . . 10cd7f3: CALL runtime.deferreturn(SB) . . 10cd7f8: MOVQ 0x2e0(SP), BP . . 10cd800: ADDQ $0x2e8, SP . . 10cd807: RET . . 10cd808: MOVQ 0x1d0(SP), AX ;main.go:84 . . 10cd810: MOVQ AX, 0(SP) . . 10cd814: CALL main.(*Graph).PrintAdjList(SB) . . 10cd819: JMP 0x10cd622 . . 10cd81e: MOVQ CX, 0(SP) ;main.go:60 . . 10cd822: MOVQ AX, 0x8(SP) . . 10cd827: CALL runtime.convTstring(SB) . . 10cd82c: MOVQ main.dest(SB), AX . . 10cd833: MOVQ 0x10(SP), CX . . 10cd838: MOVQ CX, 0x1f8(SP) . . 10cd840: MOVQ 0(AX), DX . . 10cd843: MOVQ 0x8(AX), AX . . 10cd847: MOVQ DX, 0(SP) . . 10cd84b: MOVQ AX, 0x8(SP) . . 10cd850: CALL runtime.convTstring(SB) . . 10cd855: MOVQ 0x10(SP), AX . . 10cd85a: XORPS X0, X0 . . 10cd85d: MOVUPS X0, 0x2a0(SP) . . 10cd865: MOVUPS X0, 0x2b0(SP) . . 10cd86d: LEAQ type.*+88544(SB), CX . . 10cd874: MOVQ CX, 0x2a0(SP) . . 10cd87c: MOVQ 0x1f8(SP), DX . . 10cd884: MOVQ DX, 0x2a8(SP) . . 10cd88c: MOVQ CX, 0x2b0(SP) . . 10cd894: MOVQ AX, 0x2b8(SP) . . 10cd89c: MOVQ os.Stdout(SB), AX ;print.go:213 . . 10cd8a3: LEAQ go.itab.*os.File,io.Writer(SB), DX . . 10cd8aa: MOVQ DX, 0(SP) . . 10cd8ae: MOVQ AX, 0x8(SP) . . 10cd8b3: LEAQ go.string.*+16282(SB), AX . . 10cd8ba: MOVQ AX, 0x10(SP) . . 10cd8bf: MOVQ $0x1b, 0x18(SP) . . 10cd8c8: LEAQ 0x2a0(SP), AX . . 10cd8d0: MOVQ AX, 0x20(SP) . . 10cd8d5: MOVQ $0x2, 0x28(SP) . . 10cd8de: MOVQ $0x2, 0x30(SP) . . 10cd8e7: CALL fmt.Fprintf(SB) . . 10cd8ec: MOVQ main.src(SB), AX ;main.go:61 . . 10cd8f3: MOVQ 0x8(AX), CX . . 10cd8f7: MOVQ 0(AX), AX . . 10cd8fa: MOVQ 0x1d0(SP), DX . . 10cd902: MOVQ DX, 0(SP) . . 10cd906: MOVQ AX, 0x8(SP) . . 10cd90b: MOVQ CX, 0x10(SP) . . 10cd910: CALL main.(*Graph).Find(SB) . . 10cd915: MOVQ main.dest(SB), AX ;main.go:62 . . 10cd91c: MOVQ 0x18(SP), CX ;main.go:61 . . 10cd921: MOVQ CX, 0x58(SP) . . 10cd926: MOVQ 0x8(AX), DX ;main.go:62 . . 10cd92a: MOVQ 0(AX), AX . . 10cd92d: MOVQ 0x1d0(SP), BX . . 10cd935: MOVQ BX, 0(SP) . . 10cd939: MOVQ AX, 0x8(SP) . . 10cd93e: MOVQ DX, 0x10(SP) . . 10cd943: CALL main.(*Graph).Find(SB) . . 10cd948: MOVQ 0x18(SP), AX . . 10cd94d: MOVQ 0x58(SP), CX ;main.go:64 . . 10cd952: TESTQ CX, CX . . 10cd955: JL 0x10cdc26 . . 10cd95b: TESTQ AX, AX . . 10cd95e: JL 0x10cdc23 . . 10cd964: XORPS X0, X0 ;main.go:74 . . 10cd967: MOVUPS X0, 0x220(SP) . . 10cd96f: LEAQ type.*+88544(SB), AX . . 10cd976: MOVQ AX, 0x220(SP) . . 10cd97e: LEAQ internal/bytealg.IndexString.args_stackmap+656(SB), CX . . 10cd985: MOVQ CX, 0x228(SP) . . 10cd98d: MOVQ os.Stdout(SB), CX ;print.go:274 . . 10cd994: LEAQ go.itab.*os.File,io.Writer(SB), DX . . 10cd99b: MOVQ DX, 0(SP) . . 10cd99f: MOVQ CX, 0x8(SP) . . 10cd9a4: LEAQ 0x220(SP), CX . . 10cd9ac: MOVQ CX, 0x10(SP) . . 10cd9b1: MOVQ $0x1, 0x18(SP) . . 10cd9ba: MOVQ $0x1, 0x20(SP) . . 10cd9c3: CALL fmt.Fprintln(SB) . . 10cd9c8: MOVQ 0x1d0(SP), AX ;main.go:75 . . 10cd9d0: MOVQ AX, 0(SP) . . 10cd9d4: MOVQ 0x58(SP), CX . . 10cd9d9: MOVQ CX, 0x8(SP) . . 10cd9de: CALL main.(*Graph).AllPaths(SB) . . 10cd9e3: MOVQ main.dest(SB), AX ;main.go:76 . . 10cd9ea: MOVQ 0x10(SP), CX ;main.go:75 . . 10cd9ef: MOVQ 0x8(AX), DX ;main.go:76 . . 10cd9f3: MOVQ 0(AX), AX . . 10cd9f6: MOVQ CX, 0(SP) . . 10cd9fa: MOVQ AX, 0x8(SP) . . 10cd9ff: MOVQ DX, 0x10(SP) . . 10cda04: CALL main.(*Paths).To(SB) . . 10cda09: MOVQ 0x18(SP), AX . . 10cda0e: MOVQ AX, 0x1c8(SP) . . 10cda16: MOVQ 0x20(SP), CX . . 10cda1b: MOVQ CX, 0x60(SP) . . 10cda20: TESTQ CX, CX ;main.go:77 . . 10cda23: JE 0x10cdb35 . . 10cda29: MOVQ 0x1d0(SP), DX ;main.go:80 . . 10cda31: XORL BX, BX . . 10cda33: JMP 0x10cdb13 . . 10cda38: MOVQ BX, 0x78(SP) . . 10cda3d: LEAQ 0(SI)(SI*2), AX ;main.go:81 . . 10cda41: MOVQ 0x10(R8)(AX*8), CX . . 10cda46: MOVQ 0(R8)(AX*8), DX . . 10cda4a: MOVQ 0x8(R8)(AX*8), AX . . 10cda4f: MOVQ $0x0, 0(SP) . . 10cda57: MOVQ DX, 0x8(SP) . . 10cda5c: MOVQ AX, 0x10(SP) . . 10cda61: MOVQ CX, 0x18(SP) . . 10cda66: CALL runtime.slicebytetostring(SB) . . 10cda6b: MOVQ 0x28(SP), AX . . 10cda70: MOVQ 0x20(SP), CX . . 10cda75: MOVQ CX, 0(SP) . . 10cda79: MOVQ AX, 0x8(SP) . . 10cda7e: CALL runtime.convTstring(SB) . . 10cda83: MOVQ 0x10(SP), AX . . 10cda88: XORPS X0, X0 . . 10cda8b: MOVUPS X0, 0x210(SP) . . 10cda93: LEAQ type.*+88544(SB), CX . . 10cda9a: MOVQ CX, 0x210(SP) . . 10cdaa2: MOVQ AX, 0x218(SP) . . 10cdaaa: MOVQ os.Stdout(SB), AX ;print.go:274 . . 10cdab1: LEAQ go.itab.*os.File,io.Writer(SB), DX . . 10cdab8: MOVQ DX, 0(SP) . . 10cdabc: MOVQ AX, 0x8(SP) . . 10cdac1: LEAQ 0x210(SP), AX . . 10cdac9: MOVQ AX, 0x10(SP) . . 10cdace: MOVQ $0x1, 0x18(SP) . . 10cdad7: MOVQ $0x1, 0x20(SP) . . 10cdae0: CALL fmt.Fprintln(SB) . . 10cdae5: MOVQ 0x78(SP), AX ;main.go:80 . . 10cdaea: LEAQ 0x1(AX), BX . . 10cdaee: MOVQ 0x60(SP), AX . . 10cdaf3: MOVQ 0x1d0(SP), CX . . 10cdafb: MOVQ 0x1c8(SP), DX . . 10cdb03: MOVQ DX, AX . . 10cdb06: MOVQ 0x60(SP), CX . . 10cdb0b: MOVQ 0x1d0(SP), DX ;main.go:81 . . 10cdb13: CMPQ CX, BX ;main.go:80 . . 10cdb16: JGE 0x10cd622 . . 10cdb1c: MOVQ 0(AX)(BX*8), SI . . 10cdb20: MOVQ 0x8(DX), DI ;main.go:81 . . 10cdb24: MOVQ 0(DX), R8 . . 10cdb27: CMPQ DI, SI . . 10cdb2a: JB 0x10cda38 . . 10cdb30: JMP 0x10ce069 . . 10cdb35: MOVQ main.src(SB), AX ;main.go:78 . . 10cdb3c: MOVQ 0x8(AX), CX . . 10cdb40: MOVQ 0(AX), AX . . 10cdb43: MOVQ AX, 0(SP) . . 10cdb47: MOVQ CX, 0x8(SP) . . 10cdb4c: CALL runtime.convTstring(SB) . . 10cdb51: MOVQ main.dest(SB), AX . . 10cdb58: MOVQ 0x10(SP), CX . . 10cdb5d: MOVQ CX, 0x1f8(SP) . . 10cdb65: MOVQ 0x8(AX), DX . . 10cdb69: MOVQ 0(AX), AX . . 10cdb6c: MOVQ AX, 0(SP) . . 10cdb70: MOVQ DX, 0x8(SP) . . 10cdb75: CALL runtime.convTstring(SB) . . 10cdb7a: MOVQ 0x10(SP), AX . . 10cdb7f: XORPS X0, X0 . . 10cdb82: MOVUPS X0, 0x280(SP) . . 10cdb8a: MOVUPS X0, 0x290(SP) . . 10cdb92: LEAQ type.*+88544(SB), CX . . 10cdb99: MOVQ CX, 0x280(SP) . . 10cdba1: MOVQ 0x1f8(SP), DX . . 10cdba9: MOVQ DX, 0x288(SP) . . 10cdbb1: MOVQ CX, 0x290(SP) . . 10cdbb9: MOVQ AX, 0x298(SP) . . 10cdbc1: MOVQ os.Stdout(SB), AX ;print.go:213 . . 10cdbc8: LEAQ go.itab.*os.File,io.Writer(SB), DX . . 10cdbcf: MOVQ DX, 0(SP) . . 10cdbd3: MOVQ AX, 0x8(SP) . . 10cdbd8: LEAQ go.string.*+20048(SB), AX . . 10cdbdf: MOVQ AX, 0x10(SP) . . 10cdbe4: MOVQ $0x1f, 0x18(SP) . . 10cdbed: LEAQ 0x280(SP), AX . . 10cdbf5: MOVQ AX, 0x20(SP) . . 10cdbfa: MOVQ $0x2, 0x28(SP) . . 10cdc03: MOVQ $0x2, 0x30(SP) . . 10cdc0c: CALL fmt.Fprintf(SB) . . 10cdc11: MOVQ 0x1c8(SP), AX ;main.go:80 . . 10cdc19: MOVQ 0x60(SP), CX . . 10cdc1e: JMP 0x10cda29 . . 10cdc23: TESTQ CX, CX ;main.go:64 . . 10cdc26: JL 0x10cdcdf ;main.go:65 . . 10cdc2c: TESTQ AX, AX ;main.go:68 . . 10cdc2f: JL 0x10cdc47 . . 10cdc31: NOPL ;main.go:71 . . 10cdc32: CALL runtime.deferreturn(SB) . . 10cdc37: MOVQ 0x2e0(SP), BP . . 10cdc3f: ADDQ $0x2e8, SP . . 10cdc46: RET . . 10cdc47: MOVQ main.dest(SB), AX ;main.go:69 . . 10cdc4e: MOVQ 0(AX), CX . . 10cdc51: MOVQ 0x8(AX), AX . . 10cdc55: MOVQ CX, 0(SP) . . 10cdc59: MOVQ AX, 0x8(SP) . . 10cdc5e: CALL runtime.convTstring(SB) . . 10cdc63: MOVQ 0x10(SP), AX . . 10cdc68: XORPS X0, X0 . . 10cdc6b: MOVUPS X0, 0x230(SP) . . 10cdc73: LEAQ type.*+88544(SB), CX . . 10cdc7a: MOVQ CX, 0x230(SP) . . 10cdc82: MOVQ AX, 0x238(SP) . . 10cdc8a: MOVQ os.Stdout(SB), AX ;print.go:213 . . 10cdc91: LEAQ go.itab.*os.File,io.Writer(SB), CX . . 10cdc98: MOVQ CX, 0(SP) . . 10cdc9c: MOVQ AX, 0x8(SP) . . 10cdca1: LEAQ go.string.*+7928(SB), AX . . 10cdca8: MOVQ AX, 0x10(SP) . . 10cdcad: MOVQ $0x11, 0x18(SP) . . 10cdcb6: LEAQ 0x230(SP), AX . . 10cdcbe: MOVQ AX, 0x20(SP) . . 10cdcc3: MOVQ $0x1, 0x28(SP) . . 10cdccc: MOVQ $0x1, 0x30(SP) . . 10cdcd5: CALL fmt.Fprintf(SB) . . 10cdcda: JMP 0x10cdc31 ;main.go:71 . . 10cdcdf: MOVQ AX, 0x50(SP) ;main.go:62 . . 10cdce4: MOVQ main.src(SB), AX ;main.go:66 . . 10cdceb: MOVQ 0x8(AX), CX . . 10cdcef: MOVQ 0(AX), AX . . 10cdcf2: MOVQ AX, 0(SP) . . 10cdcf6: MOVQ CX, 0x8(SP) . . 10cdcfb: CALL runtime.convTstring(SB) . . 10cdd00: MOVQ 0x10(SP), AX . . 10cdd05: XORPS X0, X0 . . 10cdd08: MOVUPS X0, 0x240(SP) . . 10cdd10: LEAQ type.*+88544(SB), CX . . 10cdd17: MOVQ CX, 0x240(SP) . . 10cdd1f: MOVQ AX, 0x248(SP) . . 10cdd27: MOVQ os.Stdout(SB), AX ;print.go:213 . . 10cdd2e: LEAQ go.itab.*os.File,io.Writer(SB), DX . . 10cdd35: MOVQ DX, 0(SP) . . 10cdd39: MOVQ AX, 0x8(SP) . . 10cdd3e: LEAQ go.string.*+7928(SB), AX . . 10cdd45: MOVQ AX, 0x10(SP) . . 10cdd4a: MOVQ $0x11, 0x18(SP) . . 10cdd53: LEAQ 0x240(SP), BX . . 10cdd5b: MOVQ BX, 0x20(SP) . . 10cdd60: MOVQ $0x1, 0x28(SP) . . 10cdd69: MOVQ $0x1, 0x30(SP) . . 10cdd72: CALL fmt.Fprintf(SB) . . 10cdd77: MOVQ 0x50(SP), AX ;main.go:68 . . 10cdd7c: JMP 0x10cdc2c . . 10cdd81: MOVQ main.dict(SB), AX ;main.go:56 . . 10cdd88: MOVQ 0x8(AX), CX . . 10cdd8c: MOVQ 0(AX), AX . . 10cdd8f: MOVQ AX, 0(SP) . . 10cdd93: MOVQ CX, 0x8(SP) . . 10cdd98: CALL main.dictionaryStats(SB) . . 10cdd9d: JMP 0x10cd5ed . . 10cdda2: MOVQ AX, 0(SP) ;main.go:48 . . 10cdda6: MOVQ CX, 0x8(SP) . . 10cddab: CALL main.createPathIfNotExists(SB) . . 10cddb0: JMP 0x10cd44e . . 10cddb5: NOPL ;main.go:38 . . 10cddb6: MOVQ CX, 0(SP) ;file.go:289 . . 10cddba: MOVQ AX, 0x8(SP) . . 10cddbf: MOVQ $0x602, 0x10(SP) . . 10cddc8: MOVL $0x1b6, 0x18(SP) . . 10cddd0: CALL os.OpenFile(SB) . . 10cddd5: MOVQ 0x20(SP), AX . . 10cddda: MOVQ AX, 0x1d8(SP) . . 10cdde2: MOVQ 0x30(SP), CX . . 10cdde7: MOVQ 0x28(SP), DX . . 10cddec: TESTQ DX, DX ;main.go:39 . . 10cddef: JE 0x10cde5b . . 10cddf1: JE 0x10cddf7 ;main.go:40 . . 10cddf3: MOVQ 0x8(DX), DX . . 10cddf7: XORPS X0, X0 . . 10cddfa: MOVUPS X0, 0x260(SP) . . 10cde02: MOVUPS X0, 0x270(SP) . . 10cde0a: LEAQ type.*+88544(SB), AX . . 10cde11: MOVQ AX, 0x260(SP) . . 10cde19: LEAQ internal/bytealg.IndexString.args_stackmap+624(SB), BX . . 10cde20: MOVQ BX, 0x268(SP) . . 10cde28: MOVQ DX, 0x270(SP) . . 10cde30: MOVQ CX, 0x278(SP) . . 10cde38: LEAQ 0x260(SP), CX . . 10cde40: MOVQ CX, 0(SP) . . 10cde44: MOVQ $0x2, 0x8(SP) . . 10cde4d: MOVQ $0x2, 0x10(SP) . . 10cde56: CALL log.Fatal(SB) . . 10cde5b: MOVL $0x18, 0x138(SP) ;main.go:42 . . 10cde66: LEAQ go.func.*+289(SB), AX . . 10cde6d: MOVQ AX, 0x150(SP) . . 10cde75: MOVQ 0x1d8(SP), CX . . 10cde7d: MOVQ CX, 0x168(SP) . . 10cde85: LEAQ 0x138(SP), DX . . 10cde8d: MOVQ DX, 0(SP) . . 10cde91: CALL runtime.deferprocStack(SB) . . 10cde96: TESTL AX, AX . . 10cde98: JNE 0x10cdf01 . . 10cde9a: LEAQ go.itab.*os.File,io.Writer(SB), AX ;main.go:43 . . 10cdea1: MOVQ AX, 0(SP) . . 10cdea5: MOVQ 0x1d8(SP), CX . . 10cdead: MOVQ CX, 0x8(SP) . . 10cdeb2: CALL runtime/trace.Start(SB) . . 10cdeb7: MOVL $0x0, 0x80(SP) ;main.go:44 . . 10cdec2: LEAQ go.func.*+1593(SB), AX . . 10cdec9: MOVQ AX, 0x98(SP) . . 10cded1: LEAQ 0x80(SP), AX . . 10cded9: MOVQ AX, 0(SP) . . 10cdedd: CALL runtime.deferprocStack(SB) . . 10cdee2: TESTL AX, AX . . 10cdee4: JNE 0x10cdeeb . . 10cdee6: JMP 0x10cd437 . . 10cdeeb: NOPL . . 10cdeec: CALL runtime.deferreturn(SB) . . 10cdef1: MOVQ 0x2e0(SP), BP . . 10cdef9: ADDQ $0x2e8, SP . . 10cdf00: RET . . 10cdf01: NOPL ;main.go:42 . . 10cdf02: CALL runtime.deferreturn(SB) . . 10cdf07: MOVQ 0x2e0(SP), BP . . 10cdf0f: ADDQ $0x2e8, SP . . 10cdf16: RET . . 10cdf17: NOPL ;main.go:28 . . 10cdf18: MOVQ CX, 0(SP) ;file.go:289 . . 10cdf1c: MOVQ AX, 0x8(SP) . . 10cdf21: MOVQ $0x602, 0x10(SP) . . 10cdf2a: MOVL $0x1b6, 0x18(SP) . . 10cdf32: CALL os.OpenFile(SB) . . 10cdf37: MOVQ 0x20(SP), AX . . 10cdf3c: MOVQ AX, 0x1e0(SP) . . 10cdf44: MOVQ 0x28(SP), CX . . 10cdf49: MOVQ CX, 0x68(SP) . . 10cdf4e: MOVQ 0x30(SP), DX . . 10cdf53: MOVQ DX, 0x1e8(SP) . . 10cdf5b: MOVL $0x18, 0x180(SP) ;main.go:29 . . 10cdf66: LEAQ go.func.*+289(SB), BX . . 10cdf6d: MOVQ BX, 0x198(SP) . . 10cdf75: MOVQ AX, 0x1b0(SP) . . 10cdf7d: LEAQ 0x180(SP), SI . . 10cdf85: MOVQ SI, 0(SP) . . 10cdf89: CALL runtime.deferprocStack(SB) . . 10cdf8e: TESTL AX, AX . . 10cdf90: JNE 0x10ce053 . . 10cdf96: MOVQ 0x68(SP), AX ;main.go:30 . . 10cdf9b: TESTQ AX, AX . . 10cdf9e: JE 0x10cdfec . . 10cdfa0: JE 0x10cdfa6 ;main.go:31 . . 10cdfa2: MOVQ 0x8(AX), AX . . 10cdfa6: XORPS X0, X0 . . 10cdfa9: MOVUPS X0, 0x200(SP) . . 10cdfb1: MOVQ AX, 0x200(SP) . . 10cdfb9: MOVQ 0x1e8(SP), AX . . 10cdfc1: MOVQ AX, 0x208(SP) . . 10cdfc9: LEAQ 0x200(SP), AX . . 10cdfd1: MOVQ AX, 0(SP) . . 10cdfd5: MOVQ $0x1, 0x8(SP) . . 10cdfde: MOVQ $0x1, 0x10(SP) . . 10cdfe7: CALL log.Fatal(SB) . . 10cdfec: LEAQ go.itab.*os.File,io.Writer(SB), AX ;main.go:33 . . 10cdff3: MOVQ AX, 0(SP) . . 10cdff7: MOVQ 0x1e0(SP), CX . . 10cdfff: MOVQ CX, 0x8(SP) . . 10ce004: CALL runtime/pprof.StartCPUProfile(SB) . . 10ce009: MOVL $0x0, 0xb8(SP) ;main.go:34 . . 10ce014: LEAQ go.func.*+1561(SB), AX . . 10ce01b: MOVQ AX, 0xd0(SP) . . 10ce023: LEAQ 0xb8(SP), AX . . 10ce02b: MOVQ AX, 0(SP) . . 10ce02f: CALL runtime.deferprocStack(SB) . . 10ce034: TESTL AX, AX . . 10ce036: JNE 0x10ce03d . . 10ce038: JMP 0x10cd420 . . 10ce03d: NOPL . . 10ce03e: CALL runtime.deferreturn(SB) . . 10ce043: MOVQ 0x2e0(SP), BP . . 10ce04b: ADDQ $0x2e8, SP . . 10ce052: RET . . 10ce053: NOPL ;main.go:29 . . 10ce054: CALL runtime.deferreturn(SB) . . 10ce059: MOVQ 0x2e0(SP), BP . . 10ce061: ADDQ $0x2e8, SP . . 10ce068: RET . . 10ce069: MOVQ SI, AX ;main.go:81 . . 10ce06c: MOVQ DI, CX . . 10ce06f: CALL runtime.panicIndex(SB) . . 10ce074: MOVL $0x1, AX ;flag.go:996 . . 10ce079: CALL runtime.panicSliceB(SB) . . 10ce07e: NOPL . . 10ce07f: CALL runtime.morestack_noctxt(SB) ;main.go:24 . . 10ce084: JMP main.main(SB) . . 10ce089: INT $0x3 . . 10ce08a: INT $0x3 . . 10ce08b: INT $0x3 . . 10ce08c: INT $0x3 . . 10ce08d: INT $0x3 . . 10ce08e: INT $0x3 ROUTINE ======================== main.newIndex 100ms 120ms (flat, cum) 2.05% of Total . . 10cbe00: MOVQ GS:0x30, CX ;index.go:18 . . 10cbe09: CMPQ 0x10(CX), SP . . 10cbe0d: JBE 0x10cc00e . . 10cbe13: SUBQ $0x48, SP . . 10cbe17: MOVQ BP, 0x40(SP) . . 10cbe1c: LEAQ 0x40(SP), BP . . 10cbe21: LEAQ type.*+77216(SB), AX ;index.go:19 . . 10cbe28: MOVQ AX, 0(SP) . . 10cbe2c: MOVQ 0x50(SP), AX . . 10cbe31: MOVQ AX, 0x8(SP) . . 10cbe36: MOVQ AX, 0x10(SP) . 20ms 10cbe3b: CALL runtime.makeslice(SB) ;main.newIndex index.go:19 . . 10cbe40: MOVQ 0x18(SP), AX ;index.go:19 . . 10cbe45: MOVQ AX, 0x38(SP) . . 10cbe4a: XORL CX, CX . . 10cbe4c: JMP 0x10cbe55 ;index.go:20 . . 10cbe4e: LEAQ 0x1(AX), CX . . 10cbe52: MOVQ BX, AX ;index.go:21 . . 10cbe55: MOVQ 0x50(SP), DX ;index.go:20 . . 10cbe5a: CMPQ DX, CX . . 10cbe5d: JGE 0x10cbec4 . . 10cbe5f: MOVQ CX, 0x20(SP) . . 10cbe64: LEAQ type.*+85856(SB), AX ;index.go:21 . . 10cbe6b: MOVQ AX, 0(SP) . . 10cbe6f: XORPS X0, X0 . . 10cbe72: MOVUPS X0, 0x8(SP) . . 10cbe77: CALL runtime.makeslice(SB) . . 10cbe7c: MOVQ 0x20(SP), AX . . 10cbe81: LEAQ 0(AX)(AX*2), CX . . 10cbe85: MOVQ 0x18(SP), DX . . 10cbe8a: MOVQ 0x38(SP), BX 40ms 40ms 10cbe8f: MOVQ $0x0, 0x8(BX)(CX*8) ;main.newIndex index.go:21 60ms 60ms 10cbe98: MOVQ $0x0, 0x10(BX)(CX*8) . . 10cbea1: LEAQ 0(BX)(CX*8), DI ;index.go:21 . . 10cbea5: CMPL $0x0, runtime.writeBarrier(SB) . . 10cbeac: JNE 0x10cbeb4 . . 10cbeae: MOVQ DX, 0(BX)(CX*8) . . 10cbeb2: JMP 0x10cbe4e . . 10cbeb4: MOVQ AX, CX ;index.go:20 . . 10cbeb7: MOVQ DX, AX ;index.go:21 . . 10cbeba: CALL runtime.gcWriteBarrier(SB) . . 10cbebf: MOVQ CX, AX ;index.go:20 . . 10cbec2: JMP 0x10cbe4e ;index.go:21 . . 10cbec4: NOPL ;murmur64.go:18 . . 10cbec5: MOVL $0x0, 0(SP) ;murmur64.go:22 . . 10cbecc: CALL erichgess/wordladder/vendor/github.com/spaolacci/murmur3.New128WithSeed(SB) . . 10cbed1: MOVQ 0x10(SP), AX . . 10cbed6: MOVQ 0x8(SP), CX . . 10cbedb: LEAQ go.itab.*erichgess/wordladder/vendor/github.com/spaolacci/murmur3.digest128,erichgess/wordladder/vendor/github.com/spaolacci/murmur3.Hash128(SB), DX . . 10cbee2: CMPQ DX, CX . . 10cbee5: JNE 0x10cbfec . . 10cbeeb: MOVQ AX, 0x28(SP) . . 10cbef0: LEAQ type.*+88864(SB), AX ;index.go:25 . . 10cbef7: MOVQ AX, 0(SP) . . 10cbefb: MOVQ $0x0, 0x8(SP) . . 10cbf04: MOVQ 0x58(SP), AX . . 10cbf09: MOVQ AX, 0x10(SP) . . 10cbf0e: CALL runtime.makeslice(SB) . . 10cbf13: MOVQ 0x18(SP), AX . . 10cbf18: MOVQ AX, 0x30(SP) . . 10cbf1d: LEAQ type.*+195616(SB), CX ;index.go:27 . . 10cbf24: MOVQ CX, 0(SP) . . 10cbf28: CALL runtime.newobject(SB) . . 10cbf2d: MOVQ 0x8(SP), AX ;index.go:24 . . 10cbf32: LEAQ go.itab.*erichgess/wordladder/vendor/github.com/spaolacci/murmur3.digest64,hash.Hash64(SB), CX . . 10cbf39: MOVQ CX, 0(AX) . . 10cbf3c: CMPL $0x0, runtime.writeBarrier(SB) . . 10cbf43: JNE 0x10cbfd3 . . 10cbf49: MOVQ 0x28(SP), CX . . 10cbf4e: MOVQ CX, 0x8(AX) . . 10cbf52: MOVQ $0x0, 0x30(AX) ;index.go:25 . . 10cbf5a: MOVQ 0x58(SP), CX . . 10cbf5f: MOVQ CX, 0x38(AX) . . 10cbf63: CMPL $0x0, runtime.writeBarrier(SB) . . 10cbf6a: JNE 0x10cbfbd . . 10cbf6c: MOVQ 0x30(SP), CX . . 10cbf71: MOVQ CX, 0x28(AX) . . 10cbf75: MOVQ 0x50(SP), CX ;index.go:26 . . 10cbf7a: MOVQ CX, 0x18(AX) . . 10cbf7e: MOVQ CX, 0x20(AX) . . 10cbf82: CMPL $0x0, runtime.writeBarrier(SB) . . 10cbf89: JNE 0x10cbfa7 . . 10cbf8b: MOVQ 0x38(SP), DX . . 10cbf90: MOVQ DX, 0x10(AX) . . 10cbf94: MOVQ CX, 0x40(AX) ;index.go:27 . . 10cbf98: MOVQ AX, 0x60(SP) ;index.go:23 . . 10cbf9d: MOVQ 0x40(SP), BP . . 10cbfa2: ADDQ $0x48, SP . . 10cbfa6: RET . . 10cbfa7: LEAQ 0x10(AX), DI ;index.go:26 . . 10cbfab: MOVQ AX, DX ;index.go:27 . . 10cbfae: MOVQ 0x38(SP), AX ;index.go:26 . . 10cbfb3: CALL runtime.gcWriteBarrier(SB) . . 10cbfb8: MOVQ DX, AX ;index.go:27 . . 10cbfbb: JMP 0x10cbf94 ;index.go:26 . . 10cbfbd: LEAQ 0x28(AX), DI ;index.go:25 . . 10cbfc1: MOVQ AX, CX ;index.go:27 . . 10cbfc4: MOVQ 0x30(SP), AX ;index.go:25 . . 10cbfc9: CALL runtime.gcWriteBarrier(SB) . . 10cbfce: MOVQ CX, AX ;index.go:26 . . 10cbfd1: JMP 0x10cbf75 ;index.go:25 . . 10cbfd3: LEAQ 0x8(AX), DI ;index.go:24 . . 10cbfd7: MOVQ AX, CX ;index.go:27 . . 10cbfda: MOVQ 0x28(SP), AX ;index.go:24 . . 10cbfdf: CALL runtime.gcWriteBarrier(SB) . . 10cbfe4: MOVQ CX, AX ;index.go:25 . . 10cbfe7: JMP 0x10cbf52 ;index.go:24 . . 10cbfec: MOVQ CX, 0(SP) ;murmur64.go:22 . . 10cbff0: LEAQ type.*+200512(SB), AX . . 10cbff7: MOVQ AX, 0x8(SP) . . 10cbffc: LEAQ type.*+156288(SB), AX . . 10cc003: MOVQ AX, 0x10(SP) . . 10cc008: CALL runtime.panicdottypeI(SB) . . 10cc00d: NOPL . . 10cc00e: CALL runtime.morestack_noctxt(SB) ;index.go:18 . . 10cc013: JMP main.newIndex(SB) . . 10cc018: INT $0x3 . . 10cc019: INT $0x3 . . 10cc01a: INT $0x3 . . 10cc01b: INT $0x3 . . 10cc01c: INT $0x3 . . 10cc01d: INT $0x3 . . 10cc01e: INT $0x3 ROUTINE ======================== runtime.main 0 2.89s (flat, cum) 49.32% of Total . . 102caf0: MOVQ GS:0x30, CX ;proc.go:113 . . 102caf9: CMPQ 0x10(CX), SP . . 102cafd: JBE 0x102ce70 . . 102cb03: SUBQ $0x78, SP . . 102cb07: MOVQ BP, 0x70(SP) . . 102cb0c: LEAQ 0x70(SP), BP . . 102cb11: MOVQ GS:0x30, AX ;proc.go:114 . . 102cb1a: MOVQ AX, 0x68(SP) . . 102cb1f: MOVQ 0x30(AX), CX ;proc.go:118 . . 102cb23: MOVQ 0(CX), CX . . 102cb26: MOVQ $0x0, 0x130(CX) ;proc.go:124 . . 102cb31: MOVQ $0x3b9aca00, runtime.maxstacksize(SB) . . 102cb3c: MOVB $0x1, runtime.mainStarted(SB) ;proc.go:130 . . 102cb43: LEAQ go.func.*+945(SB), CX ;proc.go:133 . . 102cb4a: MOVQ CX, 0(SP) . . 102cb4e: CALL runtime.systemstack(SB) . . 102cb53: MOVQ GS:0x30, AX ;proc.go:3550 . . 102cb5c: MOVQ 0x30(AX), AX . . 102cb60: NOPL ;proc.go:144 . . 102cb61: INCL 0x274(AX) ;proc.go:3550 . . 102cb67: MOVQ GS:0x30, AX ;proc.go:3511 . . 102cb70: MOVQ 0x30(AX), CX ;proc.go:3512 . . 102cb74: NOPL ;proc.go:3551 . . 102cb75: MOVQ AX, DX ;runtime2.go:254 . . 102cb78: MOVQ AX, 0x168(CX) . . 102cb7f: MOVQ 0x30(DX), AX ;proc.go:3513 . . 102cb83: MOVQ AX, 0xd8(DX) ;runtime2.go:292 . . 102cb8a: MOVQ 0x68(SP), AX ;proc.go:146 . . 102cb8f: MOVQ 0x30(AX), AX . . 102cb93: LEAQ runtime.m0(SB), CX . . 102cb9a: CMPQ CX, AX . . 102cb9d: JNE 0x102ce56 . . 102cba3: LEAQ runtime..inittask(SB), AX ;proc.go:150 . . 102cbaa: MOVQ AX, 0(SP) . . 102cbae: CALL runtime.doInit(SB) . . 102cbb3: CALL runtime.nanotime(SB) ;proc.go:151 . . 102cbb8: CMPQ $0x0, 0(SP) . . 102cbbd: JE 0x102ce3d . . 102cbc3: MOVB $0x1, 0x27(SP) ;proc.go:156 . . 102cbc8: MOVL $0x8, 0x30(SP) ;proc.go:157 . . 102cbd0: LEAQ go.func.*+953(SB), AX . . 102cbd7: MOVQ AX, 0x48(SP) . . 102cbdc: LEAQ 0x27(SP), AX . . 102cbe1: MOVQ AX, 0x60(SP) . . 102cbe6: LEAQ 0x30(SP), AX . . 102cbeb: MOVQ AX, 0(SP) . . 102cbef: CALL runtime.deferprocStack(SB) . . 102cbf4: TESTL AX, AX . . 102cbf6: JNE 0x102cdc9 . . 102cbfc: CALL runtime.nanotime(SB) ;proc.go:164 . . 102cc01: MOVQ 0(SP), AX . . 102cc05: MOVQ AX, runtime.runtimeInitTime(SB) . . 102cc0c: CALL runtime.gcenable(SB) ;proc.go:166 . . 102cc11: LEAQ type.*+83104(SB), AX ;proc.go:168 . . 102cc18: MOVQ AX, 0(SP) . . 102cc1c: MOVQ $0x0, 0x8(SP) . . 102cc25: CALL runtime.makechan(SB) . . 102cc2a: MOVQ 0x10(SP), AX . . 102cc2f: CMPL $0x0, runtime.writeBarrier(SB) . . 102cc36: JNE 0x102cdb8 . . 102cc3c: MOVQ AX, runtime.main_init_done(SB) . . 102cc43: CMPB $0x0, runtime.iscgo(SB) ;proc.go:169 . . 102cc4a: JE 0x102ccba . . 102cc4c: CMPQ $0x0, __cgo_thread_start(SB) ;proc.go:170 . . 102cc54: JE 0x102ce24 . . 102cc5a: CMPQ $0x0, runtime._cgo_setenv(SB) ;proc.go:174 . . 102cc62: JE 0x102ce0b . . 102cc68: CMPQ $0x0, runtime._cgo_unsetenv(SB) ;proc.go:177 . . 102cc70: JE 0x102cdf2 ;proc.go:181 . . 102cc76: CMPQ $0x0, __cgo_notify_runtime_init_done(SB) . . 102cc7e: JE 0x102cdd9 . . 102cc84: XORL AX, AX ;proc.go:1865 . . 102cc86: LEAQ runtime.newmHandoff+32(SB), CX . . 102cc8d: MOVL $0x1, DX . . 102cc92: LOCK CMPXCHGL DX, 0(CX) . . 102cc96: SETE CL . . 102cc99: TESTL CL, CL . . 102cc9b: JNE 0x102cd9a ;proc.go:187 . . 102cca1: MOVQ __cgo_notify_runtime_init_done(SB), AX . . 102cca8: MOVQ AX, 0(SP) . . 102ccac: MOVQ $0x0, 0x8(SP) . . 102ccb5: CALL runtime.cgocall(SB) . . 102ccba: LEAQ main..inittask(SB), AX ;proc.go:190 . . 102ccc1: MOVQ AX, 0(SP) . . 102ccc5: CALL runtime.doInit(SB) . . 102ccca: MOVQ runtime.main_init_done(SB), AX ;proc.go:192 . . 102ccd1: MOVQ AX, 0(SP) . . 102ccd5: CALL runtime.closechan(SB) . . 102ccda: MOVB $0x0, 0x27(SP) ;proc.go:194 . . 102ccdf: CALL runtime.unlockOSThread(SB) ;proc.go:195 . . 102cce4: CMPB $0x0, runtime.isarchive(SB) ;proc.go:197 . . 102cceb: JNE 0x102cd8a . . 102ccf1: CMPB $0x0, runtime.islibrary(SB) . . 102ccf8: JNE 0x102cd8a . . 102ccfe: MOVQ go.func.*+961(SB), AX ;proc.go:203 . . 102cd05: LEAQ go.func.*+961(SB), DX . 2.89s 102cd0c: CALL AX ;runtime.main proc.go:203 . . 102cd0e: MOVL runtime.runningPanicDefers(SB), AX ;proc.go:212 . . 102cd14: TESTL AX, AX . . 102cd16: JE 0x102cd4c . . 102cd18: XORL AX, AX . . 102cd1a: JMP 0x102cd3a ;proc.go:214 . . 102cd1c: MOVQ AX, 0x28(SP) . . 102cd21: NOPL ;proc.go:218 . . 102cd22: LEAQ go.func.*+889(SB), AX ;proc.go:269 . . 102cd29: MOVQ AX, 0(SP) . . 102cd2d: CALL runtime.mcall(SB) . . 102cd32: MOVQ 0x28(SP), AX ;proc.go:214 . . 102cd37: INCQ AX . . 102cd3a: CMPQ $0x3e8, AX . . 102cd40: JGE 0x102cd4c . . 102cd42: MOVL runtime.runningPanicDefers(SB), CX ;proc.go:215 . . 102cd48: TESTL CX, CX . . 102cd4a: JNE 0x102cd1c . . 102cd4c: MOVL runtime.panicking(SB), AX ;proc.go:221 . . 102cd52: TESTL AX, AX . . 102cd54: JNE 0x102cd6c . . 102cd56: MOVL $0x0, 0(SP) ;proc.go:225 . . 102cd5d: CALL runtime.exit(SB) . . 102cd62: XORL AX, AX ;proc.go:228 . . 102cd64: MOVL $0x0, 0(AX) . . 102cd6a: JMP 0x102cd62 . . 102cd6c: XORPS X0, X0 ;proc.go:222 . . 102cd6f: MOVUPS X0, 0(SP) . . 102cd73: MOVW $0x1008, 0x10(SP) . . 102cd7a: MOVQ $0x1, 0x18(SP) . . 102cd83: CALL runtime.gopark(SB) . . 102cd88: JMP 0x102cd56 . . 102cd8a: NOPL ;proc.go:200 . . 102cd8b: CALL runtime.deferreturn(SB) . . 102cd90: MOVQ 0x70(SP), BP . . 102cd95: ADDQ $0x78, SP . . 102cd99: RET . . 102cd9a: LEAQ go.func.*+1505(SB), AX ;proc.go:1868 . . 102cda1: MOVQ AX, 0(SP) . . 102cda5: MOVQ $0x0, 0x8(SP) . . 102cdae: CALL runtime.newm(SB) . . 102cdb3: JMP 0x102cca1 ;proc.go:186 . . 102cdb8: LEAQ runtime.main_init_done(SB), DI ;proc.go:168 . . 102cdbf: CALL runtime.gcWriteBarrier(SB) . . 102cdc4: JMP 0x102cc43 . . 102cdc9: NOPL ;proc.go:157 . . 102cdca: CALL runtime.deferreturn(SB) . . 102cdcf: MOVQ 0x70(SP), BP . . 102cdd4: ADDQ $0x78, SP . . 102cdd8: RET . . 102cdd9: LEAQ go.string.*+25247(SB), AX ;proc.go:182 . . 102cde0: MOVQ AX, 0(SP) . . 102cde4: MOVQ $0x25, 0x8(SP) . . 102cded: CALL runtime.throw(SB) . . 102cdf2: LEAQ go.string.*+11903(SB), AX ;proc.go:178 . . 102cdf9: MOVQ AX, 0(SP) . . 102cdfd: MOVQ $0x15, 0x8(SP) . . 102ce06: CALL runtime.throw(SB) . . 102ce0b: LEAQ go.string.*+9858(SB), AX ;proc.go:175 . . 102ce12: MOVQ AX, 0(SP) . . 102ce16: MOVQ $0x13, 0x8(SP) . . 102ce1f: CALL runtime.throw(SB) . . 102ce24: LEAQ go.string.*+15035(SB), AX ;proc.go:171 . . 102ce2b: MOVQ AX, 0(SP) . . 102ce2f: MOVQ $0x19, 0x8(SP) . . 102ce38: CALL runtime.throw(SB) . . 102ce3d: LEAQ go.string.*+13879(SB), AX ;proc.go:152 . . 102ce44: MOVQ AX, 0(SP) . . 102ce48: MOVQ $0x17, 0x8(SP) . . 102ce51: CALL runtime.throw(SB) . . 102ce56: LEAQ go.string.*+12998(SB), AX ;proc.go:147 . . 102ce5d: MOVQ AX, 0(SP) . . 102ce61: MOVQ $0x16, 0x8(SP) . . 102ce6a: CALL runtime.throw(SB) . . 102ce6f: NOPL . . 102ce70: CALL runtime.morestack_noctxt(SB) ;proc.go:113 . . 102ce75: JMP runtime.main(SB) . . 102ce7a: INT $0x3 . . 102ce7b: INT $0x3 . . 102ce7c: INT $0x3 . . 102ce7d: INT $0x3 . . 102ce7e: INT $0x3
; A106505: Ordered and uniqued length of side common to the two angles, one being the double of the other, of a primitive integer-sided triangle. ; 5,7,9,11,13,15,16,17,19,21,23,24,25,27,29,31,32,33,35,37,39,40,41,43,45,47,48,49,51,53,55,56,57,59,61,63,64,65,67,69,71,72,73,75,77,79,80,81,83,85,87,88,89,91,93,95,96,97,99,101,103,104,105,107,109,111,112 mov $2,$0 lpb $2,1 trn $0,5 add $1,2 trn $1,$0 sub $2,1 lpe add $1,5