text
stringlengths
1
1.05M
[bits 32] [section .text] INT_VECTOR_SYS_CALL equ 0x80 _NR_MALLOC EQU 1 global malloc malloc: mov eax, _NR_MALLOC mov ebx, [esp + 4] ;第一个参数 int INT_VECTOR_SYS_CALL ret
/** * Texture.cpp * Authors: Sheldon Taylor, Jiju Poovvancheri * * Implementation of OpenGL-based texture generation. */ #include <icg_common.h> #include "Texture.h" Texture::Texture() {} Texture::~Texture() {} /* * Reads noise texture images from file. * * Returns: * 0 if succesfully completed. TODO: return -1 if failed */ int Texture::readNoiseTexture(GLuint *tex) { printf("\n Attempting to read noise texture from file.\n"); // Set our texture parameters and texture filtering //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Define filename of texture to read std::string filename = "../Output/temp/noise_output.bmp"; // Read file int texWidth, texHeight; //stbi_set_flip_vertically_on_load(true); unsigned char* image = stbi_load(filename.c_str(), &texWidth, &texHeight, 0, 4); // Create texture and generate mipmaps glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); // Debug printf(" BMP file read: %s\n Successfully read noise texture from file.\n", filename.c_str()); // Cleanup stbi_image_free(image); return 0; } /* * Reads skybox texture images from file. * * Returns: * 0 if succesfully completed. TODO: return -1 if failed */ int Texture::readSkyboxTexture(unsigned int i, std::string filename) { printf("\n Attempting to read skybox texture from file.\n"); int texWidth, texHeight; unsigned char* image = stbi_load(filename.c_str(), &texWidth, &texHeight, 0, 4); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); // Debug printf(" PNG file read: %s\n Successfully read skybox texture from file.\n", filename.c_str()); // Cleanup stbi_image_free(image); return 0; } /* * Reads terrain texture images from file. * * Returns: * 0 if succesfully completed. TODO: return -1 if failed */ int Texture::readTerrainTexture(int i, std::string filename) { printf("\n Attempting to read terrain texture from file.\n"); int texWidth, texHeight; unsigned char* image = stbi_load(filename.c_str(), &texWidth, &texHeight, 0, 4); //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); //glGenerateMipmap(GL_TEXTURE_2D); int numMipmapLevels = 9; for (int i = 0; i < numMipmapLevels; i++) { glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); } glGenerateMipmap(GL_TEXTURE_2D); // Read texture from file glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, numMipmapLevels - 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // MIPMAP doesn't apply to Magnification glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Debug printf(" PNG file read: %s\n Successfully read terrain texture from file.\n", filename.c_str()); // Cleanup stbi_image_free(image); return 0; } /* * Generates noise texture from file. * * Returns: * 0 if succesfully completed. TODO: return -1 if failed */ int Texture::generateNoiseTexture(GLuint *tex) { // Read texture from file printf("\n Starting noise texture generation."); Texture::readNoiseTexture(tex); printf(" Successfully completed noise texture generation.\n"); return 0; } /* * Generates skybox texture from files. * * Returns: * 0 if succesfully completed. TODO: return -1 if failed */ int Texture::generateSkyboxTexture(int i, std::string filename) { // Read texture from file Texture::readSkyboxTexture(i, filename); return 0; } /* * Generates terrain textures from file. * * Returns: * 0 if succesfully completed. TODO: return -1 if failed */ int Texture::generateTerrainTexture(int i, std::string filename) { // Read texture from file Texture::readTerrainTexture(i, filename); return 0; }
; =============================================================== ; Stefano Bodrato ; aralbrec: accommodate nmos z80 bug ; =============================================================== ; ; void z80_push_di(void) ; ; Save the current ei/di status on the stack and disable ints. ; ; =============================================================== INCLUDE "config_private.inc" SECTION code_clib SECTION code_z80 PUBLIC asm_z80_push_di PUBLIC asm_cpu_push_di asm_z80_push_di: asm_cpu_push_di: IF __CPU_R2KA__ | __CPU_R3K__ ipset 3 ELSE ; exit : stack = ei_di_status ; ; uses : af ex (sp),hl push hl IF __CPU_8085__ rim ELSE IF __Z80 & __Z80_NMOS ; nmos z80 bug prevents use of "ld a,i" to gather IFF2 into p/v flag ; see http://www.z80.info/zip/ZilogProductSpecsDatabook129-143.pdf ; this is zilog's suggested solution, note status in carry flag not p/v ld hl,0 push hl pop hl ; zero written underneath SP scf ld a,i jp PE, continue ; carry set if ints enabled dec sp dec sp pop hl ; have a look at zero word underneath SP ld a,h or l jr Z, continue ; int did not occur, ints are disabled, carry reset scf ; int occurred, set carry ELSE ; cmos z80 has no bug ld a,i ENDIF ENDIF continue: di push af pop hl ; hl = ei_di status pop af ; af = ret ex (sp),hl ; restore hl, push ei_di_status push af ENDIF ret
; A138967: Infinite Fibonacci word on the alphabet {1,2,3,4}. ; Submitted by Christian Krause ; 1,2,3,1,4,1,2,3,1,2,3,1,4,1,2,3,1,4,1,2,3,1,2,3,1,4,1,2,3,1,2,3,1,4,1,2,3,1,4,1,2,3,1,2,3,1,4,1,2,3,1,4,1,2,3,1,2,3,1,4,1,2,3,1,2,3,1,4,1,2,3,1,4,1,2,3,1,2,3,1,4,1,2,3,1,2,3,1,4,1,2,3,1,4,1,2,3,1,2,3 seq $0,48679 ; Compressed fibbinary numbers (A003714), with rewrite 0->0, 01->1 applied to their binary expansion. mod $0,4 add $0,1
MODULE fscanf SECTION code_clib PUBLIC fscanf EXTERN asm_scanf ; sccz80 version ;void fscanf(FILE *fp, char *fmt,...) ;{ ; asm_scanf(fp, sccz80_delta, *ct,ct-1); ;} fscanf: ld l,a ld h,0 add hl,hl add hl,sp ;&buf ld c,(hl) ;fp inc hl ld b,(hl) push bc ;fp on stack dec hl dec hl ;&fmt+1 ld bc,1 ;sccz80 push bc ld b,(hl) ;fmt dec hl ld c,(hl) push bc dec hl dec hl push hl ;&ap call asm_scanf pop bc pop bc pop bc pop bc pop bc pop bc pop ix ret
/* * Copyright (C) 2009 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 "config.h" #include "WebScreenInfoFactory.h" #include "WebScreenInfo.h" #include <gtk/gtk.h> namespace WebKit { WebScreenInfo WebScreenInfoFactory::screenInfo(GtkWidget* widget) { WebScreenInfo results; results.depth = 32; results.depthPerComponent = 8; results.isMonochrome = false; if (!widget) return results; GdkScreen* screen = gtk_widget_get_screen(widget); results.rect = WebRect( 0, 0, gdk_screen_get_width(screen), gdk_screen_get_height(screen)); // I don't know of a way to query the "maximize" size of the window (e.g. // screen size less sidebars etc) since this is something which only the // window manager knows. results.availableRect = results.rect; return results; } } // namespace WebKit
; ; ; uint8_t joystick_sc(uint16_t keys[...]) __z88dk_fastcall ; Keys are ordered: RIGHT, LEFT, DOWN, UP, FIRE1, FIRE2, FIRE3, FIRE4 ; Terminated by \0 ; ; Uses scancodes MODULE joystick_sc SECTION code_clib PUBLIC joystick_sc PUBLIC _joystick_sc EXTERN in_LookupKey EXTERN in_KeyPressed joystick_sc: _joystick_sc: ld b,8 ld de,$0001 loop: push bc ld c,(hl) inc hl ld b,(hl) inc hl ld a,c or b jr z,finished push hl ld l,c ld h,b push de call in_KeyPressed pop de jr nc,continue ld a,d or e ld d,a continue: sla e ;Shift mask across pop hl pop bc djnz loop finished: pop bc ld l,d ld h,0 ret
;; ;; Copyright (c) 2012-2020, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation nor the names of its contributors ;; may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; %include "include/os.asm" %include "imb_job.asm" %include "mb_mgr_datastruct.asm" %include "include/reg_sizes.asm" ;%define DO_DBGPRINT %include "include/dbgprint.asm" extern md5_x8x2_avx2 section .data default rel align 16 dupw: ;ddq 0x01000100010001000100010001000100 dq 0x0100010001000100, 0x0100010001000100 x80: ;ddq 0x00000000000000000000000000000080 dq 0x0000000000000080, 0x0000000000000000 x00: ;ddq 0x00000000000000000000000000000000 dq 0x0000000000000000, 0x0000000000000000 len_masks: ;ddq 0x0000000000000000000000000000FFFF dq 0x000000000000FFFF, 0x0000000000000000 ;ddq 0x000000000000000000000000FFFF0000 dq 0x00000000FFFF0000, 0x0000000000000000 ;ddq 0x00000000000000000000FFFF00000000 dq 0x0000FFFF00000000, 0x0000000000000000 ;ddq 0x0000000000000000FFFF000000000000 dq 0xFFFF000000000000, 0x0000000000000000 ;ddq 0x000000000000FFFF0000000000000000 dq 0x0000000000000000, 0x000000000000FFFF ;ddq 0x00000000FFFF00000000000000000000 dq 0x0000000000000000, 0x00000000FFFF0000 ;ddq 0x0000FFFF000000000000000000000000 dq 0x0000000000000000, 0x0000FFFF00000000 ;ddq 0xFFFF0000000000000000000000000000 dq 0x0000000000000000, 0xFFFF000000000000 lane_1: dq 1 lane_2: dq 2 lane_3: dq 3 lane_4: dq 4 lane_5: dq 5 lane_6: dq 6 lane_7: dq 7 lane_8: dq 8 lane_9: dq 9 lane_10: dq 10 lane_11: dq 11 lane_12: dq 12 lane_13: dq 13 lane_14: dq 14 lane_15: dq 15 section .text %if 1 %ifdef LINUX %define arg1 rdi %define arg2 rsi %else %define arg1 rcx %define arg2 rdx %endif %define state arg1 %define job arg2 %define len2 arg2 ; idx needs to be in rbp %define idx rbp %define unused_lanes rbx %define lane_data rbx %define tmp2 rbx %define job_rax rax %define tmp1 rax %define size_offset rax %define tmp rax %define start_offset rax %define tmp3 arg1 %define extra_blocks arg2 %define p arg2 %define tmp4 r8 %define tmp5 r9 %define num_lanes_inuse r12 %define len_upper r13 %define idx_upper r14 %endif ; This routine and/or the called routine clobbers all GPRs struc STACK _gpr_save: resq 8 _rsp_save: resq 1 endstruc %define APPEND(a,b) a %+ b ; JOB* flush_job_hmac_md5_avx(MB_MGR_HMAC_MD5_OOO *state) ; arg 1 : rcx : state MKGLOBAL(flush_job_hmac_md5_avx2,function,internal) flush_job_hmac_md5_avx2: mov rax, rsp sub rsp, STACK_size and rsp, -32 mov [rsp + _gpr_save + 8*0], rbx mov [rsp + _gpr_save + 8*1], rbp mov [rsp + _gpr_save + 8*2], r12 mov [rsp + _gpr_save + 8*3], r13 mov [rsp + _gpr_save + 8*4], r14 mov [rsp + _gpr_save + 8*5], r15 %ifndef LINUX mov [rsp + _gpr_save + 8*6], rsi mov [rsp + _gpr_save + 8*7], rdi %endif mov [rsp + _rsp_save], rax ; original SP DBGPRINTL "---------- enter md5 flush -----------" mov DWORD(num_lanes_inuse), [state + _num_lanes_inuse_md5] ;; empty? cmp num_lanes_inuse, 0 jz return_null ; find a lane with a non-null job -- flush does not have to be efficient! mov idx, 0 %assign I 1 %rep 15 cmp qword [state + _ldata_md5 + I * _HMAC_SHA1_LANE_DATA_size + _job_in_lane], 0 cmovne idx, [rel APPEND(lane_,I)] %assign I (I+1) %endrep copy_lane_data: ; copy good lane (idx) to empty lanes mov tmp, [state + _args_data_ptr_md5 + PTR_SZ*idx] ;; tackle lower 8 lanes vmovdqa xmm0, [state + _lens_md5 + 0*16] ;; lower 8 lengths %assign I 0 %rep 8 cmp qword [state + _ldata_md5 + I * _HMAC_SHA1_LANE_DATA_size + _job_in_lane], 0 jne APPEND(lower_skip_,I) mov [state + _args_data_ptr_md5 + PTR_SZ*I], tmp vpor xmm0, xmm0, [rel len_masks + 16*I] APPEND(lower_skip_,I): %assign I (I+1) %endrep ;; tackle upper lanes vmovdqa xmm1, [state + _lens_md5 + 1*16] ;; upper 8 lengths %assign I 0 %rep 8 cmp qword [state + _ldata_md5 + (8 + I) * _HMAC_SHA1_LANE_DATA_size + _job_in_lane], 0 jne APPEND(upper_skip_,I) mov [state + _args_data_ptr_md5 + PTR_SZ*(8+I)], tmp vpor xmm1, xmm1, [rel len_masks + 16*I] APPEND(upper_skip_,I): %assign I (I+1) %endrep jmp start_loop0 align 32 start_loop0: ; Find min length vphminposuw xmm2, xmm0 vpextrw DWORD(len2), xmm2, 0 ; min value vpextrw DWORD(idx), xmm2, 1 ; min index (0...7) vphminposuw xmm3, xmm1 vpextrw DWORD(len_upper), xmm3, 0 ; min value vpextrw DWORD(idx_upper), xmm3, 1 ; min index (8...F) cmp len2, len_upper jle use_min min_in_high: vmovdqa xmm2, xmm3 mov len2, len_upper mov idx, idx_upper or idx, 0x8 ; to reflect that index in 8-F use_min: and len2, len2 ; to set flags jz len_is_0 DBGPRINTL64 "min_length min_index ", len2, idx DBGPRINTL_XMM "FLUSH md5 lens before sub lower", xmm0 vpbroadcastw xmm2, xmm2 ; duplicate words across all lanes vpsubw xmm0, xmm0, xmm2 DBGPRINTL_XMM "FLUSH md5 lens after sub lower", xmm0 vmovdqa [state + _lens_md5 + 0*16], xmm0 vpsubw xmm1, xmm1, xmm2 DBGPRINTL_XMM "FLUSH md5 lens after sub upper", xmm1 vmovdqa [state + _lens_md5 + 1*16], xmm1 ; "state" and "args" are the same address, arg1 ; len is arg2 call md5_x8x2_avx2 ; state and idx are intact len_is_0: ; process completed job "idx" imul lane_data, idx, _HMAC_SHA1_LANE_DATA_size lea lane_data, [state + _ldata_md5 + lane_data] mov DWORD(extra_blocks), [lane_data + _extra_blocks] cmp extra_blocks, 0 jne proc_extra_blocks cmp dword [lane_data + _outer_done], 0 jne end_loop proc_outer: mov dword [lane_data + _outer_done], 1 mov DWORD(size_offset), [lane_data + _size_offset] mov qword [lane_data + _extra_block + size_offset], 0 mov word [state + _lens_md5 + 2*idx], 1 lea tmp, [lane_data + _outer_block] mov job, [lane_data + _job_in_lane] mov [state + _args_data_ptr_md5 + PTR_SZ*idx], tmp vmovd xmm0, [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 0*MD5_DIGEST_ROW_SIZE] vpinsrd xmm0, [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 1*MD5_DIGEST_ROW_SIZE], 1 vpinsrd xmm0, [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 2*MD5_DIGEST_ROW_SIZE], 2 vpinsrd xmm0, [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 3*MD5_DIGEST_ROW_SIZE], 3 vmovdqa [lane_data + _outer_block], xmm0 mov tmp, [job + _auth_key_xor_opad] vmovdqu xmm0, [tmp] vmovd [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 0*MD5_DIGEST_ROW_SIZE], xmm0 vpextrd [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 1*MD5_DIGEST_ROW_SIZE], xmm0, 1 vpextrd [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 2*MD5_DIGEST_ROW_SIZE], xmm0, 2 vpextrd [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 3*MD5_DIGEST_ROW_SIZE], xmm0, 3 jmp copy_lane_data align 16 proc_extra_blocks: mov DWORD(start_offset), [lane_data + _start_offset] mov [state + _lens_md5 + 2*idx], WORD(extra_blocks) lea tmp, [lane_data + _extra_block + start_offset] mov [state + _args_data_ptr_md5 + PTR_SZ*idx], tmp mov dword [lane_data + _extra_blocks], 0 jmp copy_lane_data return_null: xor job_rax, job_rax jmp return align 16 end_loop: mov job_rax, [lane_data + _job_in_lane] mov qword [lane_data + _job_in_lane], 0 or dword [job_rax + _status], STS_COMPLETED_HMAC mov unused_lanes, [state + _unused_lanes_md5] shl unused_lanes, 4 or unused_lanes, idx mov [state + _unused_lanes_md5], unused_lanes mov DWORD(num_lanes_inuse), [state + _num_lanes_inuse_md5] ;; update lanes inuse sub num_lanes_inuse, 1 mov [state + _num_lanes_inuse_md5], DWORD(num_lanes_inuse) mov p, [job_rax + _auth_tag_output] ; copy 12 bytes mov DWORD(tmp2), [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 0*MD5_DIGEST_ROW_SIZE] mov DWORD(tmp4), [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 1*MD5_DIGEST_ROW_SIZE] mov DWORD(tmp5), [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 2*MD5_DIGEST_ROW_SIZE] ; bswap DWORD(tmp2) ; bswap DWORD(tmp4) ; bswap DWORD(tmp3) mov [p + 0*4], DWORD(tmp2) mov [p + 1*4], DWORD(tmp4) mov [p + 2*4], DWORD(tmp5) cmp DWORD [job_rax + _auth_tag_output_len_in_bytes], 12 je clear_ret ; copy 16 bytes mov DWORD(tmp5), [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*idx + 3*MD5_DIGEST_ROW_SIZE] mov [p + 3*4], DWORD(tmp5) clear_ret: %ifdef SAFE_DATA vpxor ymm0, ymm0 ;; Clear digest (16B), outer_block (16B) and extra_block (64B) ;; of returned job and NULL jobs %assign I 0 %rep 16 cmp qword [state + _ldata_md5 + (I*_HMAC_SHA1_LANE_DATA_size) + _job_in_lane], 0 jne APPEND(skip_clear_,I) ;; Clear digest (16 bytes) %assign J 0 %rep 4 mov dword [state + _args_digest_md5 + MD5_DIGEST_WORD_SIZE*I + J*MD5_DIGEST_ROW_SIZE], 0 %assign J (J+1) %endrep lea lane_data, [state + _ldata_md5 + (I*_HMAC_SHA1_LANE_DATA_size)] ;; Clear first 64 bytes of extra_block vmovdqa [lane_data + _extra_block], ymm0 vmovdqa [lane_data + _extra_block + 32], ymm0 ;; Clear first 16 bytes of outer_block vmovdqa [lane_data + _outer_block], xmm0 APPEND(skip_clear_,I): %assign I (I+1) %endrep %endif ;; SAFE_DATA return: DBGPRINTL "---------- exit md5 flush -----------" vzeroupper mov rbx, [rsp + _gpr_save + 8*0] mov rbp, [rsp + _gpr_save + 8*1] mov r12, [rsp + _gpr_save + 8*2] mov r13, [rsp + _gpr_save + 8*3] mov r14, [rsp + _gpr_save + 8*4] mov r15, [rsp + _gpr_save + 8*5] %ifndef LINUX mov rsi, [rsp + _gpr_save + 8*6] mov rdi, [rsp + _gpr_save + 8*7] %endif mov rsp, [rsp + _rsp_save] ; original SP ret %ifdef LINUX section .note.GNU-stack noalloc noexec nowrite progbits %endif
; A095310: a(n+3) = 2*a(n+2) + 3*(n+1) - a(n). ; Submitted by Jon Maiga ; 1,5,12,38,107,316,915,2671,7771,22640,65922,191993,559112,1628281,4741905,13809541,40216516,117119750,341079507,993301748,2892722267,8424270271,24533405595,71446899736,208069745986,605946785585 mov $2,1 lpb $0 sub $0,1 add $1,1 add $3,$2 add $2,$3 mov $4,$3 add $4,$2 mov $2,$1 mov $1,$4 add $2,$3 lpe add $3,$4 mov $0,$3 add $0,1
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Tracks/MovieSceneIntegerTrack.h" #include "Sections/MovieSceneIntegerSection.h" #include "Evaluation/MovieScenePropertyTemplates.h" UMovieSceneIntegerTrack::UMovieSceneIntegerTrack( const FObjectInitializer& ObjectInitializer ) : Super( ObjectInitializer ) { SupportedBlendTypes = FMovieSceneBlendTypeField::All(); } UMovieSceneSection* UMovieSceneIntegerTrack::CreateNewSection() { return NewObject<UMovieSceneSection>(this, UMovieSceneIntegerSection::StaticClass(), NAME_None, RF_Transactional); } FMovieSceneEvalTemplatePtr UMovieSceneIntegerTrack::CreateTemplateForSection(const UMovieSceneSection& InSection) const { return FMovieSceneIntegerPropertySectionTemplate(*CastChecked<UMovieSceneIntegerSection>(&InSection), *this); }
FuchsiaMart_Object: db $0 ; border block db 2 ; warps warp 3, 7, 0, -1 warp 4, 7, 0, -1 db 0 ; signs db 3 ; objects object SPRITE_MART_GUY, 0, 5, STAY, RIGHT, 1 ; person object SPRITE_FAT_BALD_GUY, 4, 2, STAY, NONE, 2 ; person object SPRITE_LASS, 6, 5, WALK, 1, 3 ; person ; warp-to warp_to 3, 7, FUCHSIA_MART_WIDTH warp_to 4, 7, FUCHSIA_MART_WIDTH
; A022998: If n is odd then n, otherwise 2n. ; 0,1,4,3,8,5,12,7,16,9,20,11,24,13,28,15,32,17,36,19,40,21,44,23,48,25,52,27,56,29,60,31,64,33,68,35,72,37,76,39,80,41,84,43,88,45,92,47,96,49,100,51,104,53,108,55,112,57,116,59,120,61,124,63,128,65,132,67,136,69,140,71,144,73,148,75,152,77,156,79,160,81,164,83,168,85,172,87,176,89,180,91,184,93,188,95,192,97,196,99 mov $1,$0 gcd $0,2 mul $0,$1
// Test using some simple supported string escape \n in both string and char // Uses encoding PETSCII mixed // Commodore 64 PRG executable file .file [name="string-escapes-3.prg", type="prg", segments="Program"] .segmentdef Program [segments="Basic, Code, Data"] .segmentdef Basic [start=$0801] .segmentdef Code [start=$80d] .segmentdef Data [startAfter="Code"] .segment Basic :BasicUpstart(main) .encoding "petscii_mixed" .const CH = '\n' .label SCREEN = $400 .segment Code main: { .label cursor = 2 .label msg = 6 .label line = 4 lda #<$400 sta.z cursor lda #>$400 sta.z cursor+1 lda #<$400 sta.z line lda #>$400 sta.z line+1 lda #<MESSAGE sta.z msg lda #>MESSAGE sta.z msg+1 __b1: // while(*msg) ldy #0 lda (msg),y cmp #0 bne __b2 // SCREEN[0xa0] = CH lda #CH sta SCREEN+$a0 // } rts __b2: // case '\n': // line += 0x28; // cursor = line; // break; lda #'\n' ldy #0 cmp (msg),y beq __b4 // case '\\': // line += 0x50; // cursor = line; // break; lda #'\\' cmp (msg),y beq __b5 // *msg & 0x3f lda #$3f and (msg),y // *cursor++ = *msg & 0x3f sta (cursor),y // *cursor++ = *msg & 0x3f; inc.z cursor bne !+ inc.z cursor+1 !: __b7: // msg++; inc.z msg bne !+ inc.z msg+1 !: jmp __b1 __b5: // line += 0x50 lda #$50 clc adc.z line sta.z cursor lda #0 adc.z line+1 sta.z cursor+1 lda.z cursor sta.z line lda.z cursor+1 sta.z line+1 jmp __b7 __b4: // line += 0x28 lda #$28 clc adc.z line sta.z cursor lda #0 adc.z line+1 sta.z cursor+1 lda.z cursor sta.z line lda.z cursor+1 sta.z line+1 jmp __b7 } .segment Data MESSAGE: .text @"hello\nworld\\again" .byte 0
// Original test: ./sadashiv/hw4/problem6/rol_2.asm // Author: sadashiv // Test source code follows // Test for "ROL Rd, Rs, Rt" {Rd <- Rs << (rotate) Rt (lowest 4 bits)}// // This test check for all possible cases of rotate left from 0 -15 // lbi r1,0xA1 slbi r1, 0x97 // r1 = 0xA197 lbi r2, 0x0 // rotate 0 times rol r4, r1, r2 // No change in r1 lbi r2, 0x51 // rotate 1 time rol r4, r1, r2 // r4 = 0x432F lbi r2, 0x62 // rotate 2 times rol r4, r1, r2 // r4 = 0x865E lbi r2, 0xA3 // rotate 3 times rol r4, r1, r2 // r4 = 0x0CBD lbi r2, 0x94 // rotate 4 times rol r4, r1, r2 // r4 = 0x197A lbi r2, 0x05 // rotate 5 times rol r4, r1, r2 // r4 = 0x32F4 lbi r2, 0xE6 // rotate 6 times rol r4, r1, r2 // r4 = 0x65E8 lbi r2, 0x27 // rotate 7 times rol r4, r1, r2 // r4 = 0xCBD0 lbi r2, 0x88 // rotate 8 times rol r4, r1, r2 // r4 = 0x971A lbi r2, 0x39 // rotate 9 times rol r4, r1, r2 // r4 = 0x2F43 lbi r2, 0x6A // rotate 10 times rol r4, r1, r2 // r4 = 0x5E86 lbi r2, 0x4B // rotate 11 times rol r4, r1, r2 // r4 = 0xBD0C lbi r2, 0x9C // rotate 12 times rol r4, r1, r2 // r4 = 0x7A19 lbi r2, 0x4D // rotate 13 times rol r4, r1, r2 // r4 = 0xF432 lbi r2, 0x9E // rotate 14 times rol r4, r1, r2 // r4 = 0xE865 lbi r2, 0xFF // rotate 15 times rol r4, r1, r2 // r4 = 0xD0CB halt
; A052533: Expansion of (1-x)/(1-x-3*x^2). ; 1,0,3,3,12,21,57,120,291,651,1524,3477,8049,18480,42627,98067,225948,520149,1197993,2758440,6352419,14627739,33684996,77568213,178623201,411327840,947197443,2181180963,5022773292,11566316181,26634636057,61333584600,141237492771,325238246571,748950724884,1724665464597,3971517639249,9145514033040,21060066950787,48496609049907,111676809902268,257166637051989,592197066758793,1363696977914760,3140288178191139,7231379111935419 mov $1,1 mov $2,1 lpb $0 sub $0,1 mov $3,$1 add $1,$2 add $2,$1 mul $3,2 sub $1,$3 lpe
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: StructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // // System includes // External includes // Project includes #include "containers/model.h" #include "includes/model_part_io.h" #include "structural_mechanics_application_variables.h" #include "custom_processes/shell_to_solid_shell_process.h" #include "custom_processes/solid_shell_thickness_compute_process.h" namespace Kratos { template<SizeType TNumNodes> ShellToSolidShellProcess<TNumNodes>::ShellToSolidShellProcess( ModelPart& rThisModelPart, Parameters ThisParameters ):mrThisModelPart(rThisModelPart), mThisParameters(ThisParameters) { KRATOS_TRY Parameters default_parameters = Parameters(R"( { "element_name" : "SolidShellElementSprism3D6N", "new_constitutive_law_name" : "", "model_part_name" : "", "number_of_layers" : 1, "export_to_mdpa" : false, "output_name" : "output", "computing_model_part_name" : "computing_domain", "create_submodelparts_external_layers" : false, "append_submodelparts_external_layers" : false, "initialize_elements" : false, "replace_previous_geometry" : true, "collapse_geometry" : false })" ); // Some initial checks if (mThisParameters.Has("collapse_geometry")) { if (mThisParameters["collapse_geometry"].GetBool()) { const std::string element_name = "Element3D" + std::to_string(TNumNodes) + "N"; if (mThisParameters.Has("element_name")) { Element const& r_clone_element = KratosComponents<Element>::Get(element_name); if (r_clone_element.GetGeometry().size() != TNumNodes) { mThisParameters["element_name"].SetString(element_name); } } else { default_parameters["element_name"].SetString(element_name); } } } mThisParameters.ValidateAndAssignDefaults(default_parameters); KRATOS_CATCH("") } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::Execute() { // If we compute the extrussion or the inverse extrussion if (mThisParameters["collapse_geometry"].GetBool()) { ExecuteCollapse(); } else { ExecuteExtrusion(); } } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::ReorderAllIds(const bool ReorderAccordingShellConnectivity) { if (!ReorderAccordingShellConnectivity) { NodesArrayType& r_nodes_array = mrThisModelPart.Nodes(); const auto it_node_begin = r_nodes_array.begin(); for(SizeType i = 0; i < r_nodes_array.size(); ++i) (it_node_begin + i)->SetId(i + 1); } else { // The name of the submodelpart const std::string& r_model_part_name = mThisParameters["model_part_name"].GetString(); ModelPart& r_geometry_model_part = r_model_part_name == "" ? mrThisModelPart : mrThisModelPart.GetSubModelPart(r_model_part_name); // Auxiliar values NodesArrayType& r_nodes_array = r_geometry_model_part.Nodes(); const SizeType geometry_number_of_nodes = r_nodes_array.size(); NodesArrayType& total_nodes_array = mrThisModelPart.Nodes(); const SizeType total_number_of_nodes = total_nodes_array.size(); // We reoder first all the nodes for(SizeType i = 0; i < total_number_of_nodes; ++i) (total_nodes_array.begin() + i)->SetId(total_number_of_nodes + i + 1); // We reoder now just the shell the nodes const auto it_node_begin = r_nodes_array.begin(); for(SizeType i = 0; i < geometry_number_of_nodes; ++i) { auto it_node = it_node_begin + i; it_node->SetId(i + 1); it_node->Set(VISITED, true); } // We reoder the rest of all the nodes IndexType aux_index = 0; for(SizeType i = 0; i < total_number_of_nodes; ++i) { auto it_node = total_nodes_array.begin() + i; if (it_node->IsNot(VISITED)) { it_node->SetId(geometry_number_of_nodes + aux_index + 1); aux_index++; } else { it_node->Set(VISITED, false); } } } ConditionsArrayType& condition_array = mrThisModelPart.Conditions(); for(SizeType i = 0; i < condition_array.size(); ++i) (condition_array.begin() + i)->SetId(i + 1); ElementsArrayType& element_array = mrThisModelPart.Elements(); for(SizeType i = 0; i < element_array.size(); ++i) (element_array.begin() + i)->SetId(i + 1); } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::ExecuteExtrusion() { KRATOS_TRY Model& r_current_model = mrThisModelPart.GetModel(); // The name of the submodelpart const std::string& r_model_part_name = mThisParameters["model_part_name"].GetString(); ModelPart& r_geometry_model_part = r_model_part_name == "" ? mrThisModelPart : mrThisModelPart.GetSubModelPart(r_model_part_name); // We initialize some values use later NodeType::Pointer p_node_begin = *(r_geometry_model_part.NodesBegin().base()); // Auxiliar model part where to store new nodes and elements ModelPart& r_auxiliar_model_part = r_current_model.CreateModelPart("Extruded" + r_model_part_name); const bool create_submodelparts_external_layers = mThisParameters["create_submodelparts_external_layers"].GetBool(); const bool append_submodelparts_external_layers = mThisParameters["append_submodelparts_external_layers"].GetBool(); ModelPart& r_auxiliar_model_part_upper = r_current_model.CreateModelPart("AuxiliarUpper" + r_model_part_name); ModelPart& r_auxiliar_model_part_lower = r_current_model.CreateModelPart("AuxiliarLower" + r_model_part_name); // Auxiliar values NodesArrayType& r_nodes_array = r_geometry_model_part.Nodes(); ElementsArrayType& r_elements_array = r_geometry_model_part.Elements(); const SizeType geometry_number_of_nodes = r_nodes_array.size(); const SizeType geometry_number_of_elements = r_elements_array.size(); const SizeType total_number_of_nodes = mrThisModelPart.Nodes().size(); const SizeType total_number_of_conditions = mrThisModelPart.Conditions().size(); const SizeType total_number_of_elements = mrThisModelPart.Elements().size(); const bool replace_previous_geometry = mThisParameters["replace_previous_geometry"].GetBool(); // First we reoder the ids ReorderAllIds(true); // We copy the dof from the first node const auto it_node_begin = r_nodes_array.begin(); NodeType::DofsContainerType dofs = it_node_begin->GetDofs(); // We initialize the thickness #pragma omp parallel for for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) { auto it_node = it_node_begin + i; it_node->SetValue(THICKNESS, 0.0); it_node->SetValue(NODAL_AREA, 0.0); } // We initialize the r_normal const auto it_elem_begin = r_elements_array.begin(); const array_1d<double, 3> zero_vector = ZeroVector(3); #pragma omp parallel for for(int i = 0; i < static_cast<int>(geometry_number_of_elements); ++i) (it_elem_begin + i)->SetValue(NORMAL, zero_vector); // Calculate the mean of the r_normal in all the nodes ComputeNodesMeanNormalModelPartNonHistorical(); // We compute the nodal thickness #pragma omp parallel for for(int i = 0; i < static_cast<int>(geometry_number_of_elements); ++i) { auto it_elem = it_elem_begin + i; // We get the thickness KRATOS_DEBUG_ERROR_IF_NOT(it_elem->GetProperties().Has(THICKNESS)) << "ERROR:: THICKNESS NOT DEFINED" << std::endl; const double thickness = it_elem->GetProperties()[THICKNESS]; auto r_geometry = it_elem->GetGeometry(); for (IndexType i = 0; i < TNumNodes; ++i) { auto& r_node = r_geometry[i]; double& node_thickness = r_node.GetValue(THICKNESS); #pragma omp atomic node_thickness += thickness; double& nodal_area = r_node.GetValue(NODAL_AREA); #pragma omp atomic nodal_area += 1.0; } } #pragma omp parallel for for(int i = 0; i < static_cast<int>(geometry_number_of_nodes); ++i) { auto it_node = it_node_begin + i; double& thickness = it_node->GetValue(THICKNESS); thickness /= it_node->GetValue(NODAL_AREA); } // We create the new nodes const SizeType number_of_layers = mThisParameters["number_of_layers"].GetInt(); for(IndexType i = 0; i < geometry_number_of_nodes; ++i) { auto it_node = it_node_begin + i; const array_1d<double, 3>& r_normal = it_node->GetValue(NORMAL); const double thickness = it_node->GetValue(THICKNESS); array_1d<double, 3> coordinates = it_node->Coordinates() - 0.5 * r_normal * thickness; const double delta_thickness = thickness/static_cast<double>(number_of_layers); IndexType node_id = total_number_of_nodes + i + 1; NodeType::Pointer p_node0 = r_auxiliar_model_part.CreateNewNode(node_id, coordinates[0], coordinates[1], coordinates[2]); // Set the DOFs in the nodes for (auto it_dof = dofs.begin(); it_dof != dofs.end(); ++it_dof) p_node0->pAddDof(*it_dof); // We copy the step data CopyVariablesList(p_node0, p_node_begin); // We add the node to the external layers if (create_submodelparts_external_layers) r_auxiliar_model_part_lower.AddNode(p_node0); for (IndexType j = 0; j < number_of_layers; ++j) { coordinates += r_normal * delta_thickness; node_id = (j + 1) * geometry_number_of_nodes + total_number_of_nodes + i + 1; NodeType::Pointer p_node1 = r_auxiliar_model_part.CreateNewNode(node_id, coordinates[0], coordinates[1], coordinates[2]); // Set the DOFs in the nodes for (auto it_dof = dofs.begin(); it_dof != dofs.end(); ++it_dof) p_node1->pAddDof(*it_dof); // We copy the step data CopyVariablesList(p_node1, p_node_begin); // We add the node to the external layers if (create_submodelparts_external_layers && j == (number_of_layers - 1)) r_auxiliar_model_part_upper.AddNode(p_node1); } // We set the flag TO_ERASE for later remove the nodes it_node->Set(TO_ERASE, replace_previous_geometry); } const std::string& element_name = mThisParameters["element_name"].GetString(); Element const& r_clone_element = KratosComponents<Element>::Get(element_name); KRATOS_ERROR_IF_NOT(r_clone_element.GetGeometry().size() == 2 * TNumNodes) << "ERROR: Element " << element_name << " has a different number of nodes to " << 2 * TNumNodes << std::endl; // We will save the list of properties ids to later set the CL std::unordered_set<IndexType> set_id_properties; // We create the new elements IndexType element_counter = total_number_of_elements; for(IndexType i = 0; i < geometry_number_of_elements; ++i) { auto it_elem = r_elements_array.begin() + i; auto p_prop = it_elem->pGetProperties(); set_id_properties.insert(p_prop->Id()); for (IndexType j = 0; j < number_of_layers; ++j) { std::vector<IndexType> element_node_ids (2 * TNumNodes); for (IndexType k = 0; k < TNumNodes; ++k) { const IndexType index_node = it_elem->GetGeometry()[k].Id(); element_node_ids[k] = total_number_of_nodes + index_node + j * geometry_number_of_nodes; element_node_ids[k + TNumNodes] = total_number_of_nodes + index_node + (j + 1) * geometry_number_of_nodes; } element_counter++; r_auxiliar_model_part.CreateNewElement(element_name, element_counter, element_node_ids, p_prop); } // We set the flag TO_ERASE for later remove the elements it_elem->Set(TO_ERASE, replace_previous_geometry); } // We create the conditions if necessary if (create_submodelparts_external_layers) { const std::string condition_name = "SurfaceCondition3D" + std::to_string(TNumNodes) + "N"; IndexType condition_counter = total_number_of_conditions; for(IndexType i = 0; i < geometry_number_of_elements; ++i) { auto it_elem = r_elements_array.begin() + i; auto p_prop = it_elem->pGetProperties(); set_id_properties.insert(p_prop->Id()); std::vector<IndexType> upper_condition_node_ids (TNumNodes); std::vector<IndexType> lower_condition_node_ids (TNumNodes); for (IndexType k = 0; k < TNumNodes; ++k) { const IndexType index_node = it_elem->GetGeometry()[k].Id(); lower_condition_node_ids[TNumNodes - (k + 1)] = total_number_of_nodes + index_node; // We invert the order for the lower face to have the normal in the right direction upper_condition_node_ids[k] = total_number_of_nodes + index_node + number_of_layers * geometry_number_of_nodes; } condition_counter++; r_auxiliar_model_part_lower.CreateNewCondition(condition_name, condition_counter, lower_condition_node_ids, p_prop); condition_counter++; r_auxiliar_model_part_upper.CreateNewCondition(condition_name, condition_counter, upper_condition_node_ids, p_prop); } } // We reassign a new constitutive law ReassignConstitutiveLaw(r_geometry_model_part, set_id_properties); // In case we replace the geometry if (replace_previous_geometry) { ReplacePreviousGeometry(r_geometry_model_part, r_auxiliar_model_part); } // We copy the external layers if (create_submodelparts_external_layers) { const std::string name_upper = "Upper_" + r_model_part_name; ModelPart& r_upper_model_part = append_submodelparts_external_layers ? r_geometry_model_part.CreateSubModelPart(name_upper) : mrThisModelPart.CreateSubModelPart(name_upper); r_upper_model_part.AddNodes( r_auxiliar_model_part_upper.NodesBegin(), r_auxiliar_model_part_upper.NodesEnd() ); r_upper_model_part.AddConditions( r_auxiliar_model_part_upper.ConditionsBegin(), r_auxiliar_model_part_upper.ConditionsEnd() ); const std::string name_lower = "Lower_" + r_model_part_name; ModelPart& r_lower_model_part = append_submodelparts_external_layers ? r_geometry_model_part.CreateSubModelPart(name_lower) : mrThisModelPart.CreateSubModelPart(name_lower); r_lower_model_part.AddNodes( r_auxiliar_model_part_lower.NodesBegin(), r_auxiliar_model_part_lower.NodesEnd() ); r_lower_model_part.AddConditions( r_auxiliar_model_part_lower.ConditionsBegin(), r_auxiliar_model_part_lower.ConditionsEnd() ); } // We add to the computing model part if available const std::string& computing_model_part_name = mThisParameters["computing_model_part_name"].GetString(); if (computing_model_part_name != "") { ModelPart& r_computing_model_part = mrThisModelPart.GetSubModelPart(computing_model_part_name); r_computing_model_part.AddNodes( r_auxiliar_model_part.NodesBegin(), r_auxiliar_model_part.NodesEnd() ); r_computing_model_part.AddElements( r_auxiliar_model_part.ElementsBegin(), r_auxiliar_model_part.ElementsEnd() ); r_computing_model_part.AddConditions( r_auxiliar_model_part_upper.ConditionsBegin(), r_auxiliar_model_part_upper.ConditionsEnd() ); r_computing_model_part.AddConditions( r_auxiliar_model_part_lower.ConditionsBegin(), r_auxiliar_model_part_lower.ConditionsEnd() ); } // Reorder again all the IDs ReorderAllIds(); // We initialize the new elements if (mThisParameters["initialize_elements"].GetBool()) { InitializeElements(); } // Export to *.mdpa if desired if (mThisParameters["export_to_mdpa"].GetBool()) { ExportToMDPA(); } // Clean the model CleanModel(); KRATOS_CATCH("") } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::ExecuteCollapse() { KRATOS_TRY Model& r_current_model = mrThisModelPart.GetModel(); // The name of the submodelpart const std::string& r_model_part_name = mThisParameters["model_part_name"].GetString(); ModelPart& r_geometry_model_part = r_model_part_name == "" ? mrThisModelPart : mrThisModelPart.GetSubModelPart(r_model_part_name); // We initialize some values use later NodeType::Pointer p_node_begin = *(r_geometry_model_part.NodesBegin().base()); // Auxiliar model part where to store new nodes and elements ModelPart& r_auxiliar_model_part = r_current_model.CreateModelPart("Collapsed" + r_model_part_name); // We compute the thickness SolidShellThickComputeProcess thickness_process(r_geometry_model_part); thickness_process.Execute(); // Auxiliar values NodesArrayType& r_nodes_array = r_geometry_model_part.Nodes(); ElementsArrayType& r_elements_array = r_geometry_model_part.Elements(); const SizeType geometry_number_of_elements = r_elements_array.size(); const SizeType total_number_of_nodes = mrThisModelPart.Nodes().size(); const SizeType total_number_of_elements = mrThisModelPart.Elements().size(); const bool replace_previous_geometry = mThisParameters["replace_previous_geometry"].GetBool(); // First we reoder the ids ReorderAllIds(true); // We copy the dof from the first node const auto it_node_begin = r_nodes_array.begin(); NodeType::DofsContainerType dofs = it_node_begin->GetDofs(); // Initial check const SizeType number_of_layers = mThisParameters["number_of_layers"].GetInt(); KRATOS_ERROR_IF(number_of_layers > 1) << "Collapsed only compatible with one layer" << std::endl; // We get the element name const std::string& element_name = mThisParameters["element_name"].GetString(); Element const& r_clone_element = KratosComponents<Element>::Get(element_name); KRATOS_ERROR_IF_NOT(r_clone_element.GetGeometry().size() == TNumNodes) << "ERROR: Element " << element_name << " has a different number of nodes to " << TNumNodes << std::endl; // We will save the list of properties ids to later set the CL std::unordered_set<IndexType> set_id_properties; // We create the new nodes and elements const auto it_elem_begin = r_elements_array.begin(); IndexType node_id = total_number_of_nodes + 1; IndexType element_id = total_number_of_elements + 1; std::vector<IndexType> element_node_ids (TNumNodes); for(IndexType i = 0; i < geometry_number_of_elements; ++i) { auto it_elem = it_elem_begin + i; // Getting properties and geometry auto p_prop = it_elem->pGetProperties(); auto& r_geometry = it_elem->GetGeometry(); // Adding property set_id_properties.insert(p_prop->Id()); // Collapsing nodes for (IndexType i_node = 0; i_node < TNumNodes; ++i_node) { const array_1d<double, 3> coordinates = 0.5 * r_geometry[i_node].Coordinates() + 0.5 * r_geometry[i_node + TNumNodes].Coordinates(); NodeType::Pointer p_node = r_auxiliar_model_part.CreateNewNode(node_id, coordinates[0], coordinates[1], coordinates[2]); p_node->SetValue(THICKNESS, r_geometry[i_node].GetValue(THICKNESS)); element_node_ids[i_node] = node_id; // Set the DOFs in the nodes for (auto it_dof = dofs.begin(); it_dof != dofs.end(); ++it_dof) p_node->pAddDof(*it_dof); // We copy the step data CopyVariablesList(p_node, p_node_begin); ++node_id; } // Now we create the new elements r_auxiliar_model_part.CreateNewElement(element_name, element_id, element_node_ids, p_prop); // We set the flag TO_ERASE for later remove the nodes and elements it_elem->Set(TO_ERASE, replace_previous_geometry); for (auto& r_node : r_geometry) { r_node.Set(TO_ERASE, replace_previous_geometry); } ++element_id; } // We reassign a new constitutive law ReassignConstitutiveLaw(r_geometry_model_part, set_id_properties); // In case we replace the geometry if (replace_previous_geometry) { ReplacePreviousGeometry(r_geometry_model_part, r_auxiliar_model_part); } // We add to the computing model part if available const std::string& computing_model_part_name = mThisParameters["computing_model_part_name"].GetString(); if (computing_model_part_name != "") { ModelPart& r_computing_model_part = mrThisModelPart.GetSubModelPart(computing_model_part_name); r_computing_model_part.AddNodes( r_auxiliar_model_part.NodesBegin(), r_auxiliar_model_part.NodesEnd() ); r_computing_model_part.AddElements( r_auxiliar_model_part.ElementsBegin(), r_auxiliar_model_part.ElementsEnd() ); } // Reorder again all the IDs ReorderAllIds(); // We initialize the new elements if (mThisParameters["initialize_elements"].GetBool()) { InitializeElements(); } // Export to *.mdpa if desired if (mThisParameters["export_to_mdpa"].GetBool()) { ExportToMDPA(); } // Clean the model CleanModel(); KRATOS_CATCH("") } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::ReplacePreviousGeometry( ModelPart& rGeometryModelPart, ModelPart& rAuxiliarModelPart ) { // Finally we remove the old nodes and elements mrThisModelPart.RemoveNodesFromAllLevels(TO_ERASE); mrThisModelPart.RemoveElementsFromAllLevels(TO_ERASE); // We copy the new model part to the original one rGeometryModelPart.AddNodes( rAuxiliarModelPart.NodesBegin(), rAuxiliarModelPart.NodesEnd() ); rGeometryModelPart.AddElements( rAuxiliarModelPart.ElementsBegin(), rAuxiliarModelPart.ElementsEnd() ); } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::ReassignConstitutiveLaw( ModelPart& rGeometryModelPart, std::unordered_set<IndexType>& rSetIdProperties ) { const std::string& new_constitutive_law_name = mThisParameters["new_constitutive_law_name"].GetString(); if (new_constitutive_law_name != "") { auto p_constitutive_law = KratosComponents<ConstitutiveLaw>().Get(new_constitutive_law_name).Clone(); for (auto id_prop : rSetIdProperties) { auto p_prop = rGeometryModelPart.pGetProperties(id_prop); p_prop->SetValue(CONSTITUTIVE_LAW, p_constitutive_law); } } } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::InitializeElements() { ElementsArrayType& element_array = mrThisModelPart.Elements(); for(SizeType i = 0; i < element_array.size(); ++i) (element_array.begin() + i)->Initialize(); } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::ExportToMDPA() { const std::string& output_name = mThisParameters["output_name"].GetString(); std::ofstream output_file; ModelPartIO model_part_io(output_name, IO::WRITE); model_part_io.WriteModelPart(mrThisModelPart); } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> void ShellToSolidShellProcess<TNumNodes>::CleanModel() { // The original model part name const std::string& r_model_part_name = mThisParameters["model_part_name"].GetString(); // If we remove the Extruded/Collapsed model part const bool replace_previous_geometry = mThisParameters["replace_previous_geometry"].GetBool(); const bool collapse_geometry = mThisParameters["collapse_geometry"].GetBool(); // Getting the model Model& r_current_model = mrThisModelPart.GetModel(); // Removing model parts if (replace_previous_geometry) { if (collapse_geometry) { r_current_model.DeleteModelPart("Collapsed" + r_model_part_name); } else { r_current_model.DeleteModelPart("Extruded" + r_model_part_name); } } r_current_model.DeleteModelPart("AuxiliarUpper" + r_model_part_name); r_current_model.DeleteModelPart("AuxiliarLower" + r_model_part_name); } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> inline void ShellToSolidShellProcess<TNumNodes>::ComputeNodesMeanNormalModelPartNonHistorical() { // Tolerance const double tolerance = std::numeric_limits<double>::epsilon(); // The name of the submodelpart const std::string& r_model_part_name = mThisParameters["model_part_name"].GetString(); ModelPart& r_geometry_model_part = r_model_part_name == "" ? mrThisModelPart : mrThisModelPart.GetSubModelPart(r_model_part_name); // We iterate over the nodes NodesArrayType& r_nodes_array = r_geometry_model_part.Nodes(); const int num_nodes = static_cast<int>(r_nodes_array.size()); #pragma omp parallel for for(int i = 0; i < num_nodes; ++i) (r_nodes_array.begin() + i)->SetValue(NORMAL, ZeroVector(3)); // Sum all the nodes normals ElementsArrayType& r_elements_array = r_geometry_model_part.Elements(); #pragma omp parallel for for(int i = 0; i < static_cast<int>(r_elements_array.size()); ++i) { auto it_elem = r_elements_array.begin() + i; GeometryType& this_geometry = it_elem->GetGeometry(); // Aux coordinates array_1d<double, 3> aux_coords; aux_coords = this_geometry.PointLocalCoordinates(aux_coords, this_geometry.Center()); it_elem->SetValue(NORMAL, this_geometry.UnitNormal(aux_coords)); const unsigned int number_nodes = this_geometry.PointsNumber(); for (unsigned int i = 0; i < number_nodes; ++i) { auto& this_node = this_geometry[i]; aux_coords = this_geometry.PointLocalCoordinates(aux_coords, this_node.Coordinates()); const array_1d<double, 3>& r_normal = this_geometry.UnitNormal(aux_coords); auto& aux_normal = this_node.GetValue(NORMAL); for (unsigned int index = 0; index < 3; ++index) { #pragma omp atomic aux_normal[index] += r_normal[index]; } } } #pragma omp parallel for for(int i = 0; i < num_nodes; ++i) { auto it_node = r_nodes_array.begin() + i; array_1d<double, 3>& r_normal = it_node->GetValue(NORMAL); const double norm_normal = norm_2(r_normal); if (norm_normal > tolerance) r_normal /= norm_normal; else KRATOS_ERROR << "WARNING:: ZERO NORM NORMAL IN NODE: " << it_node->Id() << std::endl; } } /***********************************************************************************/ /***********************************************************************************/ template<SizeType TNumNodes> inline void ShellToSolidShellProcess<TNumNodes>::CopyVariablesList( NodeType::Pointer pNodeNew, NodeType::Pointer pNodeOld ) { auto& node_data = pNodeNew->SolutionStepData(); auto& node_data_reference = pNodeOld->SolutionStepData(); node_data.SetVariablesList(node_data_reference.pGetVariablesList()); } /***********************************************************************************/ /***********************************************************************************/ template class ShellToSolidShellProcess<3>; template class ShellToSolidShellProcess<4>; // class ShellToSolidShellProcess } // namespace Kratos
; ; Copyright (C) 2021 Louis Hobson <louis-hobson@hotmail.co.uk>. All Rights Reserved. ; ; Distributed under MIT licence as a part of a cellular automaton project. ; For details, see: https://github.com/louishobson/GameOfLife/blob/master/LICENSE ; ; IO.asm ; ; Various functions for interfacing with the screen and keyboard. ; Include macros #include "Macros.asm" ; This function sets up the an empty interrupt. SETUP_EMPTY_INTERRUPT: ; Disable interrupts di ; Load the vector table with the interrupt position. ld a,CUSTOM_INTERRUPT_BYTE ld b,0 ld hl,INTERRUPT_VTABLE SETUP_EMPTY_INTERRUPT_VTABLE_LOOP: ld (hl),a inc hl djnz SETUP_EMPTY_INTERRUPT_VTABLE_LOOP ld (hl),a ; Load the interrupt. It will simply enable interrupts and return. ld hl,CUSTOM_INTERRUPT ld (hl),$fb inc hl ld (hl),$ed inc hl ld (hl),$4d ; Set the interrupt register ld a,INTERRUPT_VTABLE_UPPER ld i,a ; Enable interrupts in mode 2 and return im 2 ei ret ; This function takes a character code to print stored in a. ; It sets hl to the address in memory of the position of the bitmap for that character. GET_BITMAP_LOCATION: ; Load a into hl ld h,0 ld l,a ; Multiply hl by 8 add hl,hl add hl,hl add hl,hl ; Add the offset to the character bitmaps to hl ld a,h add a,CHAR_BITMAPS_UPPER ld h,a ; Return ret ; This function calculates the beginning position of a character in screen pixel memory. ; d should be set to the y coordinate [0;23] ; e should be set to the x coordinate [0;31] ; See http://www.breakintoprogram.co.uk/computers/zx-spectrum/screen-memory-layout for the memory layout. ; We actually want 0 1 0 0 0 Y4 Y3 0 0 0 Y2 Y1 Y0 X4 ... X0 GET_PIXEL_LOCATION: ; Get Y3,4,5 in position. ld a,d and %00000111 rrca rrca rrca ; Get all of X in position (only the bottom 5 bytes should be set anyway) or e ; Store our bottom byte in e ld e,a ; Load Y into a, and mask the required bits ld a,d and %00011000 ; Set the front bit or %01000000 ; Load into d and return ld d,a ret ; This function calculates the position of a character in screen attribute memory. ; d should be set to the y coordinate [0;23] ; e should be set to the x coordinate [0;31] ; We need (y * 32) + x, that is ; 0 1 0 1 1 0 Y4 Y3 Y2 Y1 Y0 X4 ... X0 GET_ATTRIBUTE_LOCATION: ; We can get Y4...Y0 in position by shifting. ld a,d rrca rrca rrca ; Load into d for later, then get only Y2...Y0 ld d,a and %11100000 ; Add in X4...X0 and we are done for the lower byte or e ld e,a ; Now finish off the top byte. ; Also add in the offset to the start of attributes. ld a,d and %00000011 or %01011000 ld d,a ; Return ret ; This function prints a string. ; The location in memory of the start of the string is hl. ; The coordinates on the screen is de (see GET_PIXEL_LOCATION). ; Modifies bc PRINT_STRING: ; Push de and call GET_PIXEL_LOCATION push de call GET_PIXEL_LOCATION ; Loop over characters PRINT_STRING_CHAR_LOOP: ; Get the character in a ld a,(hl) ; Return if the character is 0 and a jr nz,PRINT_STRING_NOT_NULL pop de ret PRINT_STRING_NOT_NULL: ; If there is a newline, jump back to the top cp 10 jr nz,PRINT_STRING_NOT_CR inc hl pop de inc d ld e,0 jr PRINT_STRING PRINT_STRING_NOT_CR: ; Push hl and get the bitmap location push hl call GET_BITMAP_LOCATION ; Loop over writing the character ld b,8 PRINT_STRING_WRITE_LOOP: ; Copy over the byte ld a,(hl) ld (de),a ; Get the next byte of the bitmap inc hl ; Get the location of the next pixel byte inc d ; Loop djnz PRINT_STRING_WRITE_LOOP ; Pop hl back and increment it pop hl inc hl ; Increment the pixel location ld a,d sub 8 ld d,a inc e ; Loop jr PRINT_STRING_CHAR_LOOP ; This function fills the screen pixel data with the contents of a. ; de and bc are modified. FILL_PIXEL_DATA: ; Set de to PIXEL_DATA ld de,PIXEL_DATA ; Clear the screen. Since there are $1800 bytes to write, we write 256 bytes $18 times. ld bc,PIXEL_DATA_LENGTH_UPPER FILL_PIXEL_DATA_LOOP: ld (de),a inc de djnz FILL_PIXEL_DATA_LOOP dec c jr nz,FILL_PIXEL_DATA_LOOP ; Return ret ; This function fills the screen attribute data with the contents of a. ; de and bc are modified. FILL_ATTRIBUTE_DATA: ; Set de to ATTRIBUTE_DATA ld de,ATTRIBUTE_DATA ; Clear the screen. Since there are $0300 bytes to write, we write 256 bytes 3 times. ld bc,ATTRIBUTE_DATA_LENGTH_UPPER FILL_ATTRIBUTE_DATA_LOOP: ld (de),a inc de djnz FILL_ATTRIBUTE_DATA_LOOP dec c jr nz,FILL_ATTRIBUTE_DATA_LOOP ; Return ret ; This function fills b bytes of the screen attribute data with the contents of a. ; The starting position should be loaded in de. PARTIAL_FILL_ATTRIBUTE_DATA: ; Save a push af ; Set get the location of the first attribute call GET_ATTRIBUTE_LOCATION ; Reload a pop af ; Keep writing while b is non-zero PARTIAL_FILL_ATTRIBUTE_DATA_LOOP: ld (de),a inc de djnz PARTIAL_FILL_ATTRIBUTE_DATA_LOOP ; Return ret ; This function xors b bytes of the screen attribute data with the contents of a. ; The starting position should be loaded in de. ; c will be modified. PARTIAL_XOR_ATTRIBUTE_DATA: ; Save a in c. ld c,a ; Set get the location of the first attribute call GET_ATTRIBUTE_LOCATION ; Keep xoring while b is non-zero PARTIAL_XOR_ATTRIBUTE_DATA_LOOP: ld a,(de) xor c ld (de),a inc de djnz PARTIAL_XOR_ATTRIBUTE_DATA_LOOP ; Return ret ; This function gets keys. ; The groups should be in a, and the keys will be loaded to a. ; A mask of the specific keys in the groups being searched should be loaded to d. ; If keys are pressed, only when they are released will the function return. ; Otherwise the function will not block. ; de will be modified. GET_KEYBOARD_INPUT: ; Complement the group and save it in e cpl ld e,a ; Get the keypress and mask with b in a,(KEYBOARD_IN_ID) cpl and d ; If there were no keys being pressed, return ret z ; Push the current a push af ; Otherwise switch back to the original while the keys are being pressed GET_KEYBOARD_INPUT_WAIT: ld a,e in a,(KEYBOARD_IN_ID) cpl and d jr nz,GET_KEYBOARD_INPUT_WAIT ; Pop the original a and return pop af ret
; A120462: Expansion of -2*x*(-3-2*x+4*x^2) / ((x-1)*(2*x+1)*(2*x-1)*(1+x)). ; 0,6,4,22,20,86,84,342,340,1366,1364,5462,5460,21846,21844,87382,87380,349526,349524,1398102,1398100,5592406,5592404,22369622,22369620,89478486,89478484,357913942,357913940,1431655766,1431655764,5726623062,5726623060,22906492246,22906492244,91625968982,91625968980,366503875926,366503875924,1466015503702,1466015503700,5864062014806,5864062014804,23456248059222,23456248059220,93824992236886,93824992236884,375299968947542,375299968947540,1501199875790166,1501199875790164,6004799503160662,6004799503160660,24019198012642646,24019198012642644,96076792050570582,96076792050570580,384307168202282326,384307168202282324,1537228672809129302,1537228672809129300,6148914691236517206,6148914691236517204,24595658764946068822,24595658764946068820,98382635059784275286,98382635059784275284,393530540239137101142,393530540239137101140,1574122160956548404566,1574122160956548404564,6296488643826193618262,6296488643826193618260,25185954575304774473046,25185954575304774473044,100743818301219097892182,100743818301219097892180,402975273204876391568726,402975273204876391568724,1611901092819505566274902,1611901092819505566274900,6447604371278022265099606,6447604371278022265099604,25790417485112089060398422,25790417485112089060398420,103161669940448356241593686,103161669940448356241593684,412646679761793424966374742,412646679761793424966374740,1650586719047173699865498966,1650586719047173699865498964,6602346876188694799461995862,6602346876188694799461995860,26409387504754779197847983446,26409387504754779197847983444,105637550019019116791391933782,105637550019019116791391933780,422550200076076467165567735126,422550200076076467165567735124,1690200800304305868662270940502 lpb $0 add $1,1 mul $1,2 mov $2,$0 trn $0,2 mul $1,2 sub $2,$0 sub $1,$2 lpe mul $1,2 mov $0,$1
PUBLIC __clib_exit_stack_size IF __clib_exit_stack_size > 0 ld hl, -(__clib_exit_stack_size * 2) add hl,sp ld sp,hl ENDIF
AgathasRoom_Script: call AgathaShowOrHideExitBlock call EnableAutoTextBoxDrawing ld hl, AgathasRoomTrainerHeaders ld de, AgathasRoom_ScriptPointers ld a, [wAgathasRoomCurScript] call ExecuteCurMapScriptInTable ld [wAgathasRoomCurScript], a ret AgathaShowOrHideExitBlock: ; Blocks or clears the exit to the next room. ld hl, wCurrentMapScriptFlags bit 5, [hl] res 5, [hl] ret z CheckEvent EVENT_BEAT_AGATHAS_ROOM_TRAINER_0 jr z, .blockExitToNextRoom ld a, $e jp .setExitBlock .blockExitToNextRoom ld a, $3b .setExitBlock ld [wNewTileBlockID], a lb bc, 0, 2 predef_jump ReplaceTileBlock ResetAgathaScript: xor a ld [wAgathasRoomCurScript], a ret AgathasRoom_ScriptPointers: dw AgathaScript0 dw DisplayEnemyTrainerTextAndStartBattle dw AgathaScript2 dw AgathaScript3 dw AgathaScript4 AgathaScript4: ret AgathaScriptWalkIntoRoom: ; Walk six steps upward. ld hl, wSimulatedJoypadStatesEnd ld a, D_UP ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hl], a ld a, $6 ld [wSimulatedJoypadStatesIndex], a call StartSimulatingJoypadStates ld a, $3 ld [wAgathasRoomCurScript], a ld [wCurMapScript], a ret AgathaScript0: ld hl, AgathaEntranceCoords call ArePlayerCoordsInArray jp nc, CheckFightingMapTrainers xor a ldh [hJoyPressed], a ldh [hJoyHeld], a ld [wSimulatedJoypadStatesEnd], a ld [wSimulatedJoypadStatesIndex], a ld a, [wCoordIndex] cp $3 ; Is player standing one tile above the exit? jr c, .stopPlayerFromLeaving CheckAndSetEvent EVENT_AUTOWALKED_INTO_AGATHAS_ROOM jr z, AgathaScriptWalkIntoRoom .stopPlayerFromLeaving ld a, $2 ldh [hSpriteIndexOrTextID], a call DisplayTextID ; "Don't run away!" ld a, D_UP ld [wSimulatedJoypadStatesEnd], a ld a, $1 ld [wSimulatedJoypadStatesIndex], a call StartSimulatingJoypadStates ld a, $3 ld [wAgathasRoomCurScript], a ld [wCurMapScript], a ret AgathaEntranceCoords: dbmapcoord 4, 10 dbmapcoord 5, 10 dbmapcoord 4, 11 dbmapcoord 5, 11 db -1 ; end AgathaScript3: ld a, [wSimulatedJoypadStatesIndex] and a ret nz call Delay3 xor a ld [wJoyIgnore], a ld [wAgathasRoomCurScript], a ld [wCurMapScript], a ret AgathaScript2: call EndTrainerBattle ld a, [wIsInBattle] cp $ff jp z, ResetAgathaScript ld a, $1 ldh [hSpriteIndexOrTextID], a call DisplayTextID ld a, $1 ld [wChampionsRoomCurScript], a ret AgathasRoom_TextPointers: dw AgathaText1 dw AgathaDontRunAwayText AgathasRoomTrainerHeaders: def_trainers AgathasRoomTrainerHeader0: trainer EVENT_BEAT_AGATHAS_ROOM_TRAINER_0, 0, AgathaBeforeBattleText, AgathaEndBattleText, AgathaAfterBattleText db -1 ; end AgathaText1: text_asm ld hl, AgathasRoomTrainerHeader0 call TalkToTrainer jp TextScriptEnd AgathaBeforeBattleText: text_far _AgathaBeforeBattleText text_end AgathaEndBattleText: text_far _AgathaEndBattleText text_end AgathaAfterBattleText: text_far _AgathaAfterBattleText text_end AgathaDontRunAwayText: text_far _AgathaDontRunAwayText text_end
;/* ; * Microsoft Confidential ; * Copyright (C) Microsoft Corporation 1981-1991 ; * All Rights Reserved. ; */ page ,132 TITLE Disk Ioctl functions include version.inc ; set build flags include biosseg.inc ; define bios segment structure INCLUDE devsym.inc INCLUDE bpb.inc INCLUDE ioctl.inc INCLUDE bootform.inc INCLUDE msdskpr.inc INCLUDE msequ.inc INCLUDE msbds.inc INCLUDE msgroup.inc ; Establish Bios_Data segment DSK_TIMEOUT_ERR EQU 80h ; Time out error (no media present). DSK_CHANGELINE_ERR EQU 6h ; Change line error DSK_ILLEGAL_COMBINATION EQU 0ch ; Return code of ah=18h function. MULTI_TRK_ON EQU 10000000b ; User spcified mutitrack=on, ; or system turns ; ;---------------------------------------------------------------------------- ; ; M00x : Setting 'lstdrv' properly at Setown ioctl call. Earlier it used ; to set lstdrv to -1 on a setown call which got qbasic confused ; Now the lstdrv update is done inside checksingle ; ; M060 : Bug # 5065. Added retries for INT 13 ah=18h call in case of errors ; ; M066 : B#5833. Modification M060 was required only for Toshiba machines ; and the problem on Toshiba machines will be solved by the ; 'setmedia' driver. So the retry for ah=18 call is not ; required. Also because of the retry & disk reset, format ; becomes slow on IBM external floppy disk drives which does ; not support the set_media_type call. ; ;---------------------------------------------------------------------------- ; ; ========================================================================== ; Most of the disk routines keep ES:[DI] set up pointing to the ; currently selected bds. This is often assumed to be the standard ; operating environment and in some cases may not be mentioned in ; the subroutine headers where it will be assumed. ; ; Most of the ioctl routines use DS:[BX] as a pointer to their ; request packet for at least part of their life. ; ========================================================================== EXTRN ZeroSeg:WORD EXTRN PtrSav:DWORD EXTRN Xfer_Seg:WORD EXTRN MultiTrk_Format_Flag:BYTE EXTRN Multrk_Flag:WORD EXTRN Start_Sec_H:WORD EXTRN Dpt:DWORD EXTRN fHave96:BYTE EXTRN Formt_EOT:BYTE EXTRN HdNum:BYTE EXTRN TrkNum:WORD EXTRN Gap_Patch:BYTE EXTRN rFlag:BYTE EXTRN CurTrk:WORD EXTRN CurSec:BYTE EXTRN CurHd:BYTE EXTRN SpSav:WORD EXTRN SecCnt:WORD EXTRN Eot:BYTE EXTRN Step_Drv:BYTE EXTRN Start_Bds:DWORD EXTRN fSetOwner:BYTE EXTRN Tim_Drv:BYTE EXTRN DiskSector:BYTE ; These are some special variables defined for us ;** EXTRN Max_Sectors_Curr_Sup:abs EXTRN SectorsPerTrack:WORD EXTRN TrackTable:BYTE EXTRN MediaType:BYTE EXTRN Media_Set_For_Format:BYTE EXTRN Had_Format_Error:BYTE EXTRN TempDpt:DWORD ; ========================================================================== ; close data, open Bios_Code segment ToCode EXTRN CheckSingle:NEAR EXTRN GetBP:NEAR EXTRN MapError:NEAR EXTRN HasChange:NEAR EXTRN DiskIO:NEAR EXTRN Done:NEAR EXTRN Mov_Media_Ids:NEAR EXTRN Disk:NEAR EXTRN IoSetup:NEAR EXTRN Set_Changed_DL:NEAR EXTRN SetDrive:NEAR EXTRN BC_CmdErr:NEAR EXTRN Bios_Data_WORD:WORD ; ========================================================================== ; ; NOTE: GetAccessFlag/SetAccessFlag is unpublished function. ; ; This function is intended to give the user to control the ; bds table flags of unformatted_media bit. ; GetAccessFlag will show the status - ; a_DiskAccess_Control.dac_access_flag = 0 disk i/o not allowed ; 1 disk i/o allowed ; SetAccessFlag will set/reset the unformatted_media bit in flags - ; a_DiskAccess_Control.dac_access_flag = 0 allow disk i/o ; 1 disallow disk i/o ; ========================================================================== ; generic ioctl dispatch tables IoReadJumpTable db 8 ;maximum number (zero based) dw GetDeviceParameters ;60h dw ReadTrack ;61h dw VerifyTrack ;62h dw Cmd_Error_Proc ;overlapped with os2 subfunction dw Cmd_Error_Proc dw Cmd_Error_Proc dw GetMediaId ;66h dw GetAccessFlag ;67h unpublished function dw SenseMediaType ;68 IoWriteJumpTable db 7 dw SetDeviceParameters ;40h dw WriteTrack ;41h dw FormatTrack ;42h dw Cmd_Error_Proc dw Cmd_Error_Proc dw Cmd_Error_Proc dw SetMediaId ;46h dw SetAccessFlag ;47h unpublished function ; ========================================================================== ; IOC_DC_Table ; ; This table contains all of the valid generic IOCtl Minor codes for ; major function 08 to be used by the Ioctl_Support_Query function. ; Added for 5.00 ; ========================================================================== IOC_DC_Table LABEL BYTE db GET_DEVICE_PARAMETERS ; 60H db SET_DEVICE_PARAMETERS ; 40H db READ_TRACK ; 61H db WRITE_TRACK ; 41H db VERIFY_TRACK ; 62H db FORMAT_TRACK ; 42H db GET_MEDIA_ID ; 66h changed from 63h db SET_MEDIA_ID ; 46h changed from 43h db GET_ACCESS_FLAG ; 67h Unpublished func changed frm 64h db SET_ACCESS_FLAG ; 47h Unpublished func changed frm 44h db SENSE_MEDIA_TYPE ; 68 Added in 5.00 IOC_DC_TABLE_LEN EQU $ - OFFSET IOC_DC_Table ; ========================================================================== ; Do_Generic_IOCtl: perform generic ioctl request ; ; input: AL contains logical drive ; ; functions are dispatched through a call. On return, carry indicates ; error code in al. Note::bES:b& ds undefined on return from ; subfunctions. ; ; ========================================================================== PUBLIC Do_Generic_IOCtl Do_Generic_IOCtl PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING call SetDrive ; ES:DI Points to bds for drive. push ES les BX,[PtrSav] ; ES:BX Points to request header. cmp ES:[BX].MajorFunction,RAWIO mov AL,ES:[BX].MinorFunction pop ES jne IoctlFuncErr ; cas note: Could do the above two blocks in reverse order. ; Would have to preserve al for SetDrive mov SI,OFFSET IoReadJumpTable test AL,GEN_IOCTL_FN_TST ; test of req. function jnz NotGenericWrite ; function is a read. mov SI,OFFSET IoWriteJumpTable NotGenericWrite: and AL,NOT GEN_IOCTL_FN_TST ; get rid of read/write bit sub AL,40h ; offset for base function cmp AL,CS:[SI] ja IoctlFuncErr cbw shl AX,1 inc SI add SI,AX call CS:[SI] mov DS,Bios_Data_Word ; Exit code now assumes this ASSUME DS:Bios_Data mov AH,81h ; Return this status in case of carry ret ; Pass carry flag through to exit code ; Cmd_Error_Proc is called as a proceedure and also use ; as a fall through from above Cmd_Error_Proc: ASSUME DS:Bios_Data pop DX ; Clear up stack IoctlFuncErr: ASSUME DS:Bios_Data jmp BC_CmdErr Do_Generic_IOCtl ENDP ; ========================================================================== ;** GetDeviceParameters: ; ; GetDeviceParameters implements the generic ioctl function: ; majorcode=RAWIO, minorcode=GetDeviceParameters (60h) ; ; ENTRY (ES:di) = BDS for drive ; PtrSav = long pointer to request header ; EXIT ??? BUGBUG ; USES ??? BUGBUG ; ========================================================================== GetDeviceParameters PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING ; Copy info from bds to the device parameters packet lds BX,[PtrSav] ; DS:BX points to request header. ASSUME DS:NOTHING lds BX,[BX].GenericIOCtl_Packet ; (DS:BX) = return buffer mov AL,ES:[DI].BDS_FormFactor mov [BX].DP_DeviceType,AL mov AX,ES:[DI].BDS_Flags and AX,fNon_Removable + fChangeLine ; Mask off other bits mov [BX].DP_DeviceAttributes,AX mov AX,ES:[DI].BDS_cCyln mov [BX].DP_Cylinders,AX xor AL,AL ; Set media type to default mov [BX].DP_MediaType,AL ; copy recommended bpb lea SI,ES:[DI].BDS_RBPB test [BX].dp_specialfunctions,build_device_bpb jz UseBpbPresent ; get the correct disk in the drive push DS ; Save request packet segment mov DS,Bios_Data_Word ; Point back to Bios_Data ASSUME DS:Bios_Data call CheckSingle call GetBP ; Build the bpb from scratch pop DS ; Restore request packet segment ASSUME DS:NOTHING jc GetParmRet lea SI,ES:[DI].BDS_BPB ; Use this subfield of bds instead UseBpbPresent: lea DI,[BX].DP_BPB ; This is where the result goes ; BUGBUG - why use "small" version? jgl mov CX,SIZE A_BPB - 6 ; For now use 'small' bpb ; Shoot! Our segments are backwards for a copy! ; Damn! Reverse 'em! push DS push ES pop DS pop ES rep movsb clc GetParmRet: ret GetDeviceParameters ENDP ; ========================================================================== ; SetDeviceParameters: ; ; input: ES:di points to bds for drive ; ========================================================================== SetDeviceParameters PROC NEAR ASSUME DS:Bios_Data lds BX,[PtrSav] ; DS:BX points to request header. ASSUME DS:NOTHING lds BX,DS:[BX].GenericIOCtl_Packet ; Make sure the fCHANGED_BY_FORMAT flag gets set to kick ; Dos into looking at the BPB or ES:[DI].BDS_Flags,fCHANGED_BY_FORMAT or fCHANGED test [BX].dp_specialfunctions,only_set_tracklayout jnz setTrackTable ; Copy info from the device parameters packet to bds mov AL,[BX].DP_DeviceType mov ES:[DI].BDS_FormFactor,AL mov AX,[BX].DP_Cylinders mov ES:[DI].BDS_cCyln,AX ; If change line is not loaded then ignore changeling flag mov AX,[BX].DP_DeviceAttributes push DS ; Save packet segment mov DS,Bios_Data_Word ASSUME DS:Bios_Data cmp [fHave96],0 ; Do we have changeline support? pop DS ASSUME DS:NOTHING jnz HaveChange and AX,NOT fChangeLine ; Ignore all bits except non_removable and changeline HaveChange: and AX,fNon_Removable or fChangeLine mov CX,ES:[DI].BDS_Flags and CX,NOT(fNon_Removable OR fChangeLine OR Good_TrackLayOut OR UNFORMATTED_MEDIA) or AX,CX mov ES:[DI].BDS_Flags,AX mov AL,[BX].DP_MediaType ; Set media type push DS ; Save packet segment mov DS,Bios_Data_Word ASSUME DS:Bios_Data mov MediaType,AL pop DS ; Restore packet segment ASSUME DS:NOTHING ; The media changed (maybe) so we will have to do a set dasd ; the next time we format a track or ES:[DI].BDS_Flags,SET_DASD_TRUE push DI ; Save bds pointer ; Figure out what we are supposed to do with the bpb ; were we asked to install a fake bpb? test [BX].DP_SpecialFunctions,INSTALL_FAKE_BPB jnz SHORT InstallFakeBpb ; were we returning a fake bpb when asked to build a bpb? test ES:[DI].BDS_Flags,RETURN_FAKE_BPB jz SHORT InstallRecommendedBpb ; we were returning a fake bpb but we can stop now and ES:[DI].BDS_Flags,NOT RETURN_FAKE_BPB InstallRecommendedBpb: mov CX,SIZE A_BPB lea DI,ES:[DI].BDS_RBPB jmp SHORT CopyTheBpb InstallFakeBpb: or ES:[DI].BDS_Flags,RETURN_FAKE_BPB ; problem reported by whs. ; BUGBUG - why use "small" version? jgl mov CX,SIZE A_BPB - 6 ; move 'smaller' bpb lea DI,ES:[DI].BDS_BPB CopyTheBpb: lea SI,[BX].DP_BPB rep movsb Donewithbpbstuff: push DS ; Save packet segment mov DS,Bios_Data_Word ; Setup for ds -> Bios_Data ASSUME DS:Bios_Data call RestoreOldDpt ; Restore the old Dpt from TempDpt pop DS ; Restore packet segment pop DI ; Restore bds pointer setTrackTable: ; Set up track table (if neccessary) mov CX,[BX].DP_TrackTableEntries push DS ; Save packet segment mov DS,Bios_Data_Word ASSUME DS:Bios_Data mov SectorsPerTrack,CX pop DS ; Restore packet segment ASSUME DS:NOTHING and ES:[DI].BDS_Flags,NOT Good_TrackLayOut test [BX].DP_SpecialFunctions,TrackLayOut_Is_Good jz UglyTrackLayOut or ES:[DI].BDS_Flags,Good_TrackLayOut UglyTrackLayOut: cmp CX,MAX_SECTORS_IN_TRACK ja TooManyPerTrack jcxz SectorInfoSaved mov DI,OFFSET TrackTable lea SI,[BX].DP_SectorTable mov ES,Bios_Data_Word ; Trash our bds pointer StoreSectorInfo: inc DI ; Skip over cylinder inc DI ; Skip over head lodsw ; Get sector id stosb ; Copy it lodsw ; Get sector size call SectSizeToSectIndex stosb ; Store sector SIZE index loop StoreSectorInfo SectorInfoSaved: clc ret TooManyPerTrack: mov AL,0ch stc ret SetDeviceParameters ENDP ; ========================================================================== ; FormatTrack: ; if specialfunction byte is 1,then this is a status call to see if there is ; rom support for the combination of sec/trk and # of cyln,and if the ; combination is legal. if specialfunction byte is 0,then format the track. ; ; input: ES:di points to bds for drive ; ; output: ; for status call: ; specialfunction byte set to: ; 0 - rom support + legal combination ; 1 - no rom support ; 2 - illegal combination ; 3 - no media present ; carry cleared. ; ; for format track: ; carry set if error ; ; ========================================================================== FormatTrack PROC NEAR ASSUME DS:Bios_Data lds BX,[PtrSav] ; ES:BX points to request header. ASSUME DS:NOTHING lds BX,DS:[BX].GenericIOCtl_Packet test [BX].DP_SpecialFunctions,STATUS_FOR_FORMAT jz DoFormatTrack push DS ; Save packet mov DS,Bios_Data_Word ; Point to Bios_Data ASSUME DS:Bios_Data call SetMediaForFormat ; Also moves current Dpt to TempDpt pop DS ; Restore packet ASSUME DS:NOTHING mov [BX].DP_SpecialFunctions,AL clc ret DoFormatTrack: cmp ES:[DI].BDS_FormFactor,DEV_HARDDISK jne DoFormatDiskette mov DS,Bios_Data_Word ; Setup ds-> Bios_Data for verify jmp VerifyTrack DoFormatDiskette: mov CX,[BX].FP_Head mov DX,[BX].FP_Cylinder ; Load cylinder & head from pkt test [BX].FP_SpecialFunctions, DO_FAST_FORMAT ; Fast format request? mov DS,Bios_Data_Word ; Done with pkt seg, get to Bios_Data ASSUME DS:Bios_Data jz DoFormatDiskette_1 ; Go ahead if not multi-trk jmp VerifyTrack_Err ; Error, same as VerifyTrack_Err DoFormatDiskette_1: call SetMediaForFormat ; Also moves current Dpt to TempDpt cmp AL,1 ; ; ROM support for sec/trk,# trks comb? jz NeedToSetDasd ; Old rom. cmp AL,3 ; Time out error? jnz NoSetDasd ; No,fine.(at this point,don't care ; about the illegal combination.) jmp SHORT FormatFailed NeedToSetDasd: push DX call SetDasd ; AH=17h,int 13h pop DX NoSetDasd: call CheckSingle ; Do any needed diskette swapping mov AX,DX ; Get track from packet mov [TrkNum],AX mov BYTE PTR [HdNum],CL ; Store head from packet mov AH,CL mov BX,OFFSET TrackTable mov CX,SectorsPerTrack StoreCylinderHead: mov [BX],AX ; Store into TrackTable add BX,4 ; Skip to next sector field loop StoreCylinderHead mov CX,MaxErr ; Set up retry count FormatRetry: push CX mov BX,OFFSET TrackTable mov AL,BYTE PTR SectorsPerTrack mov AH,RomFormat mov Xfer_Seg,DS call ToRom pop CX jc FormatError ; Now verify the sectors just formatted. ; NOTE: because of bug in some BIOSes we have to ; set ES:BX to 00:00 push CX push bx xor bx,bx mov Xfer_seg,bx mov AL,BYTE PTR SectorsPerTrack mov AH,RomVerify mov CL,1 call ToRom pop bx pop CX jnc FormatOk FormatError: call ResetDisk mov [Had_Format_Error],1 push AX push CX push DX call SetMediaForFormat cmp AL,1 jnz WhileErr call SetDasd WhileErr: pop DX pop CX pop AX loop FormatRetry FormatFailed: mov [Had_Format_Error],1 ; Set the format error flag. cmp AH,DSK_CHANGELINE_ERR ; =06h. convert change line jne DoMapIt ; Error to time out error. mov AH,DSK_TIMEOUT_ERR ; =80h DoMapIt: jmp MapError FormatOk: mov [Had_Format_Error],0 ;reset the format error flag. ret FormatTrack ENDP ; fall into VerifyTrack ; ========================================================================== ; ; VerifyTrack: ; ; input: ES:di points to bds for drive ; ========================================================================== VerifyTrack PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING push DS ; Save Bios_Data lds BX,[PtrSav] ; DS:BX points to request header. ASSUME DS:NOTHING lds BX,[BX].GenericIOCtl_Packet ; Come here with DS:[BX] -> packet, ES:[DI] -> bds mov CX,[BX].VP_Cylinder ; get some stuff cuz ds will be moved mov AX,[BX].VP_Head mov DX,[BX].FP_TrackCount ; & number of tracks to verify mov BL,[BX].FP_SpecialFunctions ; Get option flag word pop DS ; Restore DS -> Bios_Data ASSUME DS:Bios_Data mov rFlag,romverify mov [CurTrk],CX mov [CurHd],AL ; **** ASSUME heads < 256 mov CX,[SectorsPerTrack] ;cl = sectors/track ; Check specialfunctions to see if DO_FAST_FORMAT has been ; specified if not we should go to the normal track verification ; routine. If fast format has been specified we should get the ; number of tracks to be verified and check it to see if it is ; > 255. If it is then it is an error and we should go to ; VerifyTrack_Err. If not multiply the number of tracks by the ; sectors per track to get the total number of sectors to be ; verified. This should also be lESs than equal to 255 ; otherwise we go to same error exit. If everything is okay ; we initalise cx to the total sectors. use ax as a temporary ; register. test BL,DO_FAST_FORMAT ; Special function requESted? jz NormVerifyTrack mov AX,DX ; Get ax = number of trks to verify or AH,AH jnz VerifyTrack_Err ; #tracks > 255 mul CL or AH,AH ; #sectors > 255 jnz VerifyTrack_Err mov CX,AX ; #sectors to verify ; set the multi track request flag test ES:[DI].BDS_Flags,fNon_Removable ; Hard disk? jz NormVerifyTrack test Multrk_Flag,MULTI_TRK_ON ; Multitrack operation = on? jz NormVerifyTrack mov MultiTrk_Format_Flag,1 ; Then set the flag NormVerifyTrack: xor AX,AX ; 1st sector ; Use 0:0 as the transfer address for verify xor BX,BX mov Xfer_Seg,BX ; Set transfer segment to zero, too call TrackIo mov MultiTrk_Format_Flag,0 ; Reset the flag. ret VerifyTrack_Err: mov AH,1 jmp MapError VerifyTrack ENDP ; ========================================================================== ; ; ReadTrack: ; ; input: ES:di points to bds for drive ; ; ========================================================================== ReadTrack proc NEAR ASSUME DS:Bios_Data,ES:NOTHING mov rFlag,ROMREAD jmp SHORT readWriteTrack ReadTrack ENDP ; ========================================================================== ; ; WriteTrack: ; ; input: ES:di points to bds for drive ; ; ========================================================================== WriteTrack proc NEAR ASSUME DS:Bios_Data,ES:NOTHING mov rFlag,ROMWRITE WriteTrack ENDP ; Fall into readWriteTrack ; ========================================================================== ; ; readWriteTrack: ; ; input: ; ES:di points to bds for drive ; rFlag - 2 for read,3 for write ; ; ========================================================================== ReadWriteTrack PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING ; save bds pointer segment so we can use it to access ; our packet. Notice that this is not the standard register ; assignment for accessing packets push ES les BX,[PtrSav] ; ES:BX -> to request header. les BX,ES:[BX].GenericIOCtl_Packet mov AX,ES:[BX].TrWp_Cylinder mov [CurTrk],AX mov AX,ES:[BX].TrWp_Head mov [CurHd],AL ; Assume heads < 256!!! mov AX,ES:[BX].TrWp_FirstSector mov CX,ES:[BX].TrWp_SectorsToReadWrite les BX,ES:[BX].TrWp_TransferAddress ; Get transfer address ; we just trashed our packet address, but we no longer care mov Xfer_Seg,es ; Pass transfer segment pop ES ; Restore bds segment ReadWriteTrack ENDP ; Fall into TrackIo ; ========================================================================== ; ; TrackIo: ; performs track read/write/verify ; ; input: ; rFlag - 2 = read ; 3 = write ; 4 = verify ; AX - Index into track table of first sector to io ; CX - Number of sectors to io ; Xfer_Seg:BX - Transfer address ; ES:DI - Pointer to bds ; CurTrk - Current cylinder ; CurHd - Current head ; ; ========================================================================== TrackIo PROC NEAR ; Procedure `disk' will pop stack to mov SpSav,sp ; SpSav and return if error call CheckSingle ; Ensure correct disk is in drv cmp [Media_Set_For_Format],1 ; See if we have already set disk jz Dptalreadyset ; base table push AX ; set up tables and variables for i/o push CX call IoSetup pop CX pop AX Dptalreadyset: ; Point si at the table entry of the mov SI,OFFSET TrackTable ; first sector to be io'd shl AX,1 shl AX,1 add SI,AX ; WE WANT: ; CX to be the number of times we have to loop ; DX to be the number of sectors we read on each iteration mov DX,1 test ES:[DI].BDS_Flags,Good_TrackLayOut jz ionextsector xchg DX,CX ; HEY! We can read all secs in one blow IoNextSector: push CX push DX inc SI ; Skip over the cylinder and head in inc SI ; the track table lodsb ; Get sector ID from track table mov [CurSec],AL ;assumptions for a fixed disk multi-track disk i/o ; 1). In the input CX (# of sectors to go) to TrackIo,only CL ; is valid. ; 2). Sector size should be set to 512 bytes. ; 3). Good track layout. test ES:[DI].BDS_Flags,fNon_Removable ; Fixed disk? jz IoRemovable ; No test Multrk_Flag,MULTI_TRK_ON ; Allow multi-track operation? jz IoRemovable ; No,don't do that. mov [SecCnt],DX ; # of sectors to i/o mov AX,DX call Disk pop DX pop CX clc ret IoRemovable: lodsb ; Get sector size index from track push AX ; table and save it ; Patch sector size in Dpt push SI push DS ; Save Bios_Data push AX ; Preserve whatever might be in ah mov AH,[Eot] ; Fetch Eot while ds-> Bios_Data lds SI,Dpt ASSUME DS:NOTHING mov BYTE PTR [SI].disk_sector_siz,AL mov [SI].disk_Eot,AH ; Set up the max number of sec/track pop AX ; Restore whatever was in ah pop DS ; Restore Bios_Data ASSUME DS:Bios_Data mov AL,DL mov [SecCnt],AX ; Set up the count of sectors to i/o call Disk pop si ; Advance buffer pointer by adding pop ax ; sector size call SectorSizeIndexToSectorSize add BX,AX pop DX pop CX loop IoNextSector cmp [Media_Set_For_Format],1 je NoNeedDone call Done ; set time of last access,and reset NoNeedDone: clc ; entries in Dpt. ret TrackIo ENDP ; ========================================================================== ; ; The sector size in bytes needs to be converted to an index value for the ibm ; rom. (0=>128,1=>256,2=>512,3=>1024). It is assumed that only these values ; are permissible. ; ; On Input AX contains sector size in bytes ; On Output AL Contains index ; All other registers preserved ; ; ========================================================================== SectSizeToSectIndex PROC NEAR ASSUME DS:NOTHING,ES:NOTHING cmp AH,2 ; examine upper byte only ja OneK mov AL,AH ; value in AH is the index! ret OneK: mov AL,3 ret SectSizeToSectIndex ENDP ; ========================================================================== ; ; ========================================================================== SectorSizeIndexToSectorSize PROC NEAR mov CL,AL mov AX,128 shl AX,CL ret SectorSizeIndexToSectorSize ENDP ; ========================================================================== ; ; SetDASD ; ; Set up the rom for formatting. ; we have to tell the rom bios what type of disk is in the drive. ; ; On Input - ES:di - Points to bds ; ; ========================================================================== SetDasd proc NEAR ASSUME DS:Bios_Data,ES:NOTHING cmp [Had_Format_Error],1 ; See if we've previously set dasd type je DoSetDasd test ES:[DI].BDS_Flags,SET_DASD_TRUE jz DasdHasBeenSet and ES:[DI].BDS_Flags,NOT SET_DASD_TRUE DoSetDasd: mov [Had_Format_Error],0 ; Reset it mov [Gap_Patch],50h ; Format gap for 48tpi disks mov AL,4 cmp ES:[DI].BDS_FormFactor,DEV_3INCH720KB jz DoSet cmp ES:[DI].BDS_FormFactor,DEV_5INCH96TPI jz GotBig mov AL,1 ; 160/320k in a 160/320k drive jmp SHORT DoSet GotBig: mov AL,2 ; 160/320k in a 1.2 meg drive cmp [MediaType],0 jne DoSet mov AL,3 ; 1.2meg in a 1.2meg drive mov [Gap_Patch],54h DoSet: push DS ; Preserve caller's DS, si push SI ; Get the disk parameter table address (DWORD address) from the ; location 0:[dskadr] and fix the head settle time in this to ; be 0fh. mov DS,ZeroSeg ; Point to interrupt vectors ASSUME DS:NOTHING lds SI,DWORD PTR DS:[DskAdr] mov DS:[SI].Disk_Head_Sttl,0fh pop SI pop DS ; Restore caller's DS, si ASSUME DS:Bios_Data mov AH,17h ; Set command to set dasd type mov DL,ES:[DI].BDS_DriveNum ; Set drive number int 13h ; Call rom-bios DasdHasBeenSet: mov AH,BYTE PTR ES:[DI].BDS_BPB.BPB_SECTORSPERTRACK mov [Formt_EOT],AH ret SetDasd ENDP ; ========================================================================== ; ; Set Media Type for Format ; Performs the int 13 with ah = 18h to see if the medium described in the ; BPB area in the BDS can be handled by the rom. ; On Input, ES:DI -> current BDS. ; The status of the operation is returned in AL ; ; - 0 - if the support is available,and the combination is valid. ; - 1 - no rom support ; - 2 - illegal combination ; - 3 - no media present (rom support exists but cannot determine now) ; ; Flags also may be altered. All other registers preserved. ; If the call to rom returns no error,then the current Dpt is "replaced" by ; the one returned by the rom. This is Done by changing the pointer in [Dpt] ; to the one returned. the original pointer to the disk base table is stored ; in TempDpt, until it is restored. ; ; ========================================================================== SetMediaForFormat PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING push CX push DX ; If we have a format error, then do not change Dpt, TempDpt. ; but we need to call int 13h, ah=18h again. cmp [Had_Format_Error],1 je SkipSaveDskAdr xor AL,AL ; If already done return 0 cmp [Media_Set_For_Format],1 jnz DoSetMediaForFormat jmp SetMediaRet ; Media already set DoSetMediaForFormat: push ES ; Preserve caller's ES, si push SI mov ES,ZeroSeg ; Point to interrupt vectors les SI,DWORD PTR ES:[DskAdr] ; Get pointer to disk base table mov WORD PTR [Dpt],SI mov WORD PTR [Dpt+2],es ; Save pointer to table ; Initialize the head settle time to 0fh. See the offsets ; given in dskprm.inc. mov ES:[SI].Disk_Head_Sttl,0fh pop SI ; Restore caller's ES, si pop ES SkipSaveDskAdr: mov CX,ES:[DI].BDS_cCyln ; Get number of cylinders dec CX ; Cylinder must be zero based and CH,03h ; Blank out unnecessary bits ror CH,1 ; Put in int form ror CH,1 xchg CH,CL or CL,BYTE PTR ES:[DI].BDS_BPB.BPB_SECTORSPERTRACK ;get number of sectors mov DL,ES:[DI].BDS_DriveNum ; Get drive number push ES ; CAS - really need to save 'em all? push DS push SI push DI mov AH,18h ; Set media for format M066 int 13h ; Call rom bios M066 jc FormaStatErr ; M066 COMMENT ^ mov si, MaxErr ; retry count M060 next_18: ; M060 mov AH,18h ; Set media for format M060 int 13h ; Call rom bios M060 jnc @f ; M060 dec si ; M060 jz FormaStatErr ; M060 xor ah, ah ; M060 int 13h ; M060 jmp next_18 ; M060 ; ES:DI points to a disk base table for this combination ; for this drive. @@: ; M060 ENDCOMMENT ^ cmp [Had_Format_Error],1 ; Did we have a format error? je skip_disk_base_setting push ES ; Save segment returned by the rom mov ES,ZeroSeg ; Point to interrupt vector segment les SI,DWORD PTR ES:[DskAdr] ; Get current disk base table mov WORD PTR [TempDpt],SI mov WORD PTR [TempDpt+2],es ; Save it ; CAS -- didn't used to reload ES -> ZeroSeg here. ; Seemed like a bug mov ES,ZeroSeg mov WORD PTR ES:[DskAdr],DI pop WORD PTR ES:[DskAdr+2] ; replace with one returned by rom mov [Media_Set_For_Format],1 skip_disk_base_setting: xor AL,AL ; Legal combination + rom support code mov [Had_Format_Error],AL ; Reset the flag jmp SHORT PopStatRet FormaStatErr: cmp AH,DSK_ILLEGAL_COMBINATION ; Illegal combination = 0ch je FormatStatIllegalComb cmp AH,DSK_TIMEOUT_ERR ; 80h je FormatStatTimeOut mov AL,1 ; Function not supported. jmp SHORT PopStatRet FormatStatIllegalComb: ; Function supported,but mov AL,2 ; Illegal sect/trk,trk combination. jmp SHORT PopStatRet FormatStatTimeOut: ; Function supported,but mov AL,3 ; Media not present. PopStatRet: pop DI ; Restore caller's DS ES DI SI pop SI pop DS pop ES SetMediaRet: pop DX pop CX ret SetMediaForFormat ENDP ASSUME DS:NOTHING,ES:NOTHING ; ========================================================================== ; ; RESET THE DRIVE ; ; we also set [Step_Drv] to -1 to force the main disk routine to use the ; slow head settle time for the next operation. this is because the reset ; operation moves the head to cylinder 0,so we need to do a seek the next ; time around - there is a problem with 3.5" drives in that the head does ; not settle down in time,even for read operations!! ; ; ========================================================================== PUBLIC ResetDisk ResetDisk proc NEAR ASSUME DS:Bios_Data,ES:NOTHING push AX cmp [Media_Set_For_Format],1; Reset while formatting? jne ResetDisk_cont ; Then verify operation in "fmt & vrfy" mov [Had_Format_Error],1 ; Might have failed. ResetDisk_cont: ; So signals that we had a format error xor AH,AH ; Set command to reset disk int 13h ; Call the rom-bios mov [Step_Drv],-1 ; Zap up the speed pop AX ret ResetDisk ENDP ; ========================================================================== ; ; This routine sets up the drive parameter table with the values needed for ; format,does an int 13. values in Dpt are restored after a verify is done. ; ; on entry - ES:DI - points to bds for the drive ; Xfer_Seg:BX - points to trkbuf ; AL - number of sectors ; AH - int 13 function code ; CL - sector number for verify ; DS - Bios_Data ; ; ON EXIT - DS,DI,ES,BX remain unchanged. ; AX and flags are the results of the int 13 ; ; ========================================================================== ToRom proc NEAR ASSUME DS:Bios_Data,ES:NOTHING push BX push SI ; Compaq bug fix - check whether we are using new ROM ; functionality to set up format, not merely if it exists. ; This was formerly a check against [new_rom] test [Media_Set_For_Format],1 jnz GotValidDpt push AX push ES ; Save bds segment cmp ES:[DI].BDS_FormFactor,ffsmall ; is it a 3.5" drive? pushf ; Save the result for when ES: is busy mov ES,ZeroSeg les SI,DWORD PTR ES:[DskAdr] ; Get pointer to disk base table mov WORD PTR [Dpt],SI mov WORD PTR [Dpt+2],es ; Save pointer to table mov AL,[Formt_EOT] mov ES:[SI].disk_eot,AL mov AL,[Gap_Patch] mov ES:[SI].Disk_Formt_Gap,AL ; Important for format mov ES:[SI].Disk_Head_Sttl,15 ; Assume we are doing a seek operation ; Set up motor start correctly for 3.5" drives popf ; Get result of earlier cmp jnz MotorStrtOK mov ES:[SI].Disk_Motor_Strt,4 MotorStrtOK: pop ES ; Restore bds segment pop AX GotValidDpt: mov DX,[TrkNum] ; Set track number mov CH,DL ; Set low 8 bits in ch mov DL,ES:[DI].BDS_DriveNum ; Set drive number mov DH,[HdNum] ; Set head number push ES ; Save bds segment mov ES,Xfer_Seg int 13h ; Call the rom-bios routines pop ES ; Restore bds segment pop SI pop BX ret ToRom ENDP ; ========================================================================== ; ; get the owner of the physical drive represented by the logical drive in al. ; the assumption is that we **always** keep track of the owner of a drive!! ; if this is not the case, the system may hang, just following the linked list. ; ; ========================================================================== PUBLIC IOCtl_GetOwn IOCtl_GetOwn proc NEAR ASSUME DS:Bios_Data call SetDrive mov AL,ES:[DI].BDS_DriveNum ; Get physical drive number les DI,[Start_Bds] ; Get start of bds chain OwnLoop: cmp ES:[DI].BDS_DriveNum,AL jne GetNextBDS test ES:[DI].BDS_Flags,FI_Own_Physical jnz ExitOwn GetNextBDS: les DI,ES:[DI].BDS_Link jmp OwnLoop IOCtl_GetOwn ENDP ; ========================================================================== ; ; set the ownership of the physical drive represented by the logical drive in ; al to al. ; ; ========================================================================== PUBLIC IOCtl_SetOwn IOCtl_SetOwn PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING call SetDrive mov BYTE PTR [fSetOwner],1 ; set flag for CheckSingle to ; look at. call CheckSingle ; set ownership of drive mov BYTE PTR [fSetOwner],0 ; reset flag ; M00x - BEGIN ; push ES ; mov ES,ZeroSeg ; mov BYTE PTR ES:[lstdrv],-1 ; set up sdsb as well ; pop ES ; restore bds pointer ; M00x - END IOCtl_SetOwn ENDP ; fall into ExitOwn ; ========================================================================== ; ; if there is only one logical drive assigned to this physical drive, return ; 0 to user to indicate this. Enter with ES:di -> the owner's bds. ; ; ========================================================================== ExitOwn PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING xor CL,CL test ES:[DI].BDS_Flags,FI_Am_Mult jz ExitNoMult mov CL,ES:[DI].BDS_DriveLet ; Get logical drive number inc cl ; Get it 1-based ExitNoMult: lds BX,[PtrSav] ASSUME DS:NOTHING mov DS:[BX].unit,CL clc ; Exit normal termination ret ExitOwn ENDP ; ========================================================================== ; ; moves the old Dpt that had been saved in TempDpt back to Dpt. this is done ; only if the first byte of TempDpt is not -1. ; all registers (including flags) are preserved. ; ; ========================================================================== RestoreOldDpt PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING ; if we have already restored the disk base table earlier, ; do not do it again. push AX xor AL,AL mov [Had_Format_Error],AL ; Reset flag and get current xchg [Media_Set_For_Format],AL ; flag setting or AL,AL jz DontRestore push SI push DS push ES lds SI,[TempDpt] ASSUME DS:NOTHING mov ES,Bios_Data_Word ; CAS -- bleeeech! ASSUME ES:Bios_Data mov ES,ZeroSeg mov WORD PTR ES:[DskAdr],SI mov WORD PTR ES:[DskAdr+2],DS pop ES pop DS ASSUME DS:Bios_Data pop si DontRestore: pop ax clc ; Clear carry ret RestoreOldDpt ENDP ; ========================================================================== ; get media id ; ========================================================================== ; ; FUNCTION: get the volume label,the system id and the serial number from ; the media that has the extended boot record. ; for the conventional media,this routine will return "unknown ; media type" error to dos. ; ; INPUT : ES:di -> bds table for this drive. ; ; OUTPUT: the request packet filled with the information,if not carry. ; if carry set,then al contains the device driver error number ; that will be returned to dos. ; register DS,DX,AX,CX,DI,SI destroyed. ; ; SUBROUTINES TO BE CALLED: ; BootIo:NEAR ; ; LOGIC: ; to recognize the extended boot record,this logic will actually ; access the boot sector even if it is a hard disk. ; note:the valid extended bpb is recognized by looking at the mediabyte ; field of bpb and the extended boot signature. ; ; { ; get logical drive number from bds table; ; rFlag = read operation; ; BootIo; /*get the media boot record into the buffer ; if (no error) then ; if (extended boot record) then ; { set volume label,volume serial number and system id ; of the request packet to those of the boot record; ; }; ; else /*not an extended bpb */ ; { set register al to "unknown media.." error code; ; set carry bit; ; }; ; else ; ret; /*already error code is set in the register al ; ; ========================================================================== GetMediaId PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING call ChangeLineChk mov AL,ES:[DI].BDS_DriveLet ; Logical drive number mov rFlag,ROMREAD ; Read operation call BootIo ; Read boot sector into DiskSector jc IOCtl_If1 cmp DiskSector.EXT_BOOT_BPB.BPB_MEDIADESCRIPTOR,0f0h jb IOCtl_If2 ; brif not valid (0f0h - 0ffh) cmp DiskSector.EXT_BOOT_SIG,ext_boot_signature ; =29h jnz IOCtl_If2 ; Extended boot record les DI,[PtrSav] ; ES:di points to request header. les DI,ES:[BX].GenericIOCtl_Packet mov SI,OFFSET DiskSector.EXT_BOOT_SERIAL add DI,mi_serial mov CX,SIZE EXT_BOOT_SERIAL+SIZE EXT_BOOT_VOL_LABEL+SIZE EXT_SYSTEM_ID rep movsb ; Move frm Bios_Data into request packet clc ret IOCtl_If2: mov AL,Error_UnKnown_Media ; =7 stc IOCtl_If1: ret GetMediaId ENDP ; ========================================================================== ; set media id ; ========================================================================== ; function: set the volume label, the system id and the serial number of ; the media that has the extended boot record. ; for the conventional media, this routine will return "unknown ; media.." error to dos. ; this routine will also set the corresponding informations in ; the bds table. ; ; input : ES:di -> bds table for this drive. ; ; output: the extended boot record in the media will be set according to ; the request packet. ; if carry set, then al contains the device driver error number ; that will be returned to dos. ; ; subroutines to be called: ; BootIo:NEAR ; ; logic: ; ; ; { ; get drive_number from bds; ; rFlag = "read operation"; ; BootIo; ; if (no error) then ; if (extended boot record) then ; { set volume label,volume serial number and system id ; of the boot record to those of the request packet; ; rFlag = "write operation"; ; get drive number from bds; ; BootIo; /*write it back*/ ; }; ; else /*not an extended bpb */ ; { set register al to "unknown media.." error code; ; set carry bit; ; ret; /*return back to caller */ ; }; ; else ; ret; /*already error code is set */ ; ; ========================================================================== SetMediaId PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING call ChangeLineChk mov AL,ES:[DI].BDS_DriveLet ; Logical drive number mov DL,AL ; Save it for the time being. mov rFlag,ROMREAD ; Read operation push DX ; Save drive number call BootIo ; Read boot sec to Bios_Data:DiskSector pop DX ; Restore drive number jc IOCtl_If6 ; Valid? (0f0h-0ffh?) cmp DiskSector.EXT_BOOT_BPB.BPB_MEDIADESCRIPTOR,0f0h jb IOCtl_If7 ; Brif not cmp DiskSector.EXT_BOOT_SIG,ext_boot_signature ; =41 (=29h) jnz IOCtl_If7 ; Extended boot record push ES ; Save BDS pointer push DI push DS ; Point ES To boot record pop ES mov DI,OFFSET DiskSector.EXT_BOOT_SERIAL lds SI,[PtrSav] ; DS:si points to request header. ASSUME DS:NOTHING lds SI,DS:[SI].GenericIOCtl_Packet add SI,mi_serial mov CX,SIZE EXT_BOOT_SERIAL+SIZE EXT_BOOT_VOL_LABEL+SIZE EXT_SYSTEM_ID rep movsb push ES ; point ds back to Bios_Data pop DS ; if dhigh ; cas - only disable for binary compare ASSUME DS:Bios_Data ; endif pop DI ;restore bds pointer pop ES call Mov_Media_Ids ; update the bds media id info. mov AL,DL ; set drive number for BootIo mov rFlag,ROMWRITE call BootIo ; write it back. mov [Tim_Drv],-1 ; make sure chk_media check the driver ret ; return with error code from BootIo IOCtl_If7: mov AL,Error_UnKnown_Media ; =7 stc IOCtl_If6: ret SetMediaId ENDP ; ========================================================================== ; BootIo ; ========================================================================== ; ; function: read/write the boot record into boot sector. ; ; input : ; al=logical drive number ; rFlag = operation (read/write) ; ; output: for read operation,the boot record of the drive specified in bds ; be read into the DiskSector buffer. ; for write operation,the DiskSector buffer image will be written ; to the drive specified in bds. ; if carry set,then al contains the device driver error number ; that will be returned to dos. ; AX,CX,DX register destroyed. ; if carry set,then al will contain the error code from DiskIO. ; ; subroutines to be called: ; DiskIO:NEAR ; ; logic: ; ; { ; first_sector = 0; /*logical sector 0 is the boot sector */ ; sectorcount = 1; /*read 1 sector only */ ; buffer = DiskSector; /*read it into the DiskSector buffer */ ; call DiskIO (rFlag,drive_number,first_sector,sectorcount,buffer); ; } ; ========================================================================== BootIo PROC NEAR ASSUME DS:Bios_Data push ES push DI push BX push DS pop ES ; Point ES: to Bios_Data ; Call DiskIO to read/write the boot sec. The parameters which ; need to be initialized for this subroutine out here are ; - Transfer address to Bios_Data:DiskSector ; - Low sector needs to be initalized to 0. this is a reg. param ; - Hi sector in [Start_Sec_H] needs to be initialised to 0. ; - Number of sectors <-- 1 mov DI,OFFSET DiskSector ; ES:di -> transfer address xor DX,DX ; First sector (h) -> 0 mov [Start_Sec_H],DX ; Start sector (h) -> 0 mov CX,1 ; One sector call DiskIO pop BX pop DI pop ES ret BootIo ENDP ; ========================================================================== ; ChangeLineChk ; ========================================================================== ; ; when the user calls get/set media id call before dos establishes the media ; by calling "media_chk",the change line activity of the drive is going to be ; lost. this routine will check the change line activity and will save the ; history in the flags. ; ; FUNCTION: check the change line error activity ; ; INPUT : ES:di -> bds table. ; ; OUTPUT: flag in bds table will be updated if change line occurs. ; ; SUBROUTINES TO BE CALLED: ; Set_Changed_DL ; ; ========================================================================== ChangeLineChk PROC NEAR ASSUME DS:Bios_Data mov DL,ES:[DI].BDS_DriveNum or DL,DL ; Fixed disk? js ChanngeLnChkRet ; Yes, skip it. test ES:[DI].BDS_Flags,RETURN_FAKE_BPB ;Don't do it duing format. jnz ChanngeLnChkRet cmp [fHave96],1 ; This rom support change line? jne ChanngeLnChkRet call HasChange ; This drive support change line? jz ChanngeLnChkRet ; Do nothing ; Execute the rom disk interrupt to check changeline activity. mov AH,16h int 13h jnc ChanngeLnChkRet ; No change line activity? push bx mov BX,fCHANGED ; Update flag in BDS for this call Set_Changed_DL ; physical drive pop bx ChanngeLnChkRet: ret ChangeLineChk ENDP ; ========================================================================== ; GetAccessFlag ; ========================================================================== ; ; FUNCTION: get the status of UNFORMATTED_MEDIA bit of flags in bds table ; ; INPUT : ; ES:di -> bds table ; ; OUTPUT: a_DiskAccess_Control.dac_access_flag = 0 if disk i/o not allowed. ; = 1 if disk i/o allowed. ; ========================================================================== GetAccessFlag PROC ASSUME DS:Bios_Data,ES:NOTHING lds BX,[PtrSav] ; DS:BX points to request header. ASSUME DS:NOTHING lds BX,DS:[BX].GenericIOCtl_Packet mov AL,0 ; Assume result is unformatted test ES:[DI].BDS_Flags,UNFORMATTED_MEDIA ; Is it unformtted media? jnz GafDone ; Done if unformatted inc al ; Return true for formatted GafDone: mov [BX].dac_access_flag,AL ret GetAccessFlag ENDP ; ========================================================================== ; SetAccessFlag ; ========================================================================== ; ; function: set/reset the UNFORMATTED_MEDIA bit of flags in bds table ; ; input : ; ES:di -> bds table ; ; output: unformtted_media bit modified according to the user request ; ========================================================================== SetAccessFlag PROC ASSUME DS:Bios_Data lds BX,[PtrSav] ; ES:BX points to request header. lds BX,DS:[BX].GenericIOCtl_Packet and ES:[DI].BDS_Flags,NOT UNFORMATTED_MEDIA cmp [BX].DAC_Access_Flag,0 jne saf_Done or ES:[DI].BDS_Flags,UNFORMATTED_MEDIA saf_Done: ret SetAccessFlag ENDP ; ========================================================================== ; Ioctl_Support_Query ; ========================================================================== ; ; New device command which was added in DOS 5.00 to allow a query of a ; specific specific GENERIC IOCtl to see if it is supported. Bit 7 in the ; device attributes specifies if this function is supported. ; ; ========================================================================== PUBLIC Ioctl_Support_Query Ioctl_Support_Query PROC NEAR ASSUME DS:Bios_Data,ES:NOTHING push ES les BX,[PtrSav] ; ES:BX Points to request header. mov AX,WORD PTR ES:[BX].MajorFunction ; AL == Major, AH == Minor cmp AL,IOC_DC ; See if major code is 8 jne NoSupport push CS ; ES == Code segment pop ES ASSUME ES:Bios_Code mov CX,IOC_DC_TABLE_LEN mov DI,OFFSET IOC_DC_Table ; ES:DI -> Major table xchg AL,AH ; Put minor code in AL repne scasb ; Scan for minor code in AL jne NoSupport ; Was it found mov AX,100h ; Signal ioctl is supported jmp SHORT IoctlSupExit IoctlSupExit: pop ES clc ret NoSupport: pop ES jmp BC_CmdErr Ioctl_Support_Query ENDP ; ========================================================================== ; GetMediaSenseStatus ; ========================================================================== ; ; FUNCTION: Will return the type of diskette media in the specified DOS ; diskette drive and whether the media is the default type ; for that drive. (default type means the max size for that ; drive) ; ; INPUT : ES:DI -> BDS table ; OUTPUT: If carry clear ; DS:BX -> Updated IOCtlPacket ; ; Special Function at offset 0: ; 0 - Media detected is not default type ; 1 - Media detected is default type ; ; Device Type at offset 1: ; 2 - 720K 3.5" 80 tracks ; 7 - 1.44M 3.5" 80 tracks ; 9 - 2.88M 3.5" 80 tracks ; ; Error Codes returned in AX if carry set: ; ; 8102 - Drive not ready - No disk is in the drive. ; 8107 - Unknown media type - Drive doesn't support this function or ; the media is really unkown, any error ; other than "media not present" ; ; ========================================================================== SenseMediaType PROC ASSUME DS:Bios_Data,ES:NOTHING lds BX,[PtrSav] ; DS:BX points to request header. ASSUME DS:NOTHING lds BX,DS:[BX].GenericIOCtl_Packet mov WORD PTR DS:[BX],00 ; Initialize the 2 packet bytes mov DL,ES:[DI].BDS_DriveNum ; Get int 13h drive number from BDS xor DH,DH ; DX == physical drive number mov AH,20h ; Get Media Type function int 13h ; If no carry media type in AL jc MediaSenseErr ; ELSE error code in AH inc BYTE PTR DS:[BX] ; Signal media type is default (bit 1) DetermineMediaType: dec AL cmp AL,2 ; Chk for 720K ie: (3-1) = 2 je GotMediaType add AL,4 cmp AL,7 ; Chk for 1.44M ie: (4-1+4) = 7 je GotMediaType cmp AL,9 ; Chk for 2.88M ie: (6-1+4) = 9 jne UnknownMediaType ; Just didn't recognize media type GotMediaType: mov DS:[BX+1],AL ; Save the return value clc ; Signal success ret ; We come here if carry was set after the int 13h call. ; Before we process the error we need to see if it was ; a real error or just that the media type is not the ; default for the type of drive but was readily identified. MediaSenseErr: cmp AH,32h ; See if not default media erro je DetermineMediaType ; Not really an error mov AL,2 ; Now assume drive not ready cmp AH,31h ; See if media was present je SenseErrExit ; Return drive not ready UnknownMediaType: mov AL,7 ; Just don't know the media type SenseErrExit: mov AH,81h ; Signal error return stc ret SenseMediaType ENDP ; ========================================================================== Bios_Code ends end  
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright (C) 2022 Intel Corporation ; ; SPDX-License-Identifier: MIT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %include "options.asm" %include "lz0a_const.asm" %include "data_struct2.asm" %include "bitbuf2.asm" %include "huffman.asm" %include "igzip_compare_types.asm" %include "stdmac.asm" %include "reg_sizes.asm" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %define curr_data rax %define tmp1 rax %define f_index rbx %define code rbx %define tmp4 rbx %define tmp5 rbx %define tmp6 rbx %define tmp2 rcx %define hash rcx %define tmp3 rdx %define stream rsi %define f_i rdi %define code_len2 rbp %define hmask1 rbp %define m_out_buf r8 %define level_buf r9 %define dist r10 %define hmask2 r10 %define code2 r12 %define f_end_i r12 %define file_start r13 %define len r14 %define hufftables r15 %define hash_table level_buf + _hash8k_hash_table %define lit_len_hist level_buf + _hist_lit_len %define dist_hist level_buf + _hist_dist ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; f_end_i_mem_offset equ 0 ; local variable (8 bytes) m_out_end equ 8 m_out_start equ 16 dist_mask_offset equ 24 hash_mask_offset equ 32 stack_size equ 5*8 %xdefine METHOD hash_hist [bits 64] default rel section .text ; void isal_deflate_icf_finish ( isal_zstream *stream ) ; arg 1: rcx: addr of stream global isal_deflate_icf_finish_ %+ METHOD %+ _01 isal_deflate_icf_finish_ %+ METHOD %+ _01: endbranch PUSH_ALL rbx, rsi, rdi, rbp, r12, r13, r14, r15 sub rsp, stack_size %ifidn __OUTPUT_FORMAT__, win64 mov stream, rcx %else mov stream, rdi %endif ; state->bitbuf.set_buf(stream->next_out, stream->avail_out); mov tmp2 %+ d, dword [stream + _internal_state_dist_mask] mov tmp3 %+ d, dword [stream + _internal_state_hash_mask] mov level_buf, [stream + _level_buf] mov m_out_buf, [level_buf + _icf_buf_next] mov [rsp + m_out_start], m_out_buf mov tmp1, [level_buf + _icf_buf_avail_out] add tmp1, m_out_buf sub tmp1, 4 mov [rsp + dist_mask_offset], tmp2 mov [rsp + hash_mask_offset], tmp3 mov [rsp + m_out_end], tmp1 mov hufftables, [stream + _hufftables] mov file_start, [stream + _next_in] mov f_i %+ d, dword [stream + _total_in] sub file_start, f_i mov f_end_i %+ d, dword [stream + _avail_in] add f_end_i, f_i sub f_end_i, LAST_BYTES_COUNT mov [rsp + f_end_i_mem_offset], f_end_i ; for (f_i = f_start_i; f_i < f_end_i; f_i++) { cmp f_i, f_end_i jge .end_loop_2 mov curr_data %+ d, [file_start + f_i] cmp byte [stream + _internal_state_has_hist], IGZIP_NO_HIST jne .skip_write_first_byte cmp m_out_buf, [rsp + m_out_end] ja .end_loop_2 mov hmask1 %+ d, [rsp + hash_mask_offset] compute_hash hash, curr_data and hash %+ d, hmask1 %+ d mov [hash_table + 2 * hash], f_i %+ w mov byte [stream + _internal_state_has_hist], IGZIP_HIST jmp .encode_literal .skip_write_first_byte: .loop2: mov tmp3 %+ d, [rsp + dist_mask_offset] mov hmask1 %+ d, [rsp + hash_mask_offset] ; if (state->bitbuf.is_full()) { cmp m_out_buf, [rsp + m_out_end] ja .end_loop_2 ; hash = compute_hash(state->file_start + f_i) & hash_mask; mov curr_data %+ d, [file_start + f_i] compute_hash hash, curr_data and hash %+ d, hmask1 %+ d ; f_index = state->head[hash]; movzx f_index %+ d, word [hash_table + 2 * hash] ; state->head[hash] = (uint16_t) f_i; mov [hash_table + 2 * hash], f_i %+ w ; dist = f_i - f_index; // mod 64k mov dist %+ d, f_i %+ d sub dist %+ d, f_index %+ d and dist %+ d, 0xFFFF ; if ((dist-1) <= (D-1)) { mov tmp1 %+ d, dist %+ d sub tmp1 %+ d, 1 cmp tmp1 %+ d, tmp3 %+ d jae .encode_literal ; len = f_end_i - f_i; mov tmp4, [rsp + f_end_i_mem_offset] sub tmp4, f_i add tmp4, LAST_BYTES_COUNT ; if (len > 258) len = 258; cmp tmp4, 258 cmovg tmp4, [c258] ; len = compare(state->file_start + f_i, ; state->file_start + f_i - dist, len); lea tmp1, [file_start + f_i] mov tmp2, tmp1 sub tmp2, dist compare tmp4, tmp1, tmp2, len, tmp3 ; if (len >= SHORTEST_MATCH) { cmp len, SHORTEST_MATCH jb .encode_literal ;; encode as dist/len ; get_dist_code(dist, &code2, &code_len2); dec dist get_dist_icf_code dist, code2, tmp3 ;; clobbers dist, rcx ;; get_len_code lea code, [len + 254] mov hmask2 %+ d, [rsp + hash_mask_offset] or code2, code inc dword [lit_len_hist + HIST_ELEM_SIZE*code] ; for (k = f_i+1, f_i += len-1; k <= f_i; k++) { lea tmp3, [f_i + 1] ; tmp3 <= k add f_i, len cmp f_i, [rsp + f_end_i_mem_offset] jae .skip_hash_update ; only update hash twice ; hash = compute_hash(state->file_start + k) & hash_mask; mov tmp6 %+ d, dword [file_start + tmp3] compute_hash hash, tmp6 and hash %+ d, hmask2 %+ d ; state->head[hash] = k; mov [hash_table + 2 * hash], tmp3 %+ w add tmp3, 1 ; hash = compute_hash(state->file_start + k) & hash_mask; mov tmp6 %+ d, dword [file_start + tmp3] compute_hash hash, tmp6 and hash %+ d, hmask2 %+ d ; state->head[hash] = k; mov [hash_table + 2 * hash], tmp3 %+ w .skip_hash_update: write_dword code2, m_out_buf shr code2, DIST_OFFSET and code2, 0x1F inc dword [dist_hist + HIST_ELEM_SIZE*code2] ; continue cmp f_i, [rsp + f_end_i_mem_offset] jl .loop2 jmp .end_loop_2 .encode_literal: ; get_lit_code(state->file_start[f_i], &code2, &code_len2); movzx tmp5, byte [file_start + f_i] inc dword [lit_len_hist + HIST_ELEM_SIZE*tmp5] or tmp5, LIT write_dword tmp5, m_out_buf ; continue add f_i, 1 cmp f_i, [rsp + f_end_i_mem_offset] jl .loop2 .end_loop_2: mov f_end_i, [rsp + f_end_i_mem_offset] add f_end_i, LAST_BYTES_COUNT mov [rsp + f_end_i_mem_offset], f_end_i ; if ((f_i >= f_end_i) && ! state->bitbuf.is_full()) { cmp f_i, f_end_i jge .input_end xor tmp5, tmp5 .final_bytes: cmp m_out_buf, [rsp + m_out_end] ja .out_end movzx tmp5, byte [file_start + f_i] inc dword [lit_len_hist + HIST_ELEM_SIZE*tmp5] or tmp5, LIT write_dword tmp5, m_out_buf inc f_i cmp f_i, [rsp + f_end_i_mem_offset] jl .final_bytes .input_end: cmp word [stream + _end_of_stream], 0 jne .out_end cmp word [stream + _flush], _NO_FLUSH jne .out_end jmp .end .out_end: mov dword [stream + _internal_state_state], ZSTATE_CREATE_HDR .end: ;; Update input buffer mov f_end_i, [rsp + f_end_i_mem_offset] mov [stream + _total_in], f_i %+ d mov [stream + _internal_state_block_end], f_i %+ d add file_start, f_i mov [stream + _next_in], file_start sub f_end_i, f_i mov [stream + _avail_in], f_end_i %+ d ;; Update output buffer mov [level_buf + _icf_buf_next], m_out_buf ; len = state->bitbuf.buffer_used(); sub m_out_buf, [rsp + m_out_start] ; stream->avail_out -= len; sub [level_buf + _icf_buf_avail_out], m_out_buf add rsp, stack_size POP_ALL ret section .data align 4 c258: dq 258
#include "TerminationGenerator.hpp" #include <spdlog/spdlog.h> #include "../Players/Player.hpp" #include "TerminationHandler.hpp" namespace griddly { void TerminationGenerator::defineTerminationCondition(TerminationState state, std::string commandName, int32_t reward, int32_t opposingReward, std::vector<std::string> commandArguments) { spdlog::debug("Adding termination condition definition {0} [{1}, {2}]", commandName, commandArguments[0], commandArguments[1]); TerminationConditionDefinition tcd; tcd.commandName = commandName; tcd.commandArguments = commandArguments; tcd.state = state; tcd.reward = reward; tcd.opposingReward = opposingReward; terminationConditionDefinitions_.push_back(tcd); } std::shared_ptr<TerminationHandler> TerminationGenerator::newInstance(std::shared_ptr<Grid> grid, std::vector<std::shared_ptr<Player>> players) { auto terminationHandler = std::shared_ptr<TerminationHandler>(new TerminationHandler(grid, players)); for (auto terminationConditionDefinition : terminationConditionDefinitions_) { terminationHandler->addTerminationCondition(terminationConditionDefinition); } return terminationHandler; } } // namespace griddly
;=========================================================================== ; fill.asm ; Submodule with memory fill routines. ;=========================================================================== ; Some constants BCKG_LINE_SIZE: equ 32 ; Colors BLACK: equ 0<<3 BLUE: equ 1<<3 RED: equ 2<<3 MAGENTA: equ 3<<3 GREEN: equ 4<<3 CYAN: equ 5<<3 YELLOW: equ 6<<3 WHITE: equ 7<<3 ; Fills a memory area with a certain value. ; a = contains the fill value. ; hl = address to fill ; bc = size fill_memory: ld (hl),a ld e,l ld d,h inc de dec bc ldir ret ; Fills a background line with a color. ; IN: ; a = color ; de = points to background screen ; OUT: ; de = pointing to next line fill_bckg_line: ld bc,BCKG_LINE_SIZE ld l,e ld h,d call fill_memory ; check that destination address is still in screen background ld hl,COLOR_SCREEN+COLOR_SCREEN_SIZE-1 or a ; clear carry sbc hl,de ; compare ret p ; ld start address ld de,COLOR_SCREEN ret ; Increments the fill_colors_ptr and resets it if necessary. inc_fill_colors_ptr: ld hl,(fill_colors_ptr) inc hl ld (fill_colors_ptr),hl ; check if out of range ld bc,fill_colors_end or a ; clear carry sbc hl,bc ; compare ret m ; reset ld hl,fill_colors ld (fill_colors_ptr),hl ret ; Pointer to fill colors. fill_colors_ptr: defw 0 ; Contains the colors for the lines. Each entry represnts the color for one line. fill_colors: defb RED, YELLOW, BLUE, GREEN, MAGENTA fill_colors_end: defb 0 ; WPMEM
; Copyright Oliver Kowalke 2009. ; Distributed under the Boost Software License, Version 1.0. ; (See accompanying file LICENSE_1_0.txt or copy at ; http://www.boost.org/LICENSE_1_0.txt) ; --------------------------------------------------------------------------------- ; | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ; --------------------------------------------------------------------------------- ; | 0h | 04h | 08h | 0ch | 010h | 014h | 018h | 01ch | ; --------------------------------------------------------------------------------- ; | fc_mxcsr|fc_x87_cw| fc_strg |fc_deallo| limit | base | fc_seh | EDI | ; --------------------------------------------------------------------------------- ; --------------------------------------------------------------------------------- ; | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | ; --------------------------------------------------------------------------------- ; | 020h | 024h | 028h | 02ch | 030h | 034h | 038h | 03ch | ; --------------------------------------------------------------------------------- ; | ESI | EBX | EBP | EIP | to | data | EH NXT |SEH HNDLR| ; --------------------------------------------------------------------------------- .386 .XMM .model flat, c .code tt_jump_fcontext PROC BOOST_CONTEXT_EXPORT ; prepare stack lea esp, [esp-02ch] ; save MMX control- and status-word stmxcsr [esp] ; save x87 control-word fnstcw [esp+04h] assume fs:nothing ; load NT_TIB into ECX mov edx, fs:[018h] assume fs:error ; load fiber local storage mov eax, [edx+010h] mov [esp+08h], eax ; load current deallocation stack mov eax, [edx+0e0ch] mov [esp+0ch], eax ; load current stack limit mov eax, [edx+08h] mov [esp+010h], eax ; load current stack base mov eax, [edx+04h] mov [esp+014h], eax ; load current SEH exception list mov eax, [edx] mov [esp+018h], eax mov [esp+01ch], edi ; save EDI mov [esp+020h], esi ; save ESI mov [esp+024h], ebx ; save EBX mov [esp+028h], ebp ; save EBP ; store ESP (pointing to context-data) in EAX mov eax, esp ; firstarg of tt_jump_fcontext() == fcontext to jump to mov ecx, [esp+030h] ; restore ESP (pointing to context-data) from ECX mov esp, ecx ; restore MMX control- and status-word ldmxcsr [esp] ; restore x87 control-word fldcw [esp+04h] assume fs:nothing ; load NT_TIB into EDX mov edx, fs:[018h] assume fs:error ; restore fiber local storage mov ecx, [esp+08h] mov [edx+010h], ecx ; restore current deallocation stack mov ecx, [esp+0ch] mov [edx+0e0ch], ecx ; restore current stack limit mov ecx, [esp+010h] mov [edx+08h], ecx ; restore current stack base mov ecx, [esp+014h] mov [edx+04h], ecx ; restore current SEH exception list mov ecx, [esp+018h] mov [edx], ecx mov ecx, [esp+02ch] ; restore EIP mov edi, [esp+01ch] ; restore EDI mov esi, [esp+020h] ; restore ESI mov ebx, [esp+024h] ; restore EBX mov ebp, [esp+028h] ; restore EBP ; prepare stack lea esp, [esp+030h] ; return tt_transfer_t ; FCTX == EAX, DATA == EDX mov edx, [eax+034h] ; jump to context jmp ecx tt_jump_fcontext ENDP END
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Portability.h> #include <folly/experimental/coro/BlockingWait.h> #include <folly/experimental/coro/Collect.h> #include <folly/experimental/coro/CurrentExecutor.h> #include <folly/experimental/coro/Invoke.h> #include <folly/experimental/coro/Task.h> #include <folly/portability/GTest.h> #if FOLLY_HAS_COROUTINES class CoRescheduleOnCurrentExecutorTest : public testing::Test {}; TEST_F(CoRescheduleOnCurrentExecutorTest, example) { std::vector<int> results; folly::coro::blockingWait(folly::coro::collectAll( folly::coro::co_invoke([&]() -> folly::coro::Task<void> { for (int i = 0; i <= 10; i += 2) { if (i == 6) { co_await folly::coro::co_reschedule_on_current_executor; } results.push_back(i); } }), folly::coro::co_invoke([&]() -> folly::coro::Task<void> { for (int i = 1; i < 10; i += 2) { if (i == 7) { co_await folly::coro::co_reschedule_on_current_executor; } results.push_back(i); } }))); CHECK_EQ(11, results.size()); const int expected[11] = {0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9}; for (int i = 0; i < 11; ++i) { CHECK_EQ(expected[i], results[i]); } } #endif
db "PINCER@" ; species name db "Its oversized claw" next "is very powerful," next "but when it's not" page "in battle, the" next "claw just gets in" next "the way.@"
ShowPokedexMenu: call GBPalWhiteOut call ClearScreen call UpdateSprites ld a, [wListScrollOffset] push af xor a ld [wCurrentMenuItem], a ld [wListScrollOffset], a ld [wLastMenuItem], a inc a ld [wd11e], a ld [hJoy7], a .setUpGraphics callab LoadPokedexTilePatterns .loop callba SendPokeballPal .doPokemonListMenu ld hl, wTopMenuItemY ld a, 3 ld [hli], a ; top menu item Y xor a ld [hli], a ; top menu item X inc a ld [wMenuWatchMovingOutOfBounds], a inc hl inc hl ld a, 6 ld [hli], a ; max menu item ID ld [hl], D_LEFT | D_RIGHT | B_BUTTON | A_BUTTON call HandlePokedexListMenu jr c, .goToSideMenu ; if the player chose a pokemon from the list .exitPokedex xor a ld [wMenuWatchMovingOutOfBounds], a ld [wCurrentMenuItem], a ld [wLastMenuItem], a ld [hJoy7], a ld [wWastedByteCD3A], a ld [wOverrideSimulatedJoypadStatesMask], a pop af ld [wListScrollOffset], a call GBPalWhiteOutWithDelay3 call RunDefaultPaletteCommand jp ReloadMapData .goToSideMenu call HandlePokedexSideMenu dec b jr z, .exitPokedex ; if the player chose Quit dec b jr z, .doPokemonListMenu ; if pokemon not seen or player pressed B button dec b jr z, .loop jp .setUpGraphics ; if pokemon data or area was shown ; handles the menu on the lower right in the pokedex screen ; OUTPUT: ; b = reason for exiting menu ; 00: showed pokemon data or area ; 01: the player chose Quit ; 02: the pokemon has not been seen yet or the player pressed the B button HandlePokedexSideMenu: call PlaceUnfilledArrowMenuCursor ld a, [wCurrentMenuItem] push af ld b, a ld a, [wLastMenuItem] push af ld a, [wListScrollOffset] push af add b inc a ld [wd11e], a ld a, [wd11e] push af ld a, [wDexMaxSeenMon] push af ; this doesn't need to be preserved ld hl, wPokedexSeen call IsPokemonBitSet ld b, 2 jr z, .exitSideMenu call PokedexToIndex ld hl, wTopMenuItemY ld a, 8 ld [hli], a ; top menu item Y ld a, 15 ld [hli], a ; top menu item X xor a ld [hli], a ; current menu item ID inc hl ld a, 4 ld [hli], a ; max menu item ID ld a, A_BUTTON | B_BUTTON ld [hli], a ; menu watched keys (A button and B button) xor a ld [hli], a ; old menu item ID ld [wMenuWatchMovingOutOfBounds], a ld [hJoy7], a .handleMenuInput call HandleMenuInput bit 1, a ; was the B button pressed? ld b, 2 jr nz, .buttonBPressed ld a, [wCurrentMenuItem] and a jr z, .choseData dec a jr z, .choseCry dec a jr z, .choseArea dec a jr z, .chosePrint .choseQuit ld b, 1 .exitSideMenu pop af ld [wDexMaxSeenMon], a pop af ld [wd11e], a pop af ld [wListScrollOffset], a pop af ld [wLastMenuItem], a pop af ld [wCurrentMenuItem], a ld a, $1 ld [hJoy7], a push bc coord hl, 0, 3 ld de, 20 lb bc, " ", 13 call DrawTileLine ; cover up the menu cursor in the pokemon list pop bc ret .buttonBPressed push bc coord hl, 15, 8 ld de, 20 lb bc, " ", 9 call DrawTileLine ; cover up the menu cursor in the side menu pop bc jr .exitSideMenu .choseData call ShowPokedexDataInternal ld b, 0 jr .exitSideMenu ; play pokemon cry .choseCry ld a, [wd11e] call GetCryData call PlaySound jr .handleMenuInput .choseArea predef LoadTownMap_Nest ; display pokemon areas ld b, 0 jr .exitSideMenu .chosePrint ld a, [hTilesetType] push af xor a ld [hTilesetType], a ld a, [wd11e] ld [wcf91], a callab PrintPokedexEntry xor a ld [H_AUTOBGTRANSFERENABLED], a call ClearScreen pop af ld [hTilesetType], a ld b, $3 jr .exitSideMenu ; handles the list of pokemon on the left of the pokedex screen ; sets carry flag if player presses A, unsets carry flag if player presses B HandlePokedexListMenu: call Pokedex_DrawInterface .loop call Pokedex_PlacePokemonList call GBPalNormal call HandleMenuInput bit BIT_B_BUTTON, a ; was the B button pressed? jp nz, .buttonBPressed bit BIT_A_BUTTON, a ; was the A button pressed? jp nz, .buttonAPressed .checkIfUpPressed bit BIT_D_UP, a ; was Up pressed? jr z, .checkIfDownPressed .upPressed ; scroll up one row ld a, [wListScrollOffset] and a jp z, .loop dec a ld [wListScrollOffset], a jp .loop .checkIfDownPressed bit BIT_D_DOWN, a ; was Down pressed? jr z, .checkIfRightPressed .downPressed ; scroll down one row ld a, [wDexMaxSeenMon] cp a, 7 jp c, .loop ; can't if the list is shorter than 7 sub a, 7 ld b, a ld a, [wListScrollOffset] cp b jp z, .loop inc a ld [wListScrollOffset], a jp .loop .checkIfRightPressed bit BIT_D_RIGHT, a ; was Right pressed? jr z, .checkIfLeftPressed .rightPressed ; scroll down 7 rows ld a, [wDexMaxSeenMon] cp a, 7 jp c, .loop ; can't if the list is shorter than 7 sub a, 6 ld b, a ld a, [wListScrollOffset] add a, 7 ld [wListScrollOffset], a cp b jp c, .loop dec b ld a, b ld [wListScrollOffset], a jp .loop .checkIfLeftPressed ; scroll up 7 rows bit BIT_D_LEFT, a ; was Left pressed? jr z, .buttonAPressed .leftPressed ld a, [wListScrollOffset] sub a, 7 ld [wListScrollOffset], a jp nc, .loop xor a ld [wListScrollOffset], a jp .loop .buttonAPressed scf ret .buttonBPressed and a ret Pokedex_DrawInterface: xor a ld [H_AUTOBGTRANSFERENABLED], a ; draw the horizontal line separating the seen and owned amounts from the menu coord hl, 15, 6 ld a, $7a ; horizontal line tile ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hli], a coord hl, 14, 0 ld [hl], $71 ; vertical line tile coord hl, 14, 1 call DrawPokedexVerticalLine coord hl, 14, 9 call DrawPokedexVerticalLine ld hl, wPokedexSeen ld b, wPokedexSeenEnd - wPokedexSeen call CountSetBits ld de, wNumSetBits coord hl, 16, 2 lb bc, 1, 3 call PrintNumber ; print number of seen pokemon ld hl, wPokedexOwned ld b, wPokedexOwnedEnd - wPokedexOwned call CountSetBits ld de, wNumSetBits coord hl, 16, 5 lb bc, 1, 3 call PrintNumber ; print number of owned pokemon coord hl, 16, 1 ld de, PokedexSeenText call PlaceString coord hl, 16, 4 ld de, PokedexOwnText call PlaceString coord hl, 1, 1 ld de, PokedexContentsText call PlaceString coord hl, 16, 8 ld de, PokedexMenuItemsText call PlaceString ; find the highest pokedex number among the pokemon the player has seen ld hl, wPokedexSeenEnd - 1 ld b, 0;(wPokedexSeenEnd - wPokedexSeen) * 8 + 1 gives 8 bit error, so, just enjoy having all of them. >_> .maxSeenPokemonLoop ld a, [hld] ld c, 8 .maxSeenPokemonInnerLoop dec b sla a jr c, .storeMaxSeenPokemon dec c jr nz, .maxSeenPokemonInnerLoop jr .maxSeenPokemonLoop .storeMaxSeenPokemon ld a, b ld [wDexMaxSeenMon], a ret DrawPokedexVerticalLine: ld c, 9 ; height of line ld de, SCREEN_WIDTH ; width of screen ld a, $71 ; vertical line tile .loop ld [hl], a add hl, de xor a, 1 ; toggle between vertical line tile and box tile dec c jr nz, .loop ret PokedexSeenText: db "SEEN@" PokedexOwnText: db "OWN@" PokedexContentsText: db "CONTENTS@" PokedexMenuItemsText: db "DATA" next "CRY" next "AREA" next "PRNT" next "QUIT@" Pokedex_PlacePokemonList: xor a ld [H_AUTOBGTRANSFERENABLED], a coord hl, 4, 2 lb bc, 14, 10 call ClearScreenArea coord hl, 1, 3 ld a, [wListScrollOffset] ld [wd11e], a ld d, 7 ld a, [wDexMaxSeenMon] cp a, 7 jr nc, .printPokemonLoop ld d, a dec a ld [wMaxMenuItem], a ; loop to print pokemon pokedex numbers and names ; if the player has owned the pokemon, it puts a pokeball beside the name .printPokemonLoop ld a, [wd11e] inc a ld [wd11e], a push af push de push hl ld de, -SCREEN_WIDTH add hl, de ld de, wd11e lb bc, LEADING_ZEROES | 1, 3 call PrintNumber ; print the pokedex number ld de, SCREEN_WIDTH add hl, de dec hl push hl ld hl, wPokedexOwned call IsPokemonBitSet pop hl ld a, " " jr z, .writeTile ld a, $72 ; pokeball tile .writeTile ld [hl], a ; put a pokeball next to pokemon that the player has owned push hl ld hl, wPokedexSeen call IsPokemonBitSet jr nz, .getPokemonName ; if the player has seen the pokemon ld de, .dashedLine ; print a dashed line in place of the name if the player hasn't seen the pokemon jr .skipGettingName .dashedLine ; for unseen pokemon in the list db "----------@" .getPokemonName call PokedexToIndex call GetMonName .skipGettingName pop hl inc hl call PlaceString pop hl ld bc, 2 * 20 add hl, bc pop de pop af ld [wd11e], a dec d jr nz, .printPokemonLoop ld a, 01 ld [H_AUTOBGTRANSFERENABLED], a call Delay3 ret ; tests if a pokemon's bit is set in the seen or owned pokemon bit fields ; INPUT: ; [wd11e] = pokedex number ; hl = address of bit field IsPokemonBitSet: ld a, [wd11e] dec a ld c, a ld b, FLAG_TEST predef FlagActionPredef ld a, c and a ret ; function to display pokedex data from outside the pokedex ShowPokedexData: call GBPalWhiteOutWithDelay3 call ClearScreen call UpdateSprites callab LoadPokedexTilePatterns ; load pokedex tiles ; function to display pokedex data from inside the pokedex ShowPokedexDataInternal: ld hl, wd72c set 1, [hl] ld a, $33 ; 3/7 volume ld [rNR50], a ld a, [hTilesetType] push af xor a ld [hTilesetType], a call GBPalWhiteOut ; zero all palettes ld a, [wd11e] ; pokemon ID ld [wcf91], a push af ld b, SET_PAL_POKEDEX call RunPaletteCommand pop af ld [wd11e], a call DrawDexEntryOnScreen call c, Pokedex_PrintFlavorTextAtRow11 .waitForButtonPress call JoypadLowSensitivity ld a, [hJoy5] and a, A_BUTTON | B_BUTTON jr z, .waitForButtonPress pop af ld [hTilesetType], a call GBPalWhiteOut call ClearScreen call RunDefaultPaletteCommand call LoadTextBoxTilePatterns call GBPalNormal ld hl, wd72c res 1, [hl] ld a, $77 ; max volume ld [rNR50], a ret HeightWeightText: db "HT ?", $60, "??", $61 next "WT ???lb@" ; XXX does anything point to this? PokeText: db "#@" ; horizontal line that divides the pokedex text description from the rest of the data PokedexDataDividerLine: db $68, $69, $6B, $69, $6B db $69, $6B, $69, $6B, $6B db $6B, $6B, $69, $6B, $69 db $6B, $69, $6B, $69, $6A db "@" DrawDexEntryOnScreen: call ClearScreen coord hl, 0, 0 ld de, 1 lb bc, $64, SCREEN_WIDTH call DrawTileLine ; draw top border coord hl, 0, 17 ld b, $6f call DrawTileLine ; draw bottom border coord hl, 0, 1 ld de, 20 lb bc, $66, $10 call DrawTileLine ; draw left border coord hl, 19, 1 ld b, $67 call DrawTileLine ; draw right border ld a, $63 ; upper left corner tile Coorda 0, 0 ld a, $65 ; upper right corner tile Coorda 19, 0 ld a, $6c ; lower left corner tile Coorda 0, 17 ld a, $6e ; lower right corner tile Coorda 19, 17 coord hl, 0, 9 ld de, PokedexDataDividerLine call PlaceString ; draw horizontal divider line coord hl, 9, 6 ld de, HeightWeightText call PlaceString call GetMonName coord hl, 9, 2 call PlaceString ld hl, PokedexEntryPointers ld a, [wd11e] dec a ld e, a ld d, 0 add hl, de add hl, de ld a, [hli] ld e, a ld d, [hl] ; de = address of pokedex entry coord hl, 9, 4 call PlaceString ; print species name ld h, b ld l, c push de ld a, [wd11e] push af call IndexToPokedex coord hl, 2, 8 ld a, "№" ld [hli], a ld a, $f2 ld [hli], a ld de, wd11e lb bc, LEADING_ZEROES | 1, 3 call PrintNumber ; print pokedex number ld hl, wPokedexOwned call IsPokemonBitSet pop af ld [wd11e], a ld a, [wcf91] ld [wd0b5], a pop de push af push bc push de push hl call Delay3 call GBPalNormal call GetMonHeader ; load pokemon picture location coord hl, 1, 1 call LoadFlippedFrontSpriteByMonIndex ; draw pokemon picture ld a, [wcf91] call PlayCry ; play pokemon cry pop hl pop de pop bc pop af ld a, c and a ret z ; if the pokemon has not been owned, don't print the height, weight, or description inc de ; de = address of feet (height) ld a, [de] ; reads feet, but a is overwritten without being used coord hl, 12, 6 lb bc, 1, 2 call PrintNumber ; print feet (height) ld a, $60 ; feet symbol tile (one tick) ld [hl], a inc de inc de ; de = address of inches (height) coord hl, 15, 6 lb bc, LEADING_ZEROES | 1, 2 call PrintNumber ; print inches (height) ld a, $61 ; inches symbol tile (two ticks) ld [hl], a ; now print the weight (note that weight is stored in tenths of pounds internally) inc de inc de inc de ; de = address of upper byte of weight push de ; put weight in big-endian order at hDexWeight ld hl, hDexWeight ld a, [hl] ; save existing value of [hDexWeight] push af ld a, [de] ; a = upper byte of weight ld [hli], a ; store upper byte of weight in [hDexWeight] ld a, [hl] ; save existing value of [hDexWeight + 1] push af dec de ld a, [de] ; a = lower byte of weight ld [hl], a ; store lower byte of weight in [hDexWeight + 1] ld de, hDexWeight coord hl, 11, 8 lb bc, 2, 5 ; 2 bytes, 5 digits call PrintNumber ; print weight coord hl, 14, 8 ld a, [hDexWeight + 1] sub a, 10 ld a, [hDexWeight] sbc a, 0 jr nc, .next ld [hl], "0" ; if the weight is less than 10, put a 0 before the decimal point .next inc hl ld a, [hli] ld [hld], a ; make space for the decimal point by moving the last digit forward one tile ld [hl], $f2 ; decimal point tile pop af ld [hDexWeight + 1], a ; restore original value of [hDexWeight + 1] pop af ld [hDexWeight], a ; restore original value of [hDexWeight] pop hl inc hl ; hl = address of pokedex description text scf ret Pokedex_PrintFlavorTextAtRow11: coord bc, 1, 11 Pokedex_PrintFlavorTextAtBC: ld a, 2 ld [$fff9], a call TextCommandProcessor ; print pokedex description text xor a ld [$fff9], a ret Pokedex_PrepareDexEntryForPrinting: coord hl, 0, 0 ld de, SCREEN_WIDTH lb bc, $66, $d call DrawTileLine coord hl, 19, 0 ld b, $67 call DrawTileLine coord hl, 0, 13 ld de, $1 lb bc, $6f, SCREEN_WIDTH call DrawTileLine ld a, $6c Coorda 0, 13 ld a, $6e Coorda 19, 13 ld a, [wPrinterPokedexEntryTextPointer] ld l, a ld a, [wPrinterPokedexEntryTextPointer + 1] ld h, a coord bc, 1, 1 ld a, [hFlags_0xFFFA] set 3, a ld [hFlags_0xFFFA], a call Pokedex_PrintFlavorTextAtBC ld a, [hFlags_0xFFFA] res 3, a ld [hFlags_0xFFFA], a ret ; draws a line of tiles ; INPUT: ; b = tile ID ; c = number of tile ID's to write ; de = amount to destination address after each tile (1 for horizontal, 20 for vertical) ; hl = destination address DrawTileLine: push bc push de .loop ld [hl], b add hl, de dec c jr nz, .loop pop de pop bc ret INCLUDE "data/pokedex_entries.asm" PokedexToIndex: ; converts the Pokédex number at wd11e to an index push bc push hl ld a, [wd11e] ld b, a ld c, 0 ld hl, PokedexOrder .loop ; go through the list until we find an entry with a matching dex number inc c ld a, [hli] cp b jr nz, .loop ld a, c ld [wd11e], a pop hl pop bc ret IndexToPokedex: ; converts the indexédex number at wd11e to a Pokédex number push bc push hl ld a, [wd11e] dec a ld hl, PokedexOrder ld b, 0 ld c, a add hl, bc ld a, [hl] ld [wd11e], a pop hl pop bc ret INCLUDE "data/pokedex_order.asm"
;Testname=unoptimized; Arguments=-O0 -fobj -oelif.obj; Files=stdout stderr elif.obj ;Testname=optimized; Arguments=-Ox -fobj -oelif.obj; Files=stdout stderr elif.obj %macro DosPrintMsg 1+ %ifnid %1 section .data %%str_to_print:db %1 section .text mov dx,%%str_to_print mov ah,9 int 0x21 %else mov dx,(%1) mov ah,9 int 0x21 %endif %endmacro %macro DosExit 1 %if (%1) == 0 ;use short-form return 0 exit int 0x20 %elif ((%1) < 256) && ((%1) > 0) mov ax,0x4C00 | (%1) int 0x21 %else %error Invalid return value %endif %endmacro org 0x100 DosPrintMsg predefined_str DosPrintMsg "Using string with macro-defined label",10,0 DosExit 0 DosExit 1 DosExit 256 section .data predefined_str:db "Using string with predefined label",10,0
;; ;; This is auto-generated file by bin/mmlc.pl. ;; (command line option(s): -f 1000000 mml/choral.mml) ;; MUSICDATA_CH0: .db 0xfa, 0x0e, 0xfd, 0x05, 0x16, 0x2b, 0x05, 0x16 .db 0x2d, 0x05, 0x16, 0x2f, 0x05, 0x16, 0x32, 0x05 .db 0x16, 0x30, 0x05, 0x16, 0x30, 0x05, 0x17, 0x34 .db 0x05, 0x16, 0x32, 0x05, 0x16, 0x32, 0x05, 0x16 .db 0x37, 0x05, 0x16, 0x36, 0x05, 0x16, 0x37, 0x05 .db 0x16, 0x32, 0x05, 0x16, 0x2f, 0x05, 0x16, 0x2b .db 0x05, 0x16, 0x2d, 0x05, 0x16, 0x2f, 0x05, 0x16 .db 0x30, 0x05, 0x17, 0x32, 0x05, 0x16, 0x34, 0x05 .db 0x16, 0x32, 0x05, 0x16, 0x30, 0x05, 0x16, 0x2f .db 0x05, 0x16, 0x2d, 0x05, 0x16, 0x2f, 0x05, 0x16 .db 0x2b, 0x05, 0x16, 0x2a, 0x05, 0x16, 0x2b, 0x05 .db 0x16, 0x2d, 0x05, 0x16, 0x26, 0x05, 0x17, 0x2a .db 0x05, 0x16, 0x2d, 0x05, 0x16, 0x30, 0x05, 0x16 .db 0x2f, 0x05, 0x16, 0x2d, 0x05, 0x16, 0x2f, 0x05 .db 0x16, 0x2b, 0x05, 0x16, 0x2d, 0x05, 0x16, 0x2f .db 0x05, 0x16, 0x32, 0x05, 0x16, 0x30, 0x05, 0x16 .db 0x30, 0x05, 0x17, 0x34, 0x05, 0x16, 0x32, 0x05 .db 0x16, 0x32, 0x05, 0x16, 0x37, 0x05, 0x16, 0x36 .db 0x05, 0x16, 0x37, 0x05, 0x16, 0x32, 0x05, 0x16 .db 0x2f, 0x05, 0x16, 0x2b, 0x05, 0x16, 0x2d, 0x05 .db 0x16, 0x2f, 0x05, 0x16, 0x28, 0x05, 0x17, 0x32 .db 0x05, 0x16, 0x30, 0x05, 0x16, 0x2f, 0x05, 0x16 .db 0x2d, 0x05, 0x16, 0x2b, 0x05, 0x16, 0x26, 0x05 .db 0x16, 0x2b, 0x05, 0x16, 0x2a, 0x05, 0x16, 0x2b .db 0x05, 0x16, 0x2f, 0x05, 0x16, 0x32, 0x05, 0x16 .db 0x37, 0x05, 0x17, 0x32, 0x05, 0x16, 0x2f, 0x05 .db 0x16, 0x2b, 0x05, 0x16, 0x2f, 0x05, 0x16, 0x32 .db 0x05, 0x16, 0x37, 0x1e, 0x84, 0xff MUSICDATA_CH1: .db 0xfa, 0x0d, 0xfd, 0x0f, 0x42, 0x26, 0x0f, 0x43 .db 0x28, 0x0f, 0x42, 0x2b, 0x0f, 0x42, 0x28, 0x0f .db 0x42, 0x23, 0x0f, 0x43, 0x21, 0x0f, 0x42, 0x26 .db 0x0f, 0x42, 0x24, 0x0f, 0x42, 0x24, 0x0f, 0x43 .db 0x21, 0x0f, 0x42, 0x2a, 0x0f, 0x42, 0x2b, 0x0f .db 0x42, 0x1f, 0x0f, 0x43, 0x28, 0x0f, 0x42, 0x2b .db 0x0f, 0x42, 0x28, 0x0f, 0x42, 0x23, 0x0f, 0x43 .db 0x24, 0x0f, 0x42, 0x28, 0x0f, 0x42, 0x26, 0x0f .db 0x42, 0x26, 0x0f, 0x43, 0xfd, 0x07, 0xa1, 0xfd .db 0x03, 0xd0, 0x26, 0x03, 0xd1, 0x23, 0x07, 0xa1 .db 0xfe, 0x03, 0xd0, 0x2b, 0x03, 0xd1, 0x26, 0x1e .db 0x85, 0xff MUSICDATA_CH2: .db 0xfa, 0x0d, 0x13, 0x0f, 0x42, 0x1f, 0x0f, 0x43 .db 0x1c, 0x0f, 0x42, 0x17, 0x0f, 0x42, 0x1c, 0x0f .db 0x42, 0x10, 0x0f, 0x43, 0x15, 0x0f, 0x42, 0x17 .db 0x0f, 0x42, 0x18, 0x0f, 0x42, 0x1a, 0x0f, 0x43 .db 0x1e, 0x0f, 0x42, 0x1a, 0x0f, 0x42, 0x1f, 0x0f .db 0x42, 0x1c, 0x0f, 0x43, 0x18, 0x0f, 0x42, 0x17 .db 0x0f, 0x42, 0x1c, 0x0f, 0x42, 0x1a, 0x0f, 0x43 .db 0x18, 0x0f, 0x42, 0x19, 0x0f, 0x42, 0x1a, 0x0f .db 0x42, 0x13, 0x0f, 0x43, 0xfd, 0x07, 0xa1, 0xfd .db 0x03, 0xd0, 0x1f, 0x03, 0xd1, 0x1a, 0x07, 0xa1 .db 0xfe, 0x03, 0xd0, 0x17, 0x03, 0xd1, 0x13, 0x1e .db 0x85, 0xff
// // FFIPrimitiveTypes.cpp // NativeScript // // Created by Jason Zhekov on 16.10.14. // Copyright (c) 2014 г. Telerik. All rights reserved. // #include "FFIPrimitiveTypes.h" #include "FFISimpleType.h" #include "Interop.h" #include "PointerInstance.h" #include "ReferenceInstance.h" #include "ReleasePool.h" #include "TypeFactory.h" #include <JavaScriptCore/inspector/JSGlobalObjectInspectorController.h> namespace NativeScript { using namespace JSC; #pragma mark noopType static JSValue noopType_read(ExecState* execState, const void* buffer, JSCell* self) { JSC::VM& vm = execState->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue exception = createError(execState, "Can not read from noop type."_s, defaultSourceAppender); return scope.throwException(execState, exception); } static void noopType_write(ExecState* execState, const JSValue& value, void* buffer, JSCell* self) { JSC::VM& vm = execState->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue exception = createError(execState, "Can not write to noop type."_s, defaultSourceAppender); scope.throwException(execState, exception); } static bool noopType_canConvert(ExecState* execState, const JSValue& value, JSCell* self) { return false; } const FFITypeMethodTable noopTypeMethodTable = { .read = &noopType_read, .write = &noopType_write, .canConvert = &noopType_canConvert, .ffiType = &ffi_type_pointer }; #pragma mark voidType static JSValue voidType_read(ExecState* execState, const void* buffer, JSCell* self) { return jsUndefined(); } static void voidType_write(ExecState* execState, const JSValue& value, void* buffer, JSCell* self) { } static bool voidType_canConvert(ExecState* execState, const JSValue& value, JSCell* self) { return value.isUndefinedOrNull(); } static const char* voidType_encode(JSC::VM&, JSC::JSCell* self) { return "v"; } const FFITypeMethodTable voidTypeMethodTable = { .read = &voidType_read, .write = &voidType_write, .canConvert = &voidType_canConvert, .ffiType = &ffi_type_void, .encode = &voidType_encode }; #pragma mark boolType static JSValue boolType_read(ExecState* execState, const void* buffer, JSCell* self) { return jsBoolean(*static_cast<const char*>(buffer) != 0); } static void boolType_write(ExecState* execState, const JSValue& value, void* buffer, JSCell* self) { *static_cast<bool*>(buffer) = value.toBoolean(execState); } static bool boolType_canConvert(ExecState* execState, const JSValue& value, JSCell* self) { return true; } static const char* boolType_encode(JSC::VM&, JSC::JSCell* self) { return "B"; } const FFITypeMethodTable boolTypeMethodTable = { .read = &boolType_read, .write = &boolType_write, .canConvert = &boolType_canConvert, .ffiType = &ffi_type_sint8, .encode = &boolType_encode }; #pragma mark unicharType static JSValue unicharType_read(ExecState* execState, const void* buffer, JSCell* self) { const UChar character = *static_cast<const UChar*>(buffer); return jsSingleCharacterString(execState, character); } static void unicharType_write(ExecState* execState, const JSValue& value, void* buffer, JSCell* self) { JSString* str = value.toString(execState); if (str->length() != 1) { JSC::VM& vm = execState->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue exception = createError(execState, "Only one character strings can be converted to unichar."_s, defaultSourceAppender); scope.throwException(execState, exception); return; } UChar character = str->value(execState).characterAt(0); *static_cast<UChar*>(buffer) = character; } static bool unicharType_canConvert(ExecState* execState, const JSValue& value, JSCell* self) { return value.isCell() && value.toString(execState)->length() == 1; } static const char* unicharType_encode(JSC::VM&, JSC::JSCell* self) { return "S"; } const FFITypeMethodTable unicharTypeMethodTable = { .read = &unicharType_read, .write = &unicharType_write, .canConvert = &unicharType_canConvert, .ffiType = &ffi_type_ushort, .encode = &unicharType_encode }; #pragma mark cStringType static JSValue cStringType_read(ExecState* execState, const void* buffer, JSCell* self) { const char* string = *static_cast<char* const*>(buffer); if (!string) { return jsNull(); } GlobalObject* globalObject = jsCast<GlobalObject*>(execState->lexicalGlobalObject()); JSCell* type = globalObject->typeFactory()->uint8Type(); PointerInstance* pointer = jsCast<PointerInstance*>(globalObject->interop()->pointerInstanceForPointer(execState, const_cast<char*>(string))); return ReferenceInstance::create(execState->vm(), globalObject, globalObject->interop()->referenceInstanceStructure(), type, pointer).get(); } static void cStringType_write(ExecState* execState, const JSValue& value, void* buffer, JSCell* self) { if (value.isUndefinedOrNull()) { *static_cast<char**>(buffer) = nullptr; return; } if (value.isString()) { WTF::CString result = value.toString(execState)->value(execState).utf8(); *static_cast<const char**>(buffer) = result.data(); releaseSoon(execState, std::move(result)); return; } bool hasHandle; JSC::VM& vm = execState->vm(); void* handle = tryHandleofValue(vm, value, &hasHandle); if (hasHandle) { *static_cast<char**>(buffer) = static_cast<char*>(handle); return; } auto scope = DECLARE_THROW_SCOPE(vm); JSValue exception = createError(execState, value, "is not a string."_s, defaultSourceAppender); scope.throwException(execState, exception); return; } static bool cStringType_canConvert(ExecState* execState, const JSValue& value, JSCell* self) { return true; } static const char* cStringType_encode(JSC::VM&, JSC::JSCell* self) { return "*"; } const FFITypeMethodTable utf8CStringTypeMethodTable = { .read = &cStringType_read, .write = &cStringType_write, .canConvert = &cStringType_canConvert, .ffiType = &ffi_type_pointer, .encode = &cStringType_encode }; } // namespace NativeScript
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r8 push %r9 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x515c, %rsi nop nop nop sub $20999, %r8 movups (%rsi), %xmm4 vpextrq $0, %xmm4, %r9 nop nop nop nop nop inc %rdi lea addresses_WC_ht+0x35c, %rcx dec %rdx mov $0x6162636465666768, %rax movq %rax, %xmm7 vmovups %ymm7, (%rcx) nop nop nop nop cmp %rdi, %rdi lea addresses_WT_ht+0x50dc, %rsi nop inc %rcx movb (%rsi), %dl nop nop xor %rdx, %rdx lea addresses_WC_ht+0x1b8ee, %rsi lea addresses_D_ht+0x1665c, %rdi nop nop nop nop cmp $52276, %r9 mov $32, %rcx rep movsq nop nop nop nop nop and $737, %rdx lea addresses_WT_ht+0x15c, %rsi lea addresses_D_ht+0x485c, %rdi dec %r13 mov $24, %rcx rep movsq cmp $53431, %rsi lea addresses_UC_ht+0x215c, %rsi lea addresses_A_ht+0x1a85c, %rdi clflush (%rdi) nop nop nop nop nop sub $23453, %r13 mov $84, %rcx rep movsb nop nop xor $60793, %rdi lea addresses_UC_ht+0x14f6, %r13 nop add %r9, %r9 vmovups (%r13), %ymm1 vextracti128 $0, %ymm1, %xmm1 vpextrq $0, %xmm1, %rdi nop nop xor $61679, %r8 lea addresses_WC_ht+0xb75c, %rcx nop nop add $13430, %rdx mov $0x6162636465666768, %rax movq %rax, %xmm2 and $0xffffffffffffffc0, %rcx movntdq %xmm2, (%rcx) and $57575, %r9 lea addresses_A_ht+0x165bc, %rsi lea addresses_normal_ht+0x255c, %rdi nop nop nop nop cmp $31550, %rdx mov $89, %rcx rep movsb nop and $61695, %rcx lea addresses_A_ht+0x1dd14, %rsi lea addresses_D_ht+0x1d184, %rdi nop cmp $24240, %rax mov $12, %rcx rep movsq nop nop nop nop nop and %rdx, %rdx lea addresses_UC_ht+0xf26c, %rdx nop nop nop nop nop xor $19508, %r9 mov $0x6162636465666768, %rax movq %rax, %xmm7 vmovups %ymm7, (%rdx) nop nop cmp $63827, %r13 lea addresses_A_ht+0xb9c, %rdx nop nop add %r8, %r8 movups (%rdx), %xmm1 vpextrq $0, %xmm1, %r9 add %rax, %rax pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r9 pop %r8 pop %r13 ret .global s_faulty_load s_faulty_load: push %r12 push %rbx push %rdi push %rdx // Faulty Load mov $0x15c, %rdi nop nop nop nop nop sub $21690, %rdx movups (%rdi), %xmm5 vpextrq $1, %xmm5, %r12 lea oracles, %rdi and $0xff, %r12 shlq $12, %r12 mov (%rdi,%r12,1), %r12 pop %rdx pop %rdi pop %rbx pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_P', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_P', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 11}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 7}} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 6}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': True}} {'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': True, 'congruent': 1}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16, 'NT': True, 'same': False, 'congruent': 9}} {'src': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}} {'src': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 3}} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'} {'e3': 3, 'fa': 2, 'ff': 9} ff ff ff ff ff ff ff e3 e3 e3 ff ff fa fa */
copyright zengfr site:http://github.com/zengfr/romhack 00042A move.l D1, (A0)+ 00042C dbra D0, $42a 001588 movea.l ($38,A6), A0 [123p+ 36] 00158C ext.w D0 [123p+ 38, 123p+ 3A] 0015CA movea.l ($38,A6), A0 [123p+ 36] 0015CE ext.w D0 [123p+ 38, 123p+ 3A] 004D94 move.l D1, (A1)+ 004D96 dbra D0, $4d94 005CE6 move.l ($34,PC,D0.w), ($38,A6) [123p+ 20] 005CEC move.w ($20,A6), D0 [123p+ 38, 123p+ 3A] 005FE0 move.l (A0,D1.w), ($38,A6) 005FE6 move.b #$1, ($25,A6) [123p+ 38, 123p+ 3A] 01A120 move.l ($42,PC,D0.w), ($38,A6) [123p+ 20] 01A126 move.b ($2d,A6), D1 [123p+ 38, 123p+ 3A] 01A198 move.l (-$36,PC,D0.w), ($38,A6) [123p+ 20] 01A19E move.b #$1, ($25,A6) [123p+ 38, 123p+ 3A] 01A4A6 move.l (A0,D0.w), ($38,A6) 01A4AC move.b #$1, ($25,A6) [123p+ 38, 123p+ 3A] 0AAACA move.l (A0), D2 0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAACE move.w D0, ($2,A0) 0AAAD2 cmp.l (A0), D0 0AAAD4 bne $aaafc 0AAAD8 move.l D2, (A0)+ 0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAE6 move.l (A0), D2 0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAF4 move.l D2, (A0)+ 0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] copyright zengfr site:http://github.com/zengfr/romhack
; A187577: Complement of A187576. ; 3,6,9,10,13,16,19,22,25,26,29,32,35,36,39,42,45,48,51,52,55,58,61,64,67,68,71,74,77,78,81,84,87,90,93,94,97,100,103,104,107,110,113,116,119,120,123,126,129,132,135,136,139,142,145,146,149,152,155,158,161,162,165,168,171,174,177,178,181,184,187,188,191,194,197,200,203,204,207,210,213,214,217,220 mov $5,$0 mov $7,$0 add $7,1 lpb $7,1 clr $0,5 mov $0,$5 sub $7,1 sub $0,$7 add $2,$0 cal $0,163801 ; a(n)=n-a(a(n-2)) with a(0)=0,a(1)=1 add $0,$2 gcd $0,2 mov $1,$0 sub $1,1 mul $1,2 add $1,1 add $6,$1 lpe mov $1,$6
;;; ;; Recursive backtracking knights tour ;; ; aug 28 - 93 first attempt ; aug 28 - 79 still just goofing ; aug 28 - 77 oh how I suck at asm IO ; aug 28 - 72 carry for backtrack-flag ; aug 28 - 70 cx for depth counter ; aug 28 - 69 redundant ret removed ; aug 28 - 68 updated movetable for smaller 0check ; aug 30 - 65 pusha/popa, cant believe i missed that ; aug 30 - 64 many changes, just one byte ; ;; build with ;; nasmw -fbin -o entry.com entry.asm bits 16 org 100h mov di, bp ; 2 push di ; 1 rep stosb ; 2 pop di ; 1 mov cl, 64 ; 2 seek jcxz done ; 2 inc ax ; 1 xchg byte [di+bx], al ; 2 mov ah, bl ; 2 and ax, 0x88ff ; 3 jnz fail ; 2 mov si, move ; 3 next lodsb ; 1 dec ax ; 1 jz fail ; 2 pusha ; 1 add bl, al ; 2 dec cx ; 1 call seek ; 3 popa ; 1 jnc next ; 2 mov al, bl ; 2 aam 16 ; 2 mov dx, ax ; 2 mov ah, 2 ; 2 int 21h ; 2 mov dl, dh ; 2 int 21h ; 2 done stc ; 1 fail xchg byte [di+bx], al ; 2 ret ; 1 move db 0xe0, 0xe2, 0xef, 0xf3, 0x0f, 0x13, 0x20, 0x22, 0x01 ; 9
%define BE(a) ( ((((a)>>24)&0xFF) << 0) + ((((a)>>16)&0xFF) << 8) + ((((a)>>8)&0xFF) << 16) + ((((a)>>0)&0xFF) << 24)) ftyp_start: dd BE(ftyp_end - ftyp_start) dd "ftyp" db 0x61, 0x76, 0x69, 0x66 ; brand(32) ('avif') db 0x00, 0x00, 0x00, 0x00 ; version(32) db 0x6D, 0x69, 0x66, 0x31 ; compatible_brand(32) ('mif1') db 0x61, 0x76, 0x69, 0x66 ; compatible_brand(32) ('avif') db 0x6D, 0x69, 0x61, 0x66 ; compatible_brand(32) ('miaf') db 0x4D, 0x41, 0x31, 0x42 ; compatible_brand(32) ('MA1B') ftyp_end: meta_start: dd BE(meta_end - meta_start) dd "meta" db 0x00 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) hdlr_start: dd BE(hdlr_end - hdlr_start) dd "hdlr" db 0x00 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x00, 0x00, 0x00, 0x00 ; pre_defined(32) db 0x70, 0x69, 0x63, 0x74 ; handler_type(32) ('pict') db 0x00, 0x00, 0x00, 0x00 ; reserved1(32) db 0x00, 0x00, 0x00, 0x00 ; reserved2(32) db 0x00, 0x00, 0x00, 0x00 ; reserved3(32) db 0x00 ; name(8) hdlr_end: pitm_start: dd BE(pitm_end - pitm_start) dd "pitm" db 0x00 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x00, 0x01 ; item_ID(16) pitm_end: iinf_start: dd BE(iinf_end - iinf_start) dd "iinf" db 0x00 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x00, 0x02 ; entry_count(16) infe_start: dd BE(infe_end - infe_start) dd "infe" db 0x02 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x00, 0x01 ; item_ID(16) db 0x00, 0x00 ; item_protection_index(16) db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01') db 0x00 ; item_name(8) infe_end: infe2_start: dd BE(infe2_end - infe2_start) dd "infe" db 0x02 ; version(8) db 0x00, 0x00, 0x01 ; flags(24) db 0x00, 0x02 ; item_ID(16) db 0x00, 0x00 ; item_protection_index(16) db 0x45, 0x78, 0x69, 0x66 ; item_type(32) ('Exif') db 0x00 ; item_name(8) infe2_end: iinf_end: iloc_start: dd BE(iloc_end - iloc_start) dd "iloc" db 0x01 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x44 ; offset_size(4) ('D') length_size(4) ('D') db 0x00 ; base_offset_size(4) reserved1(4) db 0x00, 0x02 ; item_count(16) db 0x00, 0x01 ; item_ID(16) db 0x00, 0x00 ; "reserved2(12)" "construction_method(4)" db 0x00, 0x00 ; data_reference_index(16) ; base_offset(0) db 0x00, 0x01 ; extent_count(16) dd BE(mdat_start - ftyp_start + 8) ; extent_offset(32) db 0x00, 0x00, 0x00, 0x01 ; extent_length(32) db 0x00, 0x02 ; item_ID(16) db 0x00, 0x00 ; "reserved2(12)" "construction_method(4)" db 0x00, 0x00 ; data_reference_index(16) ; base_offset(0) db 0x00, 0x01 ; extent_count(16) dd BE(mdat_start - ftyp_start + 8) ; extent_offset(32) db 0x00, 0x00, 0x00, 0x01 ; extent_length(32) iloc_end: iprp_start: dd BE(iprp_end - iprp_start) dd "iprp" ipco_start: dd BE(ipco_end - ipco_start) dd "ipco" ispe_start: dd BE(ispe_end - ispe_start) dd "ispe" db 0x00 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x00, 0x00, 0x07, 0x80 ; image_width(32) db 0x00, 0x00, 0x04, 0x38 ; image_height(32) ispe_end: colr_start: dd BE(colr_end - colr_start) dd "colr" db 0x6E ; (8) ('n') db 0x63 ; (8) ('c') db 0x6C ; (8) ('l') db 0x78 ; (8) ('x') db 0x00 ; (8) db 0x02 ; (8) db 0x00 ; (8) db 0x02 ; (8) db 0x00 ; (8) db 0x02 ; (8) db 0x80 ; (8) colr_end: av1C_start: dd BE(av1C_end - av1C_start) dd "av1C" db 0x81 ; marker(1) version(7) db 0x09 ; seq_profile(3) seq_level_idx_0(5) db 0x0C ; seq_tier_0(1) high_bitdepth(1) twelve_bit(1) monochrome(1) chroma_subsampling_x(1) chroma_subsampling_y(1) chroma_sample_position(2) db 0x00 ; reserved(3) initial_presentation_delay_present(1) reserved(4) ; configOBUs(0) ; obu(0) db 0x0A ; forbidden(1) obu_type(4) obu_extension_flag(1) obu_has_size_field(1) obu_reserved_1bit(1) db 0x0B ; leb128_byte(8) ; seqhdr(0) db 0x00, 0x00, 0x00 ; seq_profile(3) still_picture(1) reduced_still_picture_header(1) timing_info_present_flag(1) initial_display_delay_present_flag(1) operating_points_cnt_minus_1(5) operating_point_idc[i])(12) db 0x4A, 0xAB, 0xBF, 0xC3, 0x77 ; seq_level_idx[i](5) seq_tier[i](1) frame_width_bits_minus_1(4) frame_height_bits_minus_1(4) max_frame_width_minus_1(11) max_frame_height_minus_1(11) frame_id_numbers_present_flag(1) use_128x128_superblock(1) enable_filter_intra(1) enable_intra_edge_filter(1) db 0xFF ; enable_interintra_compound(1) enable_masked_compound(1) enable_warped_motion(1) enable_dual_filter(1) enable_order_hint(1) enable_jnt_comp(1) enable_ref_frame_mvs(1) seq_choose_screen_content_tools(1) db 0xE6 ; seq_choose_integer_mv(1) order_hint_bits_minus_1(3) enable_superres(1) enable_cdef(1) enable_restoration(1) high_bitdepth(1) db 0x01 ; mono_chrome(1) color_description_present_flag(1) color_range(1) chroma_sample_position(1) separate_uv_delta_q(1) film_grain_params_present(1) bits(2) ; /seqhdr(0) av1C_end: pixi_start: dd BE(pixi_end - pixi_start) dd "pixi" db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x03 ; (8) db 0x08 ; (8) db 0x08 ; (8) db 0x08 ; (8) pixi_end: irot_start: dd BE(irot_end - irot_start) dd "irot" db 0x03 ; (8) irot_end: ipco_end: ipma_start: dd BE(ipma_end - ipma_start) dd "ipma" db 0x00 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x00, 0x00, 0x00, 0x01 ; entry_count(32) db 0x00, 0x01 ; item_ID(16) db 0x05 ; association_count(8) db 0x01 ; essential(1) property_index(7) db 0x02 ; essential(1) property_index(7) db 0x83 ; essential(1) property_index(7) db 0x04 ; essential(1) property_index(7) db 0x85 ; essential(1) property_index(7) ipma_end: iprp_end: iref_start: dd BE(iref_end - iref_start) dd "iref" db 0x00 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x00, 0x00, 0x00, 0x0E ; box_size(32) db 0x63, 0x64, 0x73, 0x63 ; box_type(32) ('cdsc') db 0x00, 0x02 ; from_item_ID(16) db 0x00, 0x01 ; reference_count(16) db 0x00, 0x01 ; to_item_ID(16) iref_end: meta_end: free_start: dd BE(free_end - free_start) dd "free" db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) db 0x00 ; (8) free_end: mdat_start: dd BE(mdat_end - mdat_start) db "mdat" db 0x00 mdat_end: ; vim: syntax=nasm
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft import six %> <%docstring>stime(when) -> str Invokes the syscall stime. See 'man 2 stime' for more information. Arguments: when(time_t*): when Returns: int </%docstring> <%page args="when=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = [] can_pushstr_array = [] argument_names = ['when'] argument_values = [when] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False))) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)): if isinstance(arg, six.text_type): arg = arg.encode('utf-8') string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_stime']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* stime(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
; A100691: Number of self-avoiding paths with n steps on a triangular lattice in the strip Z x {0,1}. ; 1,4,12,30,70,158,352,780,1724,3806,8398,18526,40864,90132,198796,438462,967062,2132926,4704320,10375708,22884348,50473022,111321758,245527870,541528768,1194379300,2634286476,5810101726,12814582758 seq $0,77852 ; Expansion of (1-x)^(-1)/(1-2*x-x^3). mov $1,$0 add $2,$0 bin $2,$0 mul $2,2 trn $0,$2 add $1,$2 add $0,$1 sub $0,2
; A308580: a(n) = 3*2^n + n^2 - n. ; 3,6,14,30,60,116,222,426,824,1608,3162,6254,12420,24732,49334,98514,196848,393488,786738,1573206,3146108,6291876,12583374,25166330,50332200,100663896,201327242,402653886,805307124,1610613548,3221226342,6442451874,12884902880,25769804832 mov $2,$0 mul $2,$0 seq $0,123720 ; a(n) = 2^n + 2^(n-1) - n. add $0,$2 add $0,1
SECTION code_clib SECTION code_l_sdcc PUBLIC ___sdcc_call_iy EXTERN l_call_iy defc ___sdcc_call_iy = l_call_iy
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include "base/os.h" #include <vector> #include <string> #include <base/logging.h> #include <boost/bind.hpp> #include <tbb/task.h> #include "io/test/event_manager_test.h" #include <cmn/agent_cmn.h> #include "base/test/task_test_util.h" #include "controller/controller_ifmap.h" #include "pkt/pkt_init.h" #include "services/services_init.h" #include "test_cmn_util.h" #include "xmpp/xmpp_init.h" #include "xmpp/test/xmpp_test_util.h" #include "vr_types.h" #include "xml/xml_pugi.h" #include "controller/controller_peer.h" #include "controller/controller_export.h" #include "controller/controller_vrf_export.h" #include "controller/controller_types.h" using namespace pugi; void RouterIdDepInit(Agent *agent) { } class AgentBgpXmppPeerTest : public AgentXmppChannel { public: AgentBgpXmppPeerTest(std::string xs, uint8_t xs_idx) : AgentXmppChannel(Agent::GetInstance(), xs, "0", xs_idx), rx_count_(0), stop_scheduler_(false), rx_channel_event_queue_( TaskScheduler::GetInstance()->GetTaskId("xmpp::StateMachine"), 0, boost::bind(&AgentBgpXmppPeerTest::ProcessChannelEvent, this, _1)) { } virtual void ReceiveUpdate(const XmppStanza::XmppMessage *msg) { rx_count_++; AgentXmppChannel::ReceiveUpdate(msg); } bool ProcessChannelEvent(xmps::PeerState state) { AgentXmppChannel::HandleAgentXmppClientChannelEvent(static_cast<AgentXmppChannel *>(this), state); return true; } void HandleXmppChannelEvent(xmps::PeerState state) { rx_channel_event_queue_.Enqueue(state); } size_t Count() const { return rx_count_; } virtual ~AgentBgpXmppPeerTest() { } void stop_scheduler(bool stop) {stop_scheduler_ = stop;} private: size_t rx_count_; bool stop_scheduler_; WorkQueue<xmps::PeerState> rx_channel_event_queue_; }; class ControlNodeMockBgpXmppPeer { public: ControlNodeMockBgpXmppPeer() : channel_ (NULL), rx_count_(0) { } void ReceiveUpdate(const XmppStanza::XmppMessage *msg) { rx_count_++; } void HandleXmppChannelEvent(XmppChannel *channel, xmps::PeerState state) { if (!channel_ && state == xmps::NOT_READY) { return; } if (state != xmps::READY) { assert(channel_ && channel == channel_); channel->UnRegisterReceive(xmps::BGP); channel_ = NULL; } else { if (channel_) { assert(channel == channel_); } //assert(channel_ && channel == channel_); channel->RegisterReceive(xmps::BGP, boost::bind(&ControlNodeMockBgpXmppPeer::ReceiveUpdate, this, _1)); channel_ = channel; } } bool SendUpdate(uint8_t *msg, size_t size) { if (channel_ && (channel_->GetPeerState() == xmps::READY)) { return channel_->Send(msg, size, xmps::BGP, boost::bind(&ControlNodeMockBgpXmppPeer::WriteReadyCb, this, _1)); } return false; } void WriteReadyCb(const boost::system::error_code &ec) { } size_t Count() const { return rx_count_; } virtual ~ControlNodeMockBgpXmppPeer() { } private: XmppChannel *channel_; size_t rx_count_; }; class AgentXmppUnitTest : public ::testing::Test { protected: AgentXmppUnitTest() : thread_(&evm_), agent_(Agent::GetInstance()) {} virtual void SetUp() { //TestInit initilaizes xmpp connection to 127.0.0.1, so disconnect that //and again spawn a new one. Its required since the receive path //is overridden by mock class. //TODO later use the agent initializer agent_->controller()->Cleanup(); client->WaitForIdle(); agent_->controller()->DisConnect(); client->WaitForIdle(); xs1 = new XmppServer(&evm_, XmppInit::kControlNodeJID); xs2 = new XmppServer(&evm_, XmppInit::kControlNodeJID); xs3 = new XmppServer(&evm_, XmppInit::kControlNodeJID); xs4 = new XmppServer(&evm_, XmppInit::kControlNodeJID); xs5 = new XmppServer(&evm_, XmppInit::kControlNodeJID); xs6 = new XmppServer(&evm_, XmppInit::kControlNodeJID); xs1->Initialize(0, false); xs2->Initialize(0, false); xs3->Initialize(0, false); xs4->Initialize(0, false); xs5->Initialize(0, false); xs6->Initialize(0, false); thread_.Start(); } virtual void TearDown() { TaskScheduler::GetInstance()->Stop(); Agent::GetInstance()->controller()->unicast_cleanup_timer().cleanup_timer_->Fire(); Agent::GetInstance()->controller()->multicast_cleanup_timer().cleanup_timer_->Fire(); Agent::GetInstance()->controller()->config_cleanup_timer().cleanup_timer_->Fire(); TaskScheduler::GetInstance()->Start(); client->WaitForIdle(); Agent::GetInstance()->controller()->Cleanup(); client->WaitForIdle(); TcpServerManager::DeleteServer(xs1); TcpServerManager::DeleteServer(xs2); TcpServerManager::DeleteServer(xs3); TcpServerManager::DeleteServer(xs4); TcpServerManager::DeleteServer(xs5); TcpServerManager::DeleteServer(xs6); evm_.Shutdown(); thread_.Join(); client->WaitForIdle(); } void XmppServerConnectionInit() { //Init VNController for running tests agent_->controller()->Connect(); //Create control-node bgp mock peer mock_peer1.reset(new ControlNodeMockBgpXmppPeer()); xs1->RegisterConnectionEvent(xmps::BGP, boost::bind(&ControlNodeMockBgpXmppPeer::HandleXmppChannelEvent, mock_peer1.get(), _1, _2)); //Create control-node bgp mock peer mock_peer2.reset(new ControlNodeMockBgpXmppPeer()); xs2->RegisterConnectionEvent(xmps::BGP, boost::bind(&ControlNodeMockBgpXmppPeer::HandleXmppChannelEvent, mock_peer2.get(), _1, _2)); //Create control-node bgp mock peer mock_peer3.reset(new ControlNodeMockBgpXmppPeer()); xs3->RegisterConnectionEvent(xmps::BGP, boost::bind(&ControlNodeMockBgpXmppPeer::HandleXmppChannelEvent, mock_peer3.get(), _1, _2)); //Create control-node bgp mock peer mock_peer4.reset(new ControlNodeMockBgpXmppPeer()); xs4->RegisterConnectionEvent(xmps::BGP, boost::bind(&ControlNodeMockBgpXmppPeer::HandleXmppChannelEvent, mock_peer4.get(), _1, _2)); //Create control-node bgp mock peer mock_peer5.reset(new ControlNodeMockBgpXmppPeer()); xs5->RegisterConnectionEvent(xmps::BGP, boost::bind(&ControlNodeMockBgpXmppPeer::HandleXmppChannelEvent, mock_peer5.get(), _1, _2)); //Create control-node bgp mock peer mock_peer6.reset(new ControlNodeMockBgpXmppPeer()); xs6->RegisterConnectionEvent(xmps::BGP, boost::bind(&ControlNodeMockBgpXmppPeer::HandleXmppChannelEvent, mock_peer6.get(), _1, _2)); } EventManager evm_; ServerThread thread_; XmppServer *xs1; XmppServer *xs2; XmppServer *xs3; XmppServer *xs4; XmppServer *xs5; XmppServer *xs6; auto_ptr<ControlNodeMockBgpXmppPeer> mock_peer1; auto_ptr<ControlNodeMockBgpXmppPeer> mock_peer2; auto_ptr<ControlNodeMockBgpXmppPeer> mock_peer3; auto_ptr<ControlNodeMockBgpXmppPeer> mock_peer4; auto_ptr<ControlNodeMockBgpXmppPeer> mock_peer5; auto_ptr<ControlNodeMockBgpXmppPeer> mock_peer6; Agent *agent_; }; namespace { TEST_F(AgentXmppUnitTest, XmppConnection_Discovery) { client->Reset(); client->WaitForIdle(); XmppServerConnectionInit(); // Simulate Discovery response for Xmpp Server std::vector<DSResponse> ds_response; DSResponse resp; resp.ep.address(boost::asio::ip::address::from_string("127.0.0.1")); resp.ep.port(xs1->GetPort()); ds_response.push_back(resp); agent_->controller()->ApplyDiscoveryXmppServices(ds_response); client->WaitForIdle(); //wait for connection establishment EXPECT_TRUE(agent_->controller_ifmap_xmpp_port(0) == (uint32_t)xs1->GetPort()); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(0)->GetXmppChannel()->GetPeerState() == xmps::READY); client->WaitForIdle(); //Bring down Xmpp Server xs1->Shutdown(); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(0)->GetXmppChannel()->GetPeerState() == xmps::NOT_READY); //Discovery indicating new Xmpp Server ds_response.clear(); resp.ep.address(boost::asio::ip::address::from_string("127.0.0.2")); resp.ep.port(xs2->GetPort()); ds_response.push_back(resp); agent_->controller()->ApplyDiscoveryXmppServices(ds_response); client->WaitForIdle(); //wait for connection establishment EXPECT_TRUE(agent_->controller_ifmap_xmpp_port(1) == (uint32_t)xs2->GetPort()); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(1)->GetXmppChannel()->GetPeerState() == xmps::READY); client->WaitForIdle(); //Bring down Xmpp Server xs2->Shutdown(); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(1)->GetXmppChannel()->GetPeerState() == xmps::NOT_READY); //Discovery indicating new Xmpp Server ds_response.clear(); resp.ep.address(boost::asio::ip::address::from_string("127.0.0.3")); resp.ep.port(xs3->GetPort()); ds_response.push_back(resp); agent_->controller()->ApplyDiscoveryXmppServices(ds_response); client->WaitForIdle(); //wait for connection establishment EXPECT_TRUE(agent_->controller_ifmap_xmpp_port(0) == (uint32_t)xs3->GetPort()); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(0)->GetXmppChannel()->GetPeerState() == xmps::READY); // Wait until older XmppClient, XmppChannel is cleaned client->WaitForIdle(); //Discovery indicating new Xmpp Server ds_response.clear(); resp.ep.address(boost::asio::ip::address::from_string("127.0.0.3")); resp.ep.port(xs3->GetPort()); ds_response.push_back(resp); resp.ep.address(boost::asio::ip::address::from_string("127.0.0.4")); resp.ep.port(xs4->GetPort()); ds_response.push_back(resp); agent_->controller()->ApplyDiscoveryXmppServices(ds_response); client->WaitForIdle(); //wait for connection establishment EXPECT_TRUE(agent_->controller_ifmap_xmpp_port(0) == (uint32_t)xs3->GetPort()); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(0)->GetXmppChannel()->GetPeerState() == xmps::READY); EXPECT_TRUE(agent_->controller_ifmap_xmpp_port(1) == (uint32_t)xs4->GetPort()); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(1)->GetXmppChannel()->GetPeerState() == xmps::READY); // Wait until older XmppClient, XmppChannel is cleaned client->WaitForIdle(); xs3->Shutdown(); client->WaitForIdle(); xs4->Shutdown(); client->WaitForIdle(); //Discovery indicating new Xmpp Server ds_response.clear(); resp.ep.address(boost::asio::ip::address::from_string("127.0.0.5")); resp.ep.port(xs5->GetPort()); ds_response.push_back(resp); resp.ep.address(boost::asio::ip::address::from_string("127.0.0.6")); resp.ep.port(xs6->GetPort()); ds_response.push_back(resp); agent_->controller()->ApplyDiscoveryXmppServices(ds_response); client->WaitForIdle(); //wait for connection establishment EXPECT_TRUE(agent_->controller_ifmap_xmpp_port(0) == (uint32_t)xs5->GetPort()); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(0)->GetXmppChannel()->GetPeerState() == xmps::READY); EXPECT_TRUE(agent_->controller_ifmap_xmpp_port(1) == (uint32_t)xs6->GetPort()); WAIT_FOR(1000, 10000, agent_->controller_xmpp_channel(1)->GetXmppChannel()->GetPeerState() == xmps::READY); // Wait until older XmppClient, XmppChannel is cleaned client->WaitForIdle(); xs5->Shutdown(); client->WaitForIdle(); EXPECT_TRUE(agent_->controller()->config_cleanup_timer(). cleanup_timer_->running() == true); if (agent_->headless_agent_mode()) { EXPECT_TRUE(agent_->controller()->unicast_cleanup_timer(). cleanup_timer_->running() == true); EXPECT_TRUE(agent_->controller()->multicast_cleanup_timer(). cleanup_timer_->running() == true); } client->WaitForIdle(); //TODO Ensure timers are not running and have expired xs6->Shutdown(); client->WaitForIdle(); } }
; Tests instructions INC & DEC with all addressing modes. ; Assumes that loads & stores & ORA work with all addressing modes. ; ; Expected Results: $01DD = 0x6E start: LDA #$4B LSR ASL STA $50 ASL $50 ASL $50 LSR $50 LDA $50 LDX $50 ORA #$C9 STA $60 ASL $4C,X LSR $4C,X LSR $4C,X LDA $4C,X LDX $60 ORA #$41 STA $012E LSR $0100,X LSR $0100,X ASL $0100,X LDA $0100,X LDX $012E ORA #$81 STA $0100,X LSR $0136 LSR $0136 ASL $0136 LDA $0100,X ; rol & ror ROL ROL ROR STA $70 LDX $70 ORA #$03 STA $0C,X ROL $C0 ROR $C0 ROR $C0 LDA $0C,X LDX $C0 STA $D0 ROL $75,X ROL $75,X ROR $75,X LDA $D0 LDX $D0 STA $0100,X ROL $01B7 ROL $01B7 ROL $01B7 ROR $01B7 LDA $0100,X LDX $01B7 STA $01DD ROL $0100,X ROR $0100,X ROR $0100,X
#include <vector> #include <string> #include <cmath> #include <algorithm> #include <unordered_map> typedef std::string string; class yozh64 { unsigned char alphabet[64] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; std::unordered_map<unsigned char, unsigned int> deAlphabet = {{'A', 0}, {'B', 1}, {'C', 2}, {'D', 3}, {'E', 4}, {'F', 5}, {'G', 6}, {'H', 7}, {'I', 8}, {'J', 9}, {'K', 10}, {'L', 11}, {'M', 12}, {'N', 13}, {'O', 14}, {'P', 15}, {'Q', 16}, {'R', 17}, {'S', 18}, {'T', 19}, {'U', 20}, {'V', 21}, {'W', 22}, {'X', 23}, {'Y', 24}, {'Z', 25}, {'a', 26}, {'b', 27}, {'c', 28}, {'d', 29}, {'e', 30}, {'f', 31}, {'g', 32}, {'h', 33}, {'i', 34}, {'j', 35}, {'k', 36}, {'l', 37}, {'m', 38}, {'n', 39}, {'o', 40}, {'p', 41}, {'q', 42}, {'r', 43}, {'s', 44}, {'t', 45}, {'u', 46}, {'v', 47}, {'w', 48}, {'x', 49}, {'y', 50}, {'z', 51}, {'0', 52}, {'1', 53}, {'2', 54}, {'3', 55}, {'4', 56}, {'5', 57}, {'6', 58}, {'7', 59}, {'8', 60}, {'9', 61}, {'+', 62}, {'/', 63}}; unsigned int dataSize; unsigned char * data; unsigned int encodedDataSize; unsigned char * encodedData; unsigned int decodedDataSize; unsigned char * decodedData; int mode = -1; public: yozh64(string data_) { dataSize = data_.size(); data = new unsigned char[dataSize]; for (int i = 0; i < dataSize; i++) data[i] = data_[i]; } yozh64(unsigned char * data_, unsigned int dataSize_) { dataSize = dataSize_; data = new unsigned char[dataSize]; for (int i = 0; i < dataSize; i++) data[i] = data_[i]; } void encode() { mode = 1; unsigned int charSize = sizeof(unsigned char)*8; encodedDataSize = (unsigned int)ceil(1.0*dataSize*charSize/6.0); encodedData = new unsigned char[encodedDataSize]; std::fill(encodedData, encodedData+encodedDataSize, 0); unsigned int _masks[6] = {0xfc, 0x3f, 0xf0, 0x0f, 0xc0, 0x03}; for (int i = 0, j = 0; i < encodedDataSize; i++) { if (i % 4 == 0) { encodedData[i] = alphabet[(data[j]&_masks[0]) >> 2]; } else if (i % 4 == 1) { unsigned int _tmp = (data[j]&_masks[5]) << 4; if (j < dataSize-1) { _tmp |= ((data[j+1]&_masks[2]) >> 4); } encodedData[i] = alphabet[_tmp]; j++; } else if (i % 4 == 2) { unsigned int _tmp = (data[j]&_masks[3]) << 2; if (j < dataSize-1) { _tmp |= ((data[j+1]&_masks[4]) >> 6); } encodedData[i] = alphabet[_tmp]; j++; } else { encodedData[i] = alphabet[data[j]&_masks[1]]; j++; } } return; } void decode() { mode = 0; unsigned int charSize = sizeof(unsigned char)*8; decodedDataSize = (dataSize * 6) / charSize; decodedData = new unsigned char [decodedDataSize]; std::fill(decodedData, decodedData+decodedDataSize, 0); for (int i = 0, j = 0; i < dataSize; i++) { if (i % 4 == 0) { decodedData[j] |= (deAlphabet[data[i]] << 2); } else if (i % 4 == 1) { unsigned int _tmp = deAlphabet[data[i]]; decodedData[j] |= (_tmp >> 4); if (j < decodedDataSize - 1) { decodedData[j + 1] |= (_tmp << 4); } j++; } else if (i % 4 == 2) { unsigned int _tmp = deAlphabet[data[i]]; decodedData[j] |= (_tmp >> 2); if (j < decodedDataSize - 1) { decodedData[j + 1] |= (_tmp << 6); } j++; } else { decodedData[j] |= deAlphabet[data[i]]; j++; } } return; } string getResult() { if (mode == -1) throw std::runtime_error("YOZH64 Error cannot convert unmanipulated data to string!"); unsigned char * resAr; unsigned int resArSize; if (mode) resAr = encodedData, resArSize = encodedDataSize; else resAr = decodedData, resArSize = decodedDataSize; string result; result.reserve(resArSize); for (int i = 0; i < resArSize; i++) result += resAr[i]; return result; } };
#include "RutgersIAF/EventAnalyzer/interface/ObjectVariableDeltaBetaCorrectedTotalIso.h" #include "RutgersIAF/EventAnalyzer/interface/SignatureObject.h" ClassImp(ObjectVariableDeltaBetaCorrectedTotalIso) using namespace std; bool ObjectVariableDeltaBetaCorrectedTotalIso::calculate(SignatureObject* sigObj) { if(m_flagName != ""){ bool goodFlag = false; bool isSet_flag = sigObj->getVariable(m_flagName, goodFlag); if(!(isSet_flag && goodFlag))return false; } double chargedHadronIso = 0; bool isSet_chargedHadronIso = sigObj->getVariable(m_chargedHadronName,chargedHadronIso); double neutralHadronIso = 0; bool isSet_neutralHadronIso = m_neutralHadronName.Length() ? sigObj->getVariable(m_neutralHadronName,neutralHadronIso) : true; double photonIso = 0; bool isSet_photonIso = sigObj->getVariable(m_photonName,photonIso); double beta = 0; bool isSet_beta = sigObj->getVariable(m_betaName,beta); if(!(isSet_chargedHadronIso && isSet_neutralHadronIso && isSet_photonIso && isSet_beta))return false; double totalIso = chargedHadronIso + max(0.0,neutralHadronIso + photonIso - 0.5 * beta); sigObj->setVariable(getName(),totalIso); return true; }
; A157786: a(n) = 27225*n^2 - 15248*n + 2135. ; 14112,80539,201416,376743,606520,890747,1229424,1622551,2070128,2572155,3128632,3739559,4404936,5124763,5899040,6727767,7610944,8548571,9540648,10587175,11688152,12843579,14053456,15317783,16636560,18009787,19437464,20919591,22456168,24047195,25692672,27392599,29146976,30955803,32819080,34736807,36708984,38735611,40816688,42952215,45142192,47386619,49685496,52038823,54446600,56908827,59425504,61996631,64622208,67302235,70036712,72825639,75669016,78566843,81519120,84525847,87587024,90702651 seq $0,157787 ; 8984250n - 2515920. pow $0,2 sub $0,41839292988900 div $0,2964802500 add $0,14112
// // XRhodes // // copyright (c) Gyorgy Straub. All rights reserved. // // License: https://github.com/zyndor/xrhodes#License-bsd-2-clause // //============================================================================== #include "Example.hpp" #include "DragController.hpp" #include "xr/Device.hpp" #include "xr/Transforms.hpp" #include "xr/Timer.hpp" #include "xr/Material.hpp" #include "xr/Asset.hpp" #include "xr/meshutil.hpp" #include "xr/Mesh.hpp" #include "xr/Vertex.hpp" #include "xr/math/Vector4.hpp" #include "xr/math/Quaternion.hpp" #include "xr/utils.hpp" using namespace xr; namespace { // We're adding a directional light to the previous example, for which we need to // add normals to our vertex format, and update the shaders. class Example07 : public Example { public: Example07() : Example("07 - Phong Shading") {} virtual void Init() override { Gfx::Init(Device::GetGfxContext()); Asset::Manager::Init(".assets"); Transforms::Init(); // Add normals to vertex format. using VertexType = Vertex::Format<Vertex::Pos<>, Vertex::UV0<>, Vertex::Color0<Vector3>, Vertex::Normal>; // While we won't specify normals manually, we'll need to replace shared // vertices from the last example, with unique ones. This means that we // no longer need an index buffer, and can use Mesh instead of IndexMesh. VertexType vertices[] = { VertexType(Vector3::UnitY() * .8f, Vector2(.5f, .5f), Vector3(1.f, 1.f, 1.f)), // CT VertexType(Vector3(-1.f, 0.f, 1.f), Vector2(0.f, 0.f), Vector3(1.f, .5f, .5f)), // NW0 VertexType(Vector3(1.f, 0.f, 1.f), Vector2(1.f, 0.f), Vector3(.5f, 1.f, .5f)), // NE0 VertexType(Vector3::UnitY() * .8f, Vector2(.5f, .5f), Vector3(1.f, 1.f, 1.f)), // CT VertexType(Vector3(1.f, 0.f, 1.f), Vector2(1.f, 0.f), Vector3(.5f, 1.f, .5f)), // NE1 VertexType(Vector3(1.f, 0.f, -1.f), Vector2(1.f, 1.f), Vector3(.5f, .5f, 1.f)), // SE0 VertexType(Vector3::UnitY() * .8f, Vector2(.5f, .5f), Vector3(1.f, 1.f, 1.f)), // CT VertexType(Vector3(1.f, 0.f, -1.f), Vector2(1.f, 1.f), Vector3(.5f, .5f, 1.f)), // SE1 VertexType(Vector3(-1.f, 0.f, -1.f), Vector2(0.f, 1.f), Vector3(.5f, .5f, .5f)), //SW0 VertexType(Vector3::UnitY() * .8f, Vector2(.5f, .5f), Vector3(1.f, 1.f, 1.f)), // CT VertexType(Vector3(-1.f, 0.f, -1.f), Vector2(0.f, 1.f), Vector3(.5f, .5f, .5f)), //SW1 VertexType(Vector3(-1.f, 0.f, 1.f), Vector2(0.f, 0.f), Vector3(1.f, .5f, .5f)), // NW1 VertexType(Vector3::UnitY() * -.8f, Vector2(.5f, .5f), Vector3(1.f, 1.f, 1.f)), // CT VertexType(Vector3(1.f, 0.f, 1.f), Vector2(1.f, 1.f), Vector3(.5f, 1.f, .5f)), // NE0 VertexType(Vector3(-1.f, 0.f, 1.f), Vector2(0.f, 1.f), Vector3(1.f, .5f, .5f)), // NW0 VertexType(Vector3::UnitY() * -.8f, Vector2(.5f, .5f), Vector3(1.f, 1.f, 1.f)), // CT VertexType(Vector3(1.f, 0.f, -1.f), Vector2(1.f, 0.f), Vector3(.5f, .5f, 1.f)), // SE0 VertexType(Vector3(1.f, 0.f, 1.f), Vector2(1.f, 1.f), Vector3(.5f, 1.f, .5f)), // NE1 VertexType(Vector3::UnitY() * -.8f, Vector2(.5f, .5f), Vector3(1.f, 1.f, 1.f)), // CT VertexType(Vector3(-1.f, 0.f, -1.f), Vector2(0.f, 0.f), Vector3(.5f, .5f, .5f)), //SW0 VertexType(Vector3(1.f, 0.f, -1.f), Vector2(1.f, 0.f), Vector3(.5f, .5f, 1.f)), // SE1 VertexType(Vector3::UnitY() * -.8f, Vector2(.5f, .5f), Vector3(1.f, 1.f, 1.f)), // CT VertexType(Vector3(-1.f, 0.f, 1.f), Vector2(0.f, 1.f), Vector3(1.f, .5f, .5f)), // NW1 VertexType(Vector3(-1.f, 0.f, -1.f), Vector2(0.f, 0.f), Vector3(.5f, .5f, .5f)), //SW1 }; // Get meshutil to calculate normals for our triangles. meshutil::CalculateTrianglesNormals(XR_ARRAY_SIZE(vertices), vertices); // Create mesh m_mesh = Mesh::Create(XR_ARRAY_SIZE(vertices), vertices); m_numInstances = 32; struct InstanceData { Vector3 pos; float scale; Quaternion rotation; }; std::vector<InstanceData> instanceData; instanceData.reserve(m_numInstances); float inc = kPi * (3.f - std::sqrt(5.f)); float off = 2.f / instanceData.capacity(); InstanceData id; for (size_t i = 0; i < m_numInstances; ++i) { id.pos.y = i * off - 1.f + off * .5f; float r = std::sqrt(1.f - id.pos.y * id.pos.y); float phi = i * inc; id.pos.x = std::cos(phi) * r; id.pos.z = std::sin(phi) * r; id.pos.Normalise(); id.rotation = Quaternion::FromPositions(Vector3::UnitY(), id.pos); id.scale = ((i % 3) + 1) / 3.f; id.pos *= 4.5f * id.scale; instanceData.push_back(id); } // Upload instance data. m_hInstanceData = Gfx::CreateInstanceDataBuffer({ instanceData.size() * sizeof(InstanceData), reinterpret_cast<uint8_t*>(instanceData.data()) }, sizeof(InstanceData)); // Create uniforms for lighting m_uLightColor = Gfx::CreateUniform("uLightColor", Gfx::UniformType::Vec4); m_uLightDirection = Gfx::CreateUniform("uLightDir", Gfx::UniformType::Vec4); Vector4 lightDirection = Vector4::From(-Vector3::UnitY()); Gfx::SetUniform(m_uLightDirection, &lightDirection); Texture::RegisterSamplerUniform("uTexture0", 0); Gfx::Flush(); m_rotation = Quaternion::Identity(); m_dragControl.Reset(); m_dragControl.ConnectMouse(); m_loading = true; m_material = Asset::Manager::Load<Material>("example07.mtl"); } virtual void Update() override { if (m_loading) { Asset::Manager::Update(); m_loading = !CheckAllMaskBits(m_material->GetFlags(), Asset::ReadyFlag); } else { m_dragControl.Update(); float weight = 1.f - m_dragControl.GetPressTimerPercent(); const float controlPoints[] = { 0.f, .12f, .88f, 1.f }; weight = Bezier(controlPoints, weight); auto motion = m_dragControl.GetFrameMotion() * 0.01f; m_rotation *= Quaternion::FromAxisAngle(Vector3(.2, .5, 0.f), weight * .002f) * Quaternion::FromPitchYawRoll(motion.x, motion.y, 0.); // Change the color of the light over time. Color lightColor(.75f, .66f + sinf(float(Timer::GetUST() * .0002)) * .333f, .5f); Gfx::SetUniform(m_uLightColor, &lightColor); } } virtual void Render() override { if (m_loading) { Gfx::Clear(Gfx::F_CLEAR_COLOR | Gfx::F_CLEAR_DEPTH, Color(FlopRand(), FlopRand(), FlopRand())); Gfx::Present(); return; } Gfx::Clear(Gfx::F_CLEAR_COLOR | Gfx::F_CLEAR_DEPTH, Color(0.f, .125f, .25f)); m_material->Apply(); XR_TRANSFORMS_SCOPED_MODEL(Matrix(m_rotation, Vector3::UnitZ() * -10.f)); // Set instance data Gfx::SetInstanceData(m_hInstanceData, 0, m_numInstances); // Render mesh (instances -- since we've set instance data). m_mesh.Render(Primitive::TriangleList); Gfx::Present(); } virtual void Shutdown() override { m_dragControl.DisconnectMouse(); m_material.Reset(nullptr); m_mesh = Mesh(); Gfx::Release(m_hInstanceData); m_hInstanceData.Invalidate(); Gfx::Release(m_uLightColor); m_uLightColor.Invalidate(); Gfx::Release(m_uLightDirection); m_uLightDirection.Invalidate(); Asset::Manager::Shutdown(); Gfx::Shutdown(); } private: Mesh m_mesh; Gfx::InstanceDataBufferHandle m_hInstanceData; uint32_t m_numInstances; Gfx::UniformHandle m_uLightDirection; Gfx::UniformHandle m_uLightColor; bool m_loading; Material::Ptr m_material; DragController m_dragControl; Quaternion m_rotation; } example; }
; A057569: Numbers of the form k*(5*k+1)/2 or k*(5*k-1)/2. ; 0,2,3,9,11,21,24,38,42,60,65,87,93,119,126,156,164,198,207,245,255,297,308,354,366,416,429,483,497,555,570,632,648,714,731,801,819,893,912,990,1010,1092,1113,1199,1221,1311,1334,1428,1452,1550,1575,1677,1703,1809,1836,1946,1974,2088,2117,2235,2265,2387,2418,2544,2576,2706,2739,2873,2907,3045,3080,3222,3258,3404,3441,3591,3629,3783,3822,3980,4020,4182,4223,4389,4431,4601,4644,4818,4862,5040,5085,5267,5313,5499,5546,5736,5784,5978,6027,6225 mov $2,$0 lpb $0 trn $0,2 add $2,1 add $1,$2 lpe mov $0,$1
; A170448: Number of reduced words of length n in Coxeter group on 7 generators S_i with relations (S_i)^2 = (S_i S_j)^45 = I. ; 1,7,42,252,1512,9072,54432,326592,1959552,11757312,70543872,423263232,2539579392,15237476352,91424858112,548549148672,3291294892032,19747769352192,118486616113152,710919696678912,4265518180073472 mov $1,6 pow $1,$0 mul $1,21 div $1,18
section .data name : db 'Abhinav p',10 l : equ $-name address : db 'Panayampurath house , rammallur',0ah l1 : equ $-address district : db 'Kozhikode',0ah l2 : equ $-district section .text global _start: _start: mov eax, 4 mov ebx, 1 mov ecx, name mov edx, l int 80h mov eax, 4 mov ebx, 1 mov ecx, address mov edx, l1 int 80h mov eax, 4 mov ebx, 1 mov ecx, district mov edx, l2 int 80h mov eax, 1 mov ebx, 0 int 80h
; Listing generated by Microsoft (R) Optimizing Compiler Version 16.00.30319.01 TITLE C:\JitenderN\REBook\Pointers\Pointers\Pointers.cpp .686P .XMM include listing.inc .model flat INCLUDELIB LIBCMT INCLUDELIB OLDNAMES CONST SEGMENT $SG4679 DB 0aH, 'Address of iNumber = 0x%p', 00H ORG $+1 $SG4680 DB 0aH, 'Address of iNumber = 0x%p', 00H ORG $+1 $SG4681 DB 0aH, 'Address of piNumber = 0x%p', 00H $SG4682 DB 0aH, 'Value of piNumber = %p', 00H $SG4683 DB 0aH, 'Value of iNumber = %d', 00H ORG $+1 $SG4684 DB 0aH, 'Value of iNumber = %d', 00H ORG $+1 $SG4685 DB 0aH, 'Value of iNumber = %d', 00H CONST ENDS PUBLIC _main EXTRN _printf:PROC ; Function compile flags: /Odtp _TEXT SEGMENT _piNumber$ = -8 ; size = 4 _iNumber$ = -4 ; size = 4 _main PROC ; File c:\jitendern\rebook\pointers\pointers\pointers.cpp ; Line 7 push ebp mov ebp, esp sub esp, 8 ; Line 8 mov DWORD PTR _iNumber$[ebp], 3 ; Line 10 lea eax, DWORD PTR _iNumber$[ebp] mov DWORD PTR _piNumber$[ebp], eax ; Line 12 lea ecx, DWORD PTR _iNumber$[ebp] push ecx push OFFSET $SG4679 call _printf add esp, 8 ; Line 13 mov edx, DWORD PTR _piNumber$[ebp] push edx push OFFSET $SG4680 call _printf add esp, 8 ; Line 14 lea eax, DWORD PTR _piNumber$[ebp] push eax push OFFSET $SG4681 call _printf add esp, 8 ; Line 15 mov ecx, DWORD PTR _piNumber$[ebp] push ecx push OFFSET $SG4682 call _printf add esp, 8 ; Line 16 mov edx, DWORD PTR _iNumber$[ebp] push edx push OFFSET $SG4683 call _printf add esp, 8 ; Line 17 mov eax, DWORD PTR _iNumber$[ebp] push eax push OFFSET $SG4684 call _printf add esp, 8 ; Line 18 mov ecx, DWORD PTR _piNumber$[ebp] mov edx, DWORD PTR [ecx] push edx push OFFSET $SG4685 call _printf add esp, 8 ; Line 19 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP _TEXT ENDS END
; A247727: Number of length 1+3 0..n arrays with no disjoint pairs in any consecutive four terms having the same sum. ; 8,48,168,440,960,1848,3248,5328,8280,12320,17688,24648,33488,44520,58080,74528,94248,117648,145160,177240,214368,257048,305808,361200,423800,494208,573048,660968,758640,866760,986048,1117248,1261128 add $0,2 bin $0,2 add $0,1 bin $0,2 mov $1,$0 mul $1,8
.extern _stack .global start .equ N, 8 .data A: .word 7,3,25,4,75,2,1,1 .bss B: .space N*4 max: .space 4 ind: .space 4 .text start: LDR SP, =_stack MOV FP, #0 MOV R1, #N // R1 = N MOV R4, #0 // R4 = j for1: LDR R0, =A // R0 = A CMP R4, #N BGE fin_for1 BL sub_max MOV R5, R0 // ind = max(A) LDR R6, =A LDR R7, [R6, R5, LSL#2] LDR R8, =B STR R7, [R8, R4, LSL#2] MOV R9, #0 STR R9, [R6, R5, LSL#2] ADD R4, R4, #1 B for1 fin_for1: B . sub_max:PUSH {R4 - R9, FP} // Prologo max ADD FP, SP, #24 // 24 = 7*4 - 4 MOV R4, R0 // R4 = A LDR R6, =max MOV R7, #0 STR R7, [R6] // MAX = 0 LDR R8, =ind STR R7, [R8] // IND = 0 MOV R5, #0 // R5 = i = 0 for: CMP R5, R1 BGE fin_for LDR R7, [R4, R5, LSL#2] // R7 = A[i] LDR R9, [R6] // R9 = max CMP R7, R9 BLE finif STR R7, [R6] STR R5, [R8] finif: ADD R5, R5, #1 B for fin_for: LDR R4, [R8] MOV R0, R4 B ret_max ret_max: POP {R4- R9, FP} MOV PC, LR .end
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "pooling_inst.h" #include "primitive_type_base.h" #include "sliding_window_utils.hpp" #include "intel_gpu/runtime/error_handler.hpp" #include "json_object.h" #include <string> using namespace ov::runtime::intel_gpu; namespace cldnn { primitive_type_id pooling::type_id() { static primitive_type_base<pooling> instance; return &instance; } layout pooling_inst::calc_output_layout(parent::typed_node const& node) { auto desc = node.get_primitive(); auto input_layout = node.input().get_output_layout(); auto pad = desc->pad; auto stride = desc->stride; auto window_size = desc->size; // auto output_type = node.get_primitive()->output_data_type ? *node.get_primitive()->output_data_type : input_layout.data_type; // FIXME: dirty hack. Replace it with optional output data type (above) once IE returns correct precision on edges auto output_type = input_layout.data_type; if (output_type == data_types::u8 || output_type == data_types::i8) { if (desc->mode == pooling_mode::average_no_padding || desc->mode == pooling_mode::average) { output_type = data_types::f32; } } if (node.has_fused_primitives()) { output_type = node.get_fused_output_layout().data_type; } if (!desc->argmax.empty()) CLDNN_ERROR_NOT_EQUAL(node.id(), "Pooling mode", static_cast<size_t>(desc->mode), "should be max_with_argmax", static_cast<size_t>(pooling_mode::max_with_argmax), "Pooling mode should be set to max_with_argmax when argmax primitive is present."); if (desc->mode == pooling_mode::max_with_argmax) { CLDNN_ERROR_NOT_EQUAL(node.id(), "Argmax primitive", static_cast<size_t>(desc->argmax.empty()), "should not be empty", static_cast<size_t>(0), "Argmax primitive not present despite max_with_argmax mode."); auto argmax_layout = node.argmax().get_output_layout(); CLDNN_ERROR_NOT_EQUAL(node.id(), "Argmax data type", static_cast<size_t>(argmax_layout.data_type), "expected to be fp32", static_cast<size_t>(data_types::f32), "Argmax data type is not fp32."); CLDNN_ERROR_NOT_PROPER_FORMAT(node.id(), "Input_layout.format", input_layout.format.value, "argmax_layout.format", argmax_layout.format); } if (desc->global_pooling) { window_size = ov::Shape(input_layout.get_spatial_rank(), 1); for (size_t i = 0; i < input_layout.get_spatial_rank(); i++) { window_size[i] = input_layout.spatial(input_layout.get_spatial_rank() - i - 1); } } uint32_t stride_z = stride.size() >= 3 ? stride[stride.size() - 3] : 1; uint32_t stride_y = stride.size() >= 2 ? stride[stride.size() - 2] : 1; uint32_t stride_x = stride.size() >= 1 ? stride[stride.size() - 1] : 1; uint32_t kernel_z = window_size.size() >= 3 ? window_size[window_size.size() - 3] : 1; uint32_t kernel_y = window_size.size() >= 2 ? window_size[window_size.size() - 2] : 1; uint32_t kernel_x = window_size.size() >= 1 ? window_size[window_size.size() - 1] : 1; // TODO: Consider moving general parameter verification to arguments constructor. CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "stride spatial X", stride_x, "", 0, "Stride spatial X must be positive (>= 1)"); CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "stride spatial Y", stride_y, "", 0, "Stride spatial Y must be positive (>= 1)"); CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "window size spatial X", kernel_x, "", 0, "Size X (of pooling window) must be positive (>= 1)"); CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "window size spatial Y", kernel_y, "", 0, "Size Y (of pooling window) must be positive (>= 1)"); if (input_layout.format.spatial_num() == 3) { // 3D CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "stride spatial Z", stride_z, "", 0, "Stride spatial Z must be positive (>= 1)"); CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "window size spatial Z", kernel_z, "", 0, "Size Z (of pooling window) must be positive (>= 1)"); } if (desc->with_output_size) { CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "User-defined size of output X", desc->output_size.spatial[0], "", 0, "User-defined size of output layout (spatial X) must be positive (>= 1)"); CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "User-defined size of output Y", desc->output_size.spatial[1], "", 0, "User-defined size of output layout (spatial Y) must be positive (>= 1)"); CLDNN_ERROR_LESS_OR_EQUAL_THAN(node.id(), "User-defined size of output Z", desc->output_size.spatial[2], "", 0, "User-defined size of output layout (spatial Z) must be positive (>= 1)"); tensor output_size(input_layout.batch(), input_layout.feature(), desc->output_size.spatial[0], desc->output_size.spatial[1], desc->output_size.spatial[2]); return {output_type, input_layout.format, output_size}; } // TODO: Check compatibility of output size calculation (with caffe). tensor size(1); for (size_t i = 0; i < window_size.size(); i++) { size.spatial[i] = window_size[window_size.size() - i - 1]; } auto output_range = calc_sliding_window_output_range<swor_mode::exceed_once_data>(input_layout.size, size, ov::CoordinateDiff(pad.begin(), pad.end()), stride, ov::Strides(window_size.size(), 1), true, 1); tensor output_size(input_layout.batch(), input_layout.feature(), output_range.spatial[0], output_range.spatial[1], output_range.spatial[2]); return {output_type, input_layout.format, output_size}; } std::string pooling_inst::to_string(pooling_node const& node) { auto desc = node.get_primitive(); auto strd = desc->stride; auto mode = desc->mode == pooling_mode::max ? "max" : "average"; auto node_info = node.desc_to_json(); auto kernel_size = desc->size; std::stringstream primitive_description; bool is_global = desc->global_pooling; json_composite pooling_info; pooling_info.add("mode", mode); pooling_info.add("stride", cldnn::to_string(strd)); pooling_info.add("kernel size", cldnn::to_string(kernel_size)); pooling_info.add("is global", is_global ? "true" : "false"); if (desc->with_output_size) { json_composite ud_out_size_info; ud_out_size_info.add("size", desc->output_size.to_string()); pooling_info.add("with_user_defined_output_size", ud_out_size_info); } node_info->add("pooling info", pooling_info); node_info->dump(primitive_description); return primitive_description.str(); } } // namespace cldnn
ldi $s0, 3 //0,1 la $s1, end //2,3 loop: beq $s0, $0, $s1 //4 addi $s0, -1 //5 move $s0, $rr //6 j loop //7 end: j end //8
/* * SPDX-License-Identifier: Apache-2.0 */ //===------ LowerToLLVM.cpp - Lowering from KRNL+Affine+Std to LLVM -------===// // // Copyright 2019-2020 The IBM Research Authors. // // ============================================================================= // // // //===----------------------------------------------------------------------===// #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" #include "mlir/Conversion/ArithmeticToLLVM/ArithmeticToLLVM.h" #include "mlir/Conversion/LLVMCommon/Pattern.h" #include "mlir/Conversion/LLVMCommon/TypeConverter.h" #include "mlir/Conversion/MathToLLVM/MathToLLVM.h" #include "mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h" #include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" #include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" #include "mlir/Dialect/Affine/IR/AffineOps.h" #include "mlir/Dialect/Arithmetic/Transforms/Passes.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/SCF/SCF.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Dialect/StandardOps/Transforms/Passes.h" #include "mlir/Dialect/Vector/VectorOps.h" #include "mlir/IR/BuiltinTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Target/LLVMIR/ModuleTranslation.h" #include "mlir/Transforms/DialectConversion.h" #include "llvm/ADT/Sequence.h" #include "llvm/Support/Endian.h" #include "onnx/onnx_pb.h" #include "src/Conversion/KrnlToLLVM/KrnlToLLVM.hpp" #include "src/Conversion/ONNXToKrnl/ONNXToKrnlCommon.hpp" #include "src/Dialect/Krnl/KrnlOps.hpp" #include "src/Pass/Passes.hpp" #include "src/Support/Common.hpp" using namespace mlir; namespace { static onnx::TensorProto::DataType llvmTypeToOnnxType(mlir::Type elemType) { if (elemType.isa<Float32Type>()) return onnx::TensorProto::FLOAT; if (elemType.isUnsignedInteger(8)) return onnx::TensorProto::UINT8; if (elemType.isSignedInteger(8)) return onnx::TensorProto::INT8; if (elemType.isUnsignedInteger(16)) return onnx::TensorProto::UINT16; if (elemType.isSignedInteger(16)) return onnx::TensorProto::INT16; if (elemType.isSignedInteger(32)) return onnx::TensorProto::INT32; if (elemType.isSignedInteger(64)) return onnx::TensorProto::INT64; // TODO, wait for Tong's input about how string is represented in MLIR. if (elemType.isa<Float16Type>()) return onnx::TensorProto::FLOAT16; if (elemType.isa<Float64Type>()) return onnx::TensorProto::DOUBLE; if (elemType.isUnsignedInteger(32)) return onnx::TensorProto::UINT32; if (elemType.isUnsignedInteger(64)) return onnx::TensorProto::INT64; // LLVM Dialect does not have signed/unsigned int, only signless int if (auto llvmIntType = elemType.dyn_cast<IntegerType>()) { if (llvmIntType.getWidth() == 1) return onnx::TensorProto::BOOL; if (llvmIntType.getWidth() == 8) return onnx::TensorProto::INT8; if (llvmIntType.getWidth() == 16) return onnx::TensorProto::INT16; if (llvmIntType.getWidth() == 32) return onnx::TensorProto::INT32; if (llvmIntType.getWidth() == 64) return onnx::TensorProto::INT64; } // Complex types don't seem to exist in LLVM Dialect. elemType.dump(); llvm_unreachable("Unexpected LLVM type, cannot be converted to ONNX type."); } static FlatSymbolRefAttr getOrInsertExternFunc(StringRef funcName, ModuleOp module, mlir::Type funcType, PatternRewriter &rewriter) { auto *context = module.getContext(); if (auto sym = module.lookupSymbol<LLVM::LLVMFuncOp>(funcName)) { assert(sym.getType() == funcType && "wrong symbol type"); return SymbolRefAttr::get(context, funcName); } // Insert the function into the body of the parent module. PatternRewriter::InsertionGuard insertGuard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); rewriter.create<LLVM::LLVMFuncOp>(module.getLoc(), funcName, funcType); return SymbolRefAttr::get(context, funcName); } static size_t getRankFromMemRefType(LLVM::LLVMStructType memRefTy) { // Usually a MemRef is a 5-element struct, where the 4th and 5th elements in // this struct are arrays whose size is the rank of the tensor. In the event // that the corresponding tensor of this MemRef is a scalar, the 4th and 5th // elements will have 0-length, which in turn causes the MemRef struct to // degenerate into a 3-element struct. For more information, refer to // https://github.com/llvm/llvm-project/blob/master/mlir/docs/ConversionToLLVMDialect.md#memref-types. auto numElems = memRefTy.getBody().size(); assert((numElems == 3 || numElems == 5) && "Expect MemRef type to contain either 3 or 5 elements."); if (numElems == 3) return 0; // MemRef refers to a scalar. else return memRefTy.getBody()[3].cast<LLVM::LLVMArrayType>().getNumElements(); } // Create a function declaration for OMInstrumentPoint, the signature is: // `void (i64, i64)` static FlatSymbolRefAttr getOrInsertInstrument( PatternRewriter &rewriter, ModuleOp module) { auto *context = module.getContext(); std::string funcName("OMInstrumentPoint"); if (module.lookupSymbol<LLVM::LLVMFuncOp>(funcName)) return SymbolRefAttr::get(context, funcName); auto llvmVoidTy = LLVM::LLVMVoidType::get(context); auto llvmI64Ty = IntegerType::get(context, 64); auto llvmFnType = LLVM::LLVMFunctionType::get( llvmVoidTy, ArrayRef<mlir::Type>({llvmI64Ty, llvmI64Ty}), false); PatternRewriter::InsertionGuard insertGuard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); rewriter.create<LLVM::LLVMFuncOp>(module.getLoc(), funcName, llvmFnType); return SymbolRefAttr::get(context, funcName); } /// Return a symbol reference to the memcpy function, inserting it into the /// module if necessary. static FlatSymbolRefAttr getOrInsertMemcpy( PatternRewriter &rewriter, ModuleOp module) { auto *context = module.getContext(); if (module.lookupSymbol<LLVM::LLVMFuncOp>("llvm.memcpy.p0i8.p0i8.i64")) return SymbolRefAttr::get(context, "llvm.memcpy.p0i8.p0i8.i64"); // Create a function declaration for memcpy, the signature is: // * `void (i8*, i8* , i64, i1)` auto llvmVoidTy = LLVM::LLVMVoidType::get(context); auto llvmI8PtrTy = LLVM::LLVMPointerType::get(IntegerType::get(context, 8)); auto llvmI64Ty = IntegerType::get(context, 64); auto llvmI1Ty = IntegerType::get(context, 1); auto llvmFnType = LLVM::LLVMFunctionType::get(llvmVoidTy, ArrayRef<mlir::Type>({llvmI8PtrTy, llvmI8PtrTy, llvmI64Ty, llvmI1Ty}), false); // Insert the memcpy function into the body of the parent module. PatternRewriter::InsertionGuard insertGuard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); rewriter.create<LLVM::LLVMFuncOp>( module.getLoc(), "llvm.memcpy.p0i8.p0i8.i64", llvmFnType); return SymbolRefAttr::get(context, "llvm.memcpy.p0i8.p0i8.i64"); } static FlatSymbolRefAttr getOrInsertRandomNormal( PatternRewriter &rewriter, ModuleOp module, Type inType) { MLIRContext *context = module.getContext(); StringRef functionName = inType.isF64() ? "get_random_normal_value_f64" : "get_random_normal_value_f32"; if (module.lookupSymbol<LLVM::LLVMFuncOp>(functionName.str())) return SymbolRefAttr::get(context, functionName.str()); // Signature of the input is: // "krnl.random_normal"(%0, %c60, %cst, %cst_0, %cst_1) // with types: // (memref<3x4x5xf32>, index, f32, f32, f32) // or // (memref<3x4x5xf64>, index, f64, f64, f64) auto llvmVoidTy = LLVM::LLVMVoidType::get(context); auto llvmOptionsTy = FloatType::getF32(context); auto llvmOutputTy = LLVM::LLVMPointerType::get(llvmOptionsTy); if (inType.isF64()) { llvmOptionsTy = FloatType::getF64(context); llvmOutputTy = LLVM::LLVMPointerType::get(llvmOptionsTy); } auto llvmI64Ty = IntegerType::get(context, 64); auto llvmFnType = LLVM::LLVMFunctionType::get(llvmVoidTy, ArrayRef<mlir::Type>({llvmOutputTy, llvmI64Ty, llvmOptionsTy, llvmOptionsTy, llvmOptionsTy}), false); // Insert the random normal function into the body of the parent module. PatternRewriter::InsertionGuard insertGuard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); rewriter.create<LLVM::LLVMFuncOp>( module.getLoc(), functionName.str(), llvmFnType); return SymbolRefAttr::get(context, functionName.str()); } static FlatSymbolRefAttr getOrInsertMalloc( PatternRewriter &rewriter, ModuleOp module) { // Insert the malloc/aligned_alloc declaration if it is not already present. auto allocFunc = module.lookupSymbol<LLVM::LLVMFuncOp>("malloc"); auto ctx = rewriter.getContext(); LLVMTypeConverter converter(ctx); if (!allocFunc) { OpBuilder::InsertionGuard guard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); SmallVector<Type, 2> callArgTypes = {converter.getIndexType()}; // aligned_alloc(size_t alignment, size_t size) auto voidPtrType = LLVM::LLVMPointerType::get( IntegerType::get(&converter.getContext(), 8)); allocFunc = rewriter.create<LLVM::LLVMFuncOp>(rewriter.getUnknownLoc(), "malloc", LLVM::LLVMFunctionType::get(voidPtrType, callArgTypes, /*isVarArg=*/false)); } return SymbolRefAttr::get(ctx, "malloc"); } ATTRIBUTE(unused) static FlatSymbolRefAttr getOrInsertDealloc( PatternRewriter &rewriter, ModuleOp module) { // Insert the dealloc declaration if it is not already present. auto deallocFunc = module.lookupSymbol<LLVM::LLVMFuncOp>("free"); auto ctx = rewriter.getContext(); LLVMTypeConverter converter(ctx); if (!deallocFunc) { OpBuilder::InsertionGuard guard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); auto voidPtrType = LLVM::LLVMPointerType::get( IntegerType::get(&converter.getContext(), 8)); SmallVector<Type, 2> callArgTypes = {voidPtrType}; auto llvmVoidTy = LLVM::LLVMVoidType::get(&converter.getContext()); deallocFunc = rewriter.create<LLVM::LLVMFuncOp>(rewriter.getUnknownLoc(), "free", LLVM::LLVMFunctionType::get(llvmVoidTy, callArgTypes, /*isVarArg=*/false)); } return SymbolRefAttr::get(ctx, "free"); } // This function emits a declaration of the form: // // declare float <mathFuncName>(float) // static FlatSymbolRefAttr getOrInsertUnaryMathFunction(PatternRewriter &rewriter, ModuleOp module, std::string mathFuncName, mlir::Type llvmType) { auto *context = module.getContext(); if (module.lookupSymbol<LLVM::LLVMFuncOp>(mathFuncName)) return SymbolRefAttr::get(context, mathFuncName); // Create function declaration. // auto llvmF32Ty = FloatType::get(context); auto llvmFnType = LLVM::LLVMFunctionType::get(llvmType, ArrayRef<mlir::Type>({llvmType})); // Insert the unary math function into the body of the parent module. PatternRewriter::InsertionGuard insertGuard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); rewriter.create<LLVM::LLVMFuncOp>(module.getLoc(), mathFuncName, llvmFnType); return SymbolRefAttr::get(context, mathFuncName); } //===----------------------------------------------------------------------===// // KRNL to LLVM: KrnlGetRefOpLowering //===----------------------------------------------------------------------===// class KrnlGetRefOpLowering : public ConvertToLLVMPattern { public: explicit KrnlGetRefOpLowering( MLIRContext *context, LLVMTypeConverter &lowering_) : ConvertToLLVMPattern( KrnlGetRefOp::getOperationName(), context, lowering_) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto loc = op->getLoc(); KrnlGetRefOpAdaptor operandAdaptor(operands); // This is the type of the krnl.getref output. This type is used // for the type of the internal MemRef. auto type = op->getResult(0).getType(); auto memRefTy = type.cast<mlir::MemRefType>(); // auto llvmMemRefType = typeConverter->convertType(type).cast<Type>(); auto outputElementType = typeConverter->convertType(memRefTy.getElementType()); // This is the start of the memory pool containing the output MemRef. Type memPoolType = operandAdaptor.mempool() .getType() .cast<LLVM::LLVMStructType>() .getBody()[1]; Value alignedMemPoolBase = rewriter.create<LLVM::ExtractValueOp>(loc, memPoolType, operandAdaptor.mempool(), rewriter.getI64ArrayAttr(1)); // Get pointer using the offset. auto offset = operandAdaptor.offset(); auto llvmMemPoolType = typeConverter->convertType(memPoolType).cast<Type>(); auto outputMemPoolTypePtrAlloc = rewriter.create<LLVM::GEPOp>( loc, llvmMemPoolType, alignedMemPoolBase, ArrayRef<Value>({offset})); // Bitcast to output MemRef type i.e. from i8* to the element type // of the output MemRef. auto llvmOutputElementType = outputElementType.cast<Type>(); Value outputTypedPtrAlloc = rewriter.create<LLVM::BitcastOp>(loc, LLVM::LLVMPointerType::get(llvmOutputElementType), outputMemPoolTypePtrAlloc); // Handle the static case. if (hasAllConstantDimensions(memRefTy)) { // Create llvm MemRef from original MemRef and fill the data pointers. auto llvmMemRef = MemRefDescriptor::fromStaticShape( rewriter, loc, *getTypeConverter(), memRefTy, outputTypedPtrAlloc); rewriter.replaceOp(op, {llvmMemRef}); return success(); } // Handle the dynamic case. // Compute strides and offset based on MemRef type. int64_t alignmentOffset; SmallVector<int64_t, 4> strides; auto successStrides = getStridesAndOffset(memRefTy, strides, alignmentOffset); (void)successStrides; assert(succeeded(successStrides) && "unexpected non-strided memref"); // Create the memRef descriptor. auto structType = typeConverter->convertType(memRefTy); auto memRefDescriptor = MemRefDescriptor::undef(rewriter, loc, structType); // Allocated pointer, used for malloc/free. memRefDescriptor.setAllocatedPtr(rewriter, loc, outputTypedPtrAlloc); // Actual aligned pointer to payload. // TODO: support aligned MemRefs. memRefDescriptor.setAlignedPtr(rewriter, loc, outputTypedPtrAlloc); // Offset in aligned pointer. // TODO: support non-zero here in the aligned case. memRefDescriptor.setOffset( rewriter, loc, createIndexConstant(rewriter, loc, 0)); if (memRefTy.getRank() != 0) { // Prepare sizes. SmallVector<Value, 4> sizes; sizes.reserve(memRefTy.getRank()); unsigned i = 0; for (int64_t s : memRefTy.getShape()) sizes.push_back(s == ShapedType::kDynamicSize ? operands[2 + i++] : createIndexConstant(rewriter, loc, s)); // Store all sizes in the descriptor. Only dynamic sizes are passed in as // operands to AllocOp. Value runningStride = nullptr; auto nStrides = strides.size(); SmallVector<Value, 4> strideValues(nStrides, nullptr); for (unsigned i = 0; i < nStrides; ++i) { int64_t index = nStrides - 1 - i; if (strides[index] == MemRefType::getDynamicStrideOrOffset()) // Identity layout map is enforced in the match function, so we // compute: // `runningStride *= sizes[index + 1]` runningStride = runningStride ? rewriter.create<LLVM::MulOp>(loc, runningStride, sizes[index + 1]) : createIndexConstant(rewriter, loc, 1); else runningStride = createIndexConstant(rewriter, loc, strides[index]); strideValues[index] = runningStride; } // Fill size and stride descriptors in memref. for (auto indexedSize : llvm::enumerate(sizes)) { int64_t index = indexedSize.index(); memRefDescriptor.setSize(rewriter, loc, index, indexedSize.value()); memRefDescriptor.setStride(rewriter, loc, index, strideValues[index]); } } rewriter.replaceOp(op, {memRefDescriptor}); return success(); } private: static int64_t ArrayAttrIntVal(ArrayAttr a, int i) { return (a.getValue()[i]).cast<IntegerAttr>().getInt(); } }; //===----------------------------------------------------------------------===// // KRNL to LLVM: KrnlGlobalOpLowering //===----------------------------------------------------------------------===// class KrnlGlobalOpLowering : public ConvertToLLVMPattern { public: explicit KrnlGlobalOpLowering( MLIRContext *context, LLVMTypeConverter &lowering_) : ConvertToLLVMPattern( KrnlGlobalOp::getOperationName(), context, lowering_) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto *context = op->getContext(); auto loc = op->getLoc(); auto krnlGlobalOp = llvm::dyn_cast<KrnlGlobalOp>(op); auto alignmentAttr = krnlGlobalOp.alignmentAttr(); // Get module. ModuleOp module = op->getParentOfType<ModuleOp>(); // Global name. auto name = krnlGlobalOp.name(); // Compute total number of elements. auto shape = (krnlGlobalOp.shape()).dyn_cast<ArrayAttr>(); int64_t numElements = 1; for (unsigned int i = 0; i < shape.size(); ++i) numElements *= ArrayAttrIntVal(shape, i); // Create the global at the entry of the module. LLVM::GlobalOp global; auto type = op->getResult(0).getType(); auto memRefTy = type.cast<mlir::MemRefType>(); // auto llvmMemRefType = typeConverter->convertType(type).cast<Type>(); // The element type of the array. auto constantElementType = typeConverter->convertType(memRefTy.getElementType()); auto globalType = constantElementType; // The llvm type of the global (example: [2 x [8 x float]]) if (shape.empty()) { globalType = LLVM::LLVMArrayType::get(globalType.cast<Type>(), 1); } else { for (int i = shape.size() - 1; i >= 0; i--) globalType = LLVM::LLVMArrayType::get( globalType.cast<Type>(), ArrayAttrIntVal(shape, i)); } auto llvmGlobalType = globalType.cast<Type>(); if (!krnlGlobalOp.value().hasValue()) llvm_unreachable("Krnl Global must always have a value"); int64_t sizeInBytes = numElements * getMemRefEltSizeInBytes(memRefTy); { OpBuilder::InsertionGuard insertGuard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); auto llvmArrayI8Ty = LLVM::LLVMArrayType::get(IntegerType::get(context, 8), sizeInBytes); if (krnlGlobalOp.value().getValue().isa<OpaqueElementsAttr>()) { // LLVM::GlobalOp does not support OpaqueElementsAttr. // Both StringAttr and OpaqueElementsAttr use StringRef for internal // data array. Thus, it looks safe to use StringAtrr instead of // OpaqueElementsAttr. StringRef data = krnlGlobalOp.value() .getValue() .cast<OpaqueElementsAttr>() .getValue(); // Check data size. assert(((int64_t)data.size() == sizeInBytes) && "Data size mismatch."); StringAttr llvmStringAttr = StringAttr::get(context, data); global = rewriter.create<LLVM::GlobalOp>(loc, llvmArrayI8Ty, /*isConstant=*/true, LLVM::Linkage::Internal, name, llvmStringAttr); } else if (krnlGlobalOp.value().getValue().isa<DenseElementsAttr>()) { DenseElementsAttr denseAttr = krnlGlobalOp.value().getValue().cast<DenseElementsAttr>(); if ((!denseAttr.isSplat()) && (sizeInBytes > 1024)) { std::vector<char> rawData = denseAttr.getRawData(); // Check data size. assert(((int64_t)rawData.size() == sizeInBytes) && "Data size mismatch."); StringRef data = StringRef((char *)rawData.data(), rawData.size()); StringAttr llvmStringAttr = StringAttr::get(context, data); global = rewriter.create<LLVM::GlobalOp>(loc, llvmArrayI8Ty, /*isConstant=*/true, LLVM::Linkage::Internal, name, llvmStringAttr); } else { global = rewriter.create<LLVM::GlobalOp>(loc, llvmGlobalType, /*isConstant=*/true, LLVM::Linkage::Internal, name, krnlGlobalOp.value().getValue()); } } else llvm_unreachable("Unsupported attribute type"); } // Set alignment if alignment != 0. if (alignmentAttr && alignmentAttr.getValue().getSExtValue() != 0) { global.alignmentAttr(alignmentAttr); } // Prepare data to be inserted into MemRef. Value globalValue = rewriter.create<LLVM::AddressOfOp>(loc, global); auto globalPtrType = LLVM::LLVMPointerType::get(constantElementType.cast<Type>()); // Bitcast the global to the MemRefType's element type. Value localValue = rewriter.create<LLVM::BitcastOp>(loc, globalPtrType, globalValue); // Create llvm MemRef from original MemRef and fill the data pointers. auto llvmMemRef = MemRefDescriptor::fromStaticShape( rewriter, loc, *getTypeConverter(), memRefTy, localValue); rewriter.replaceOp(op, {llvmMemRef}); return success(); } private: static int64_t ArrayAttrIntVal(ArrayAttr a, int i) { return (a.getValue()[i]).cast<IntegerAttr>().getInt(); } // Copied from lib/Conversion/StandardToLLVM/StandardToLLVM.cpp // Returns 'input' aligned up to 'alignment'. Computes // bumped = input + alignement - 1 // aligned = bumped - bumped % alignment static Value createAligned(ConversionPatternRewriter &rewriter, Location loc, Value input, Value alignment) { Value one = rewriter.create<LLVM::ConstantOp>(loc, alignment.getType(), rewriter.getIntegerAttr(rewriter.getIndexType(), 1)); Value bump = rewriter.create<LLVM::SubOp>(loc, alignment, one); Value bumped = rewriter.create<LLVM::AddOp>(loc, input, bump); Value mod = rewriter.create<LLVM::URemOp>(loc, bumped, alignment); return rewriter.create<LLVM::SubOp>(loc, bumped, mod); } }; class KrnlInstrumentOpLowering : public ConversionPattern { public: explicit KrnlInstrumentOpLowering(MLIRContext *context) : ConversionPattern(KrnlInstrumentOp::getOperationName(), 1, context) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto *context = op->getContext(); KrnlInstrumentOpAdaptor operandAdaptor(operands); auto loc = op->getLoc(); KrnlInstrumentOp instrumentOp = llvm::dyn_cast<KrnlInstrumentOp>(op); // Get a symbol reference to the memcpy function, inserting it if necessary. ModuleOp parentModule = op->getParentOfType<ModuleOp>(); // auto llvmVoidTy = LLVM::LLVMVoidType::get(context); // auto llvmI8PtrTy = LLVM::LLVMPointerType::get(IntegerType::get(context, // 8)); // auto llvmI64Ty = IntegerType::get(context, 64); auto llvmFnType = // LLVM::LLVMFunctionType::get( // llvmVoidTy, ArrayRef<mlir::Type>({llvmI64Ty, llvmI64Ty}), false); auto instrumentRef = getOrInsertInstrument(rewriter, parentModule); Value nodeName = rewriter.create<LLVM::ConstantOp>(loc, IntegerType::get(context, 64), rewriter.getIntegerAttr( rewriter.getIntegerType(64), instrumentOp.opID())); Value tag = rewriter.create<LLVM::ConstantOp>(loc, IntegerType::get(context, 64), rewriter.getIntegerAttr( rewriter.getIntegerType(64), instrumentOp.tag())); // StringRef txt = instrumentOp->op_name(); // Value nodeName = rewriter.create<LLVM::ConstantOp>(loc, llvmI8PtrTy, // instrumentOp->op_name()); rewriter.create<CallOp>(loc, instrumentRef, ArrayRef<Type>({}), ArrayRef<Value>({nodeName, tag})); rewriter.eraseOp(op); return success(); } }; //===----------------------------------------------------------------------===// // KRNL to LLVM: KrnlMemcpyOpLowering //===----------------------------------------------------------------------===// class KrnlMemcpyOpLowering : public ConversionPattern { public: explicit KrnlMemcpyOpLowering(MLIRContext *context) : ConversionPattern(KrnlMemcpyOp::getOperationName(), 1, context) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto *context = op->getContext(); KrnlMemcpyOpAdaptor operandAdaptor(operands); auto loc = op->getLoc(); // Get a symbol reference to the memcpy function, inserting it if necessary. ModuleOp parentModule = op->getParentOfType<ModuleOp>(); auto memcpyRef = getOrInsertMemcpy(rewriter, parentModule); // First operand. Type dstType = operandAdaptor.dest() .getType() .cast<LLVM::LLVMStructType>() .getBody()[1]; Value alignedDstMemory = rewriter.create<LLVM::ExtractValueOp>( loc, dstType, operandAdaptor.dest(), rewriter.getI64ArrayAttr(1)); Value alignedInt8PtrDstMemory = rewriter.create<LLVM::BitcastOp>(loc, LLVM::LLVMPointerType::get(IntegerType::get(context, 8)), alignedDstMemory); // Second operand. Type srcType = operandAdaptor.src() .getType() .cast<LLVM::LLVMStructType>() .getBody()[1]; Value alignedSrcMemory = rewriter.create<LLVM::ExtractValueOp>( loc, srcType, operandAdaptor.src(), rewriter.getI64ArrayAttr(1)); Value alignedInt8PtrSrcMemory = rewriter.create<LLVM::BitcastOp>(loc, LLVM::LLVMPointerType::get(IntegerType::get(context, 8)), alignedSrcMemory); // Size. Value int64Size = rewriter.create<LLVM::SExtOp>( loc, IntegerType::get(context, 64), operandAdaptor.size()); // Is volatile (set to false). Value isVolatile = rewriter.create<LLVM::ConstantOp>(loc, IntegerType::get(context, 1), rewriter.getIntegerAttr(rewriter.getIntegerType(1), 0)); // Memcpy call rewriter.create<CallOp>(loc, memcpyRef, ArrayRef<Type>({}), ArrayRef<Value>({alignedInt8PtrDstMemory, alignedInt8PtrSrcMemory, int64Size, isVolatile})); rewriter.eraseOp(op); return success(); } }; //===----------------------------------------------------------------------===// // KRNL to LLVM: KrnlUnaryMathOpLowering //===----------------------------------------------------------------------===// template <typename Op> struct MathFunctionName { static std::string functionName() { return "none"; }; }; template <> struct MathFunctionName<KrnlErfOp> { static std::string functionName(mlir::Type type) { if (type.isF32()) return "erff"; if (type.isF64()) return "erf"; llvm_unreachable("Currently unsupported type for erf"); } }; template <> struct MathFunctionName<KrnlAcosOp> { static std::string functionName(mlir::Type type) { if (type.isF32()) return "acosf"; if (type.isF64()) return "acos"; llvm_unreachable("Unsupported type for acos"); } }; template <> struct MathFunctionName<KrnlAcoshOp> { static std::string functionName(mlir::Type type) { if (type.isF32()) return "acoshf"; if (type.isF64()) return "acosh"; llvm_unreachable("Unsupported type for acosh"); } }; template <> struct MathFunctionName<KrnlAsinOp> { static std::string functionName(mlir::Type type) { if (type.isF32()) return "asinf"; if (type.isF64()) return "asin"; llvm_unreachable("Unsupported type for asin"); } }; template <> struct MathFunctionName<KrnlAsinhOp> { static std::string functionName(mlir::Type type) { if (type.isF32()) return "asinhf"; if (type.isF64()) return "asinh"; llvm_unreachable("Unsupported type for asinh"); } }; template <> struct MathFunctionName<KrnlAtanOp> { static std::string functionName(mlir::Type type) { if (type.isF32()) return "atanf"; if (type.isF64()) return "atan"; llvm_unreachable("Unsupported type for atan"); } }; template <> struct MathFunctionName<KrnlTanOp> { static std::string functionName(mlir::Type type) { if (type.isF32()) return "tanf"; if (type.isF64()) return "tan"; llvm_unreachable("Unsupported type for tan"); } }; template <> struct MathFunctionName<KrnlAtanhOp> { static std::string functionName(mlir::Type type) { if (type.isF32()) return "atanhf"; if (type.isF64()) return "atanh"; llvm_unreachable("Unsupported type for atanh"); } }; template <typename KrnlScalarMathOp> class KrnlUnaryMathOpLowering : public ConversionPattern { public: explicit KrnlUnaryMathOpLowering(MLIRContext *context) : ConversionPattern(KrnlScalarMathOp::getOperationName(), 1, context) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto *context = op->getContext(); auto loc = op->getLoc(); // get the LLVM type for the function args and result mlir::Type inType = op->getOperand(0).getType(); mlir::Type llvmType; if (inType.isF32()) llvmType = FloatType::getF32(context); else if (inType.isF64()) llvmType = FloatType::getF64(context); // Insert and/or get reference to elementary math function declaration. assert( inType.isIntOrFloat() && "Type for math function must be int or float"); ModuleOp parentModule = op->getParentOfType<ModuleOp>(); auto mathFunctionRef = getOrInsertUnaryMathFunction(rewriter, parentModule, MathFunctionName<KrnlScalarMathOp>().functionName(inType), llvmType); // Emit function call. auto funcCall = rewriter.create<CallOp>( loc, mathFunctionRef, llvmType, ArrayRef<Value>({operands[0]})); rewriter.replaceOp(op, funcCall.getResults()[0]); return success(); } }; //===----------------------------------------------------------------------===// // KRNL to LLVM: KrnlEntryPointOp //===----------------------------------------------------------------------===// class KrnlEntryPointOpLowering : public OpRewritePattern<KrnlEntryPointOp> { public: using OpRewritePattern<KrnlEntryPointOp>::OpRewritePattern; enum class API { CREATE_OMTENSOR_LIST, CREATE_OMTENSOR, GET_DATA, SET_DATA, GET_DATA_SHAPE, GET_DATA_STRIDES, SET_DATA_TYPE, GET_DATA_TYPE, GET_OMT_ARRAY, }; struct ApiSpec { API id; std::string name; FlatSymbolRefAttr symbolRef; Type outputTy; SmallVector<Type, 4> inputTys; ApiSpec( API id, const std::string &name, Type outputTy, ArrayRef<Type> inputTys) : id(id), name(name), outputTy(outputTy), inputTys(inputTys.begin(), inputTys.end()) {} Type funcTy() { return LLVM::LLVMFunctionType::get(outputTy, inputTys, /*isVarArg=*/false); } }; static void genSignatureFunction(PatternRewriter &rewriter, MLIRContext *context, std::string funcName, LLVM::GlobalOp sigvar, Location loc) { auto opaquePtrTy = LLVM::LLVMPointerType::get(IntegerType::get(context, 8)); llvm::SmallVector<Type, 1> outputsType{opaquePtrTy}; auto funcType = rewriter.getFunctionType(llvm::None, outputsType); llvm::SmallVector<NamedAttribute, 1> attrs; auto funcOp = rewriter.create<FuncOp>( UnknownLoc::get(context), funcName, funcType, attrs); auto entryBlock = funcOp.addEntryBlock(); OpBuilder::InsertionGuard guard(rewriter); rewriter.setInsertionPointToStart(entryBlock); auto sigAddr = rewriter.create<LLVM::AddressOfOp>(loc, sigvar); auto sigVoidPtr = rewriter.create<LLVM::BitcastOp>(loc, opaquePtrTy, sigAddr); llvm::SmallVector<Value, 1> results = {sigVoidPtr}; rewriter.create<ReturnOp>(UnknownLoc::get(context), results); } LogicalResult matchAndRewrite( KrnlEntryPointOp op, PatternRewriter &rewriter) const override { auto module = op->getParentOfType<ModuleOp>(); auto *context = module.getContext(); auto apiRegistry = RegisterAllApis(module, rewriter); auto loc = op.getLoc(); auto numOutputs = op->getAttrOfType<IntegerAttr>( KrnlEntryPointOp::getNumOutputsAttrName()) .getInt(); auto sigAttr = op->getAttrOfType<StringAttr>(KrnlEntryPointOp::getSignatureAttrName()); auto signature = sigAttr.getValue(); auto opaquePtrTy = LLVM::LLVMPointerType::get(IntegerType::get(context, 8)); auto int32Ty = IntegerType::get(context, 32); auto int64Ty = IntegerType::get(context, 64); // create global to hold signature auto splitSig = signature.split('@'); llvm::StringRef inSig = splitSig.first; llvm::StringRef outSig = splitSig.second; mlir::StringAttr inSigAttr = mlir::StringAttr::get(context, inSig); mlir::StringAttr outSigAttr = mlir::StringAttr::get(context, outSig); auto inSigArrayType = LLVM::LLVMArrayType::get(IntegerType::get(context, 8), inSig.size()); auto insig = rewriter.create<LLVM::GlobalOp>(loc, inSigArrayType, /*isConstant=*/true, LLVM::Linkage::External, "_in_signature", inSigAttr); auto outSigArrayType = LLVM::LLVMArrayType::get(IntegerType::get(context, 8), outSig.size()); auto outsig = rewriter.create<LLVM::GlobalOp>(loc, outSigArrayType, /*isConstant=*/true, LLVM::Linkage::External, "_out_signature", outSigAttr); genSignatureFunction(rewriter, context, "omInputSignature", insig, loc); genSignatureFunction(rewriter, context, "omOutputSignature", outsig, loc); // Rewrite Krnl Entry Point Operation to an LLVM function with a dynamic // signature. The signature is dynamic because it remains the same no matter // what the model input/output schema look like. Such dynamic signature // takes a opaque ptr as input, representing a ptr to a data structure // containing a set of dynamic memrefs wrapped in a vector; similarly the // output is also a opaque ptr to a data structure with output memrefs // wrapped within it. auto staticEntryPointFuncName = op->getAttrOfType<SymbolRefAttr>( KrnlEntryPointOp::getEntryPointFuncAttrName()) .getLeafReference() .getValue(); auto dynEntryPointName = "run_" + staticEntryPointFuncName; assert(module.lookupSymbol(dynEntryPointName.str()) == nullptr && "dynamic entry point name is not unique"); rewriter.eraseOp(op); auto dynEntryPointFuncTy = LLVM::LLVMFunctionType::get(opaquePtrTy, {opaquePtrTy}, false); auto dynamicEntryPointFunc = rewriter.create<LLVM::LLVMFuncOp>( loc, dynEntryPointName.str(), dynEntryPointFuncTy); auto &entryPointEntryBlock = createEntryBlock(dynEntryPointFuncTy, dynamicEntryPointFunc); rewriter.setInsertionPointToStart(&entryPointEntryBlock); // Based on the static entry point type signature, unpack dynamic memory // refs to corresponding static memory refs. auto wrappedStaticEntryPointFuncName = "_mlir_ciface_" + staticEntryPointFuncName.lower(); auto *staticEntryPointFunc = module.lookupSymbol(wrappedStaticEntryPointFuncName); assert(staticEntryPointFunc && isa<LLVM::LLVMFuncOp>(staticEntryPointFunc) && "entry point func must exist and be an llvm func op"); auto staticEntryPointTy = dyn_cast<LLVM::LLVMFuncOp>(staticEntryPointFunc) .getType() .dyn_cast<LLVM::LLVMFunctionType>(); // Retrieve dynamic mem refs from wrapped input, and convert every one of // them to static mem refs. SmallVector<Value, 4> staticInputs; auto wrappedInput = entryPointEntryBlock.getArgument(0); auto omTensorPtrArr = callApi(rewriter, loc, apiRegistry, API::GET_OMT_ARRAY, {wrappedInput}); auto one = rewriter.create<LLVM::ConstantOp>( loc, int32Ty, rewriter.getI32IntegerAttr(1)); // Create a memref type for the return argument of the iface call auto memRefOutPtrTy = staticEntryPointTy.getParamType(0); Value ptrToOutMemRef = rewriter.create<LLVM::AllocaOp>(loc, memRefOutPtrTy, one, /*alignment=*/0); staticInputs.emplace_back(ptrToOutMemRef); // Start with param 1 because 0 is the return value for (size_t i = 1; i < staticEntryPointTy.getNumParams(); i++) { // Call API function to retrieve the i-th dynamic memref. auto idxVal = rewriter.create<LLVM::ConstantOp>( loc, int32Ty, rewriter.getI32IntegerAttr(i - 1)); auto omTensorPtrAddrTy = LLVM::LLVMPointerType::get(opaquePtrTy); auto omTensorPtrAddr = rewriter .create<LLVM::GEPOp>(loc, omTensorPtrAddrTy, omTensorPtrArr, ArrayRef<Value>({idxVal})) .getResult(); auto omTensorPtr = rewriter.create<LLVM::LoadOp>(loc, opaquePtrTy, omTensorPtrAddr) .getResult(); // Create a (static) memref type corresponding to the i-th memref input to // the inference function on stack, and load it to memRef. auto memRefPtrTy = staticEntryPointTy.getParamType(i); Value ptrToMemRef = rewriter.create<LLVM::AllocaOp>(loc, memRefPtrTy, one, /*alignment=*/0); // Fill in the memref underlying ptrToMemRef with information extracted // from omTensorPtr. fillPtrToMemRefWithOMTensor( omTensorPtr, ptrToMemRef, rewriter, loc, apiRegistry, module); // ptrToMemRef will be an input to main computation graph function. staticInputs.emplace_back(ptrToMemRef); } // Call static entry point with the memref ptrs created, and get output. rewriter.create<LLVM::CallOp>( loc, ArrayRef<Type>({}), wrappedStaticEntryPointFuncName, staticInputs); auto outMemRefs = rewriter.create<LLVM::LoadOp>(loc, ptrToOutMemRef); auto outMemRefsType = outMemRefs.getType().dyn_cast<LLVM::LLVMStructType>(); std::vector<mlir::Value> outMemRefList; if (numOutputs == 1) { // If only one output tensor exists, the tensor's corresponding memref // descriptor will be returned as is. outMemRefList.emplace_back(outMemRefs); } else { // Otherwise, if multiple tensors are to be returned, the returned value // is a struct. Multiple tensors' memref descriptors are packed into the // same struct. So we unpack them iteratively to outMemRefList. for (int i = 0; i < numOutputs; i++) { auto position = rewriter.getArrayAttr({rewriter.getI64IntegerAttr(i)}); auto type = outMemRefsType.getBody()[i]; auto extractOp = rewriter.create<LLVM::ExtractValueOp>(loc, /*res=*/type, /*type=*/outMemRefs, /*position=*/position); outMemRefList.emplace_back(extractOp.getResult()); } } auto numOutput = rewriter.create<LLVM::ConstantOp>( loc, int32Ty, rewriter.getI64IntegerAttr(outMemRefList.size())); auto mallocSym = getOrInsertMalloc(rewriter, module); // TODO(tjingrant): get pointer size from data layout. size_t kPtrSize = 8; auto outputOmtPtrsArraySizeInByte = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, rewriter.getI64IntegerAttr(outMemRefList.size() * kPtrSize)); auto outOmtPtrsArr = rewriter .create<LLVM::CallOp>(loc, LLVM::LLVMPointerType::get( IntegerType::get(module.getContext(), 8)), mallocSym, ArrayRef<Value>(outputOmtPtrsArraySizeInByte)) .getResult(0); outOmtPtrsArr = rewriter .create<LLVM::BitcastOp>(loc, LLVM::LLVMPointerType::get( LLVM::LLVMPointerType::get( IntegerType::get(module.getContext(), 8)), 0), outOmtPtrsArr) .getResult(); for (unsigned int i = 0; i < outMemRefList.size(); i++) { // Get the i-th memref returned, convert to a dynamic memref and store it // in the wrappedOutput. auto memRef = outMemRefList.at(i); auto outMemRefTy = memRef.getType().dyn_cast<LLVM::LLVMStructType>(); auto outMemRefRank = getRankFromMemRefType(outMemRefTy); auto outMemRefRankVal = rewriter.create<LLVM::ConstantOp>( loc, int64Ty, rewriter.getI64IntegerAttr(outMemRefRank)); auto outOMTensor = callApi( rewriter, loc, apiRegistry, API::CREATE_OMTENSOR, {outMemRefRankVal}); fillOMTensorWithMemRef( memRef, outOMTensor, rewriter, loc, apiRegistry, module); auto idxVal = rewriter.create<LLVM::ConstantOp>( loc, int32Ty, rewriter.getI32IntegerAttr(i)); auto omTensorPtrAddrTy = LLVM::LLVMPointerType::get(opaquePtrTy); auto omTensorPtrAddr = rewriter .create<LLVM::GEPOp>(loc, omTensorPtrAddrTy, outOmtPtrsArr, ArrayRef<Value>{idxVal}) .getResult(); rewriter.create<LLVM::StoreOp>(loc, outOMTensor, omTensorPtrAddr); } // Create wrapped output. auto wrappedOutput = callApi(rewriter, loc, apiRegistry, API::CREATE_OMTENSOR_LIST, {outOmtPtrsArr, numOutput, one}); // Return wrapped output. rewriter.create<LLVM::ReturnOp>( loc, SmallVector<Value, 1>(1, wrappedOutput)); return success(); } private: using ApiRegistry = std::map<API, ApiSpec>; ApiRegistry RegisterAllApis( ModuleOp &module, PatternRewriter &rewriter) const { auto *context = module.getContext(); auto voidTy = LLVM::LLVMVoidType::get(context); auto opaquePtrTy = LLVM::LLVMPointerType::get(IntegerType::get(context, 8)); auto opaquePtrPtrTy = LLVM::LLVMPointerType::get(opaquePtrTy); auto int32Ty = IntegerType::get(context, 32); auto int64Ty = IntegerType::get(context, 64); auto int64PtrTy = LLVM::LLVMPointerType::get(int64Ty); // Declare API type as an enum value, its string name and an LLVM Type // specifying its signature. // clang-format off std::vector<ApiSpec> apiSpecs = { ApiSpec(API::CREATE_OMTENSOR_LIST, "omTensorListCreateWithOwnership", opaquePtrTy, {opaquePtrPtrTy, int32Ty, int32Ty}), ApiSpec(API::CREATE_OMTENSOR, "omTensorCreateEmptyDeprecated", opaquePtrTy, {int64Ty}), ApiSpec(API::GET_DATA, "omTensorGetDataPtr", opaquePtrTy, {opaquePtrTy}), ApiSpec(API::SET_DATA, "omTensorSetDataPtr", voidTy, {opaquePtrTy, int32Ty, opaquePtrTy, opaquePtrTy}), ApiSpec(API::GET_DATA_SHAPE, "omTensorGetShape", int64PtrTy, {opaquePtrTy}), ApiSpec(API::GET_DATA_STRIDES, "omTensorGetStrides", int64PtrTy, {opaquePtrTy}), ApiSpec(API::GET_DATA_TYPE, "omTensorGetDataType", int32Ty, {opaquePtrTy}), ApiSpec(API::SET_DATA_TYPE, "omTensorSetDataType", voidTy, {opaquePtrTy, int32Ty}), ApiSpec(API::GET_OMT_ARRAY, "omTensorListGetOmtArray", opaquePtrPtrTy, {opaquePtrTy}), }; // clang-format on // Declare APIs in the current module and build an API registry mapping api // identities to a symbol reference to the API function. ApiRegistry registry; for (auto &apiSpec : apiSpecs) { apiSpec.symbolRef = getOrInsertExternFunc( apiSpec.name, module, apiSpec.funcTy(), rewriter); registry.emplace(apiSpec.id, apiSpec); } return registry; } // Call a registered API, return the return SSA values if only one result is // returned, otherwise return nullptr. Value callApi(PatternRewriter &rewriter, Location loc, ApiRegistry registry, API apiId, ArrayRef<Value> params) const { // To be used as parameters in LLVM::CallOp, voidTy must be converted // to empty list to avoid emission of an SSA value with voidTy. However, // we still keep using LLVM voidTy (as opposed to empty list) when recording // API function signatures in API registry because when declaring API // functions in LLVM IR, the correct way to indicate an output type for // "void" is still LLVM voidTy. Relevant discussion thread: // https://github.com/onnx/onnx-mlir/issues/255. SmallVector<Type, 1> outputTys; auto outputTy = registry.at(apiId).outputTy; if (!outputTy.isa<LLVM::LLVMVoidType>()) outputTys.emplace_back(outputTy); auto returnVals = rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>(outputTys), registry.at(apiId).symbolRef, ArrayRef<Value>(params)); if (returnVals.getNumResults() == 1) return returnVals.getResult(0); return nullptr; } // Helper function to insert an entry block to LLVM function. // (TODO): upstream this to MLIR. Block &createEntryBlock( Type &dynEntryPoint, LLVM::LLVMFuncOp &dynamicEntryPointFunc) const { // Add entry block: auto *entryPointEntryBlock = new Block(); auto dynEntryPointFuncType = dynEntryPoint.cast<LLVM::LLVMFunctionType>(); dynamicEntryPointFunc.push_back(entryPointEntryBlock); llvm::SmallVector<Type, 4> argTypes; for (size_t i = 0; i < dynEntryPointFuncType.getNumParams(); i++) argTypes.emplace_back(dynEntryPointFuncType.getParamType(i)); entryPointEntryBlock->addArguments(argTypes); return *entryPointEntryBlock; } void fillPtrToMemRefWithOMTensor(Value &rtMemRef, Value &ptrToMemRef, PatternRewriter &rewriter, const Location &loc, const std::map<API, ApiSpec> &apiRegistry, ModuleOp &module) const { auto *context = module.getContext(); auto memRefPtrTy = ptrToMemRef.getType().dyn_cast<LLVM::LLVMPointerType>(); auto memRefTy = memRefPtrTy.getElementType(); auto int64Ty = IntegerType::get(context, 64); Value memRef = rewriter.create<LLVM::UndefOp>(loc, memRefTy); // Set dataPtr and alignedDataPtr; auto dataPtr = callApi(rewriter, loc, apiRegistry, API::GET_DATA, {rtMemRef}); dataPtr = rewriter.create<LLVM::BitcastOp>( loc, memRefTy.cast<LLVM::LLVMStructType>().getBody()[0], dataPtr); memRef = rewriter.create<LLVM::InsertValueOp>(loc, memRefTy, memRef, dataPtr, rewriter.getArrayAttr({rewriter.getI32IntegerAttr(0)})); memRef = rewriter.create<LLVM::InsertValueOp>(loc, memRefTy, memRef, dataPtr, rewriter.getArrayAttr({rewriter.getI32IntegerAttr(1)})); // Use zero offset now. auto zero = rewriter.create<LLVM::ConstantOp>( loc, int64Ty, rewriter.getI64IntegerAttr(0)); memRef = rewriter.create<LLVM::InsertValueOp>(loc, memRefTy, memRef, zero, rewriter.getArrayAttr({rewriter.getI32IntegerAttr(2)})); // Get rank, sizes array ptr and strides array ptr. auto rank = getRankFromMemRefType(memRefTy.cast<LLVM::LLVMStructType>()); auto sizesArrayPtr = callApi(rewriter, loc, apiRegistry, API::GET_DATA_SHAPE, {rtMemRef}); auto stridesArrayPtr = callApi(rewriter, loc, apiRegistry, API::GET_DATA_STRIDES, {rtMemRef}); for (decltype(rank) i = 0; i < rank; i++) { auto dimIdx = rewriter.create<LLVM::ConstantOp>( loc, int64Ty, rewriter.getI64IntegerAttr(i)); // Insert size of the dimension. auto dimSizePtr = rewriter.create<LLVM::GEPOp>(loc, LLVM::LLVMPointerType::get(int64Ty), sizesArrayPtr, ArrayRef<Value>({dimIdx})); auto dimSizeLoad = rewriter.create<LLVM::LoadOp>( loc, LLVM::LLVMPointerType::get(int64Ty), dimSizePtr); Value dimSize = rewriter.create<LLVM::PtrToIntOp>(loc, int64Ty, dimSizeLoad); memRef = rewriter.create<LLVM::InsertValueOp>(loc, memRefTy, memRef, dimSize, rewriter.getArrayAttr( {rewriter.getI64IntegerAttr(3), rewriter.getI64IntegerAttr(i)})); // Insert stride of the dimension. auto dimStridePtr = rewriter.create<LLVM::GEPOp>(loc, LLVM::LLVMPointerType::get(int64Ty), stridesArrayPtr, ArrayRef<Value>({dimIdx})); auto dimStrideLoad = rewriter.create<LLVM::LoadOp>( loc, LLVM::LLVMPointerType::get(int64Ty), dimStridePtr); Value dimStride = rewriter.create<LLVM::PtrToIntOp>(loc, int64Ty, dimStrideLoad); memRef = rewriter.create<LLVM::InsertValueOp>(loc, memRefTy, memRef, dimStride, rewriter.getArrayAttr( {rewriter.getI64IntegerAttr(4), rewriter.getI64IntegerAttr(i)})); } rewriter.create<LLVM::StoreOp>(loc, memRef, ptrToMemRef); } void fillOMTensorWithMemRef(Value &outMemRef, Value &outOMTensor, PatternRewriter &rewriter, const Location &loc, const std::map<API, ApiSpec> &apiRegistry, ModuleOp &module) const { auto *context = module.getContext(); auto outMemRefTy = outMemRef.getType().dyn_cast<LLVM::LLVMStructType>(); auto int64Ty = IntegerType::get(context, 64); auto int32Ty = IntegerType::get(context, 32); // Set ownership to true, i.e., free after OMTensor is destroyed. Value owning = rewriter.create<LLVM::ConstantOp>( loc, int32Ty, rewriter.getI32IntegerAttr(1)); // Extract the allocated pointer. Value outMemRefAllocatedPtr = rewriter.create<LLVM::ExtractValueOp>(loc, outMemRefTy.getBody()[0], outMemRef, rewriter.getArrayAttr({rewriter.getI64IntegerAttr(0)})); outMemRefAllocatedPtr = rewriter.create<LLVM::BitcastOp>(loc, LLVM::LLVMPointerType::get(IntegerType::get(context, 8)), outMemRefAllocatedPtr); // Extract the aligned pointer. Value outMemRefAlignedPtr = rewriter.create<LLVM::ExtractValueOp>(loc, outMemRefTy.getBody()[1], outMemRef, rewriter.getArrayAttr({rewriter.getI64IntegerAttr(1)})); outMemRefAlignedPtr = rewriter.create<LLVM::BitcastOp>(loc, LLVM::LLVMPointerType::get(IntegerType::get(context, 8)), outMemRefAlignedPtr); // Set ownership, allocated and aligned pointer. callApi(rewriter, loc, apiRegistry, API::SET_DATA, {outOMTensor, owning, outMemRefAllocatedPtr, outMemRefAlignedPtr}); auto elemTy = outMemRefTy.getBody()[0].cast<LLVM::LLVMPointerType>().getElementType(); auto onnxTy = llvmTypeToOnnxType(elemTy); auto onnxTyVal = rewriter.create<LLVM::ConstantOp>( loc, int32Ty, rewriter.getI32IntegerAttr(onnxTy)); callApi(rewriter, loc, apiRegistry, API::SET_DATA_TYPE, {outOMTensor, onnxTyVal}); auto rank = getRankFromMemRefType(outMemRefTy); auto sizesArrayPtr = callApi(rewriter, loc, apiRegistry, API::GET_DATA_SHAPE, {outOMTensor}); auto stridesArrayPtr = callApi( rewriter, loc, apiRegistry, API::GET_DATA_STRIDES, {outOMTensor}); for (decltype(rank) i = 0; i < rank; i++) { auto dimIdx = rewriter.create<LLVM::ConstantOp>( loc, int64Ty, rewriter.getI64IntegerAttr(i)); // Transfer size of dimension from memref to dynamic memref. auto dimSize = rewriter.create<LLVM::ExtractValueOp>(loc, int64Ty, outMemRef, rewriter.getArrayAttr( {rewriter.getI64IntegerAttr(3), rewriter.getI64IntegerAttr(i)})); auto dimSizePtr = rewriter.create<LLVM::GEPOp>(loc, LLVM::LLVMPointerType::get(int64Ty), sizesArrayPtr, ArrayRef<Value>({dimIdx})); rewriter.create<LLVM::StoreOp>(loc, dimSize, dimSizePtr); // Transfer stride of dimension from memref to dynamic memref. auto dimStride = rewriter.create<LLVM::ExtractValueOp>(loc, int64Ty, outMemRef, rewriter.getArrayAttr( {rewriter.getI64IntegerAttr(4), rewriter.getI64IntegerAttr(i)})); auto dimStridePtr = rewriter.create<LLVM::GEPOp>(loc, LLVM::LLVMPointerType::get(int64Ty), stridesArrayPtr, ArrayRef<Value>({dimIdx})); rewriter.create<LLVM::StoreOp>(loc, dimStride, dimStridePtr); } } }; //===----------------------------------------------------------------------===// // KRNL to LLVM: KrnlVectorTypeCastOpLowering //===----------------------------------------------------------------------===// // struct KrnlVectorTypeCastOpLowering // : public ConvertOpToLLVMPattern<KrnlVectorTypeCastOp> { // using ConvertOpToLLVMPattern<KrnlVectorTypeCastOp>::ConvertOpToLLVMPattern; class KrnlVectorTypeCastOpLowering : public ConvertToLLVMPattern { public: explicit KrnlVectorTypeCastOpLowering( MLIRContext *context, LLVMTypeConverter &lowering_) : ConvertToLLVMPattern( KrnlVectorTypeCastOp::getOperationName(), context, lowering_) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto krnlVectorTypeCastOp = cast<KrnlVectorTypeCastOp>(op); MemRefType sourceType = krnlVectorTypeCastOp.getOperand().getType().cast<MemRefType>(); MemRefType targetType = krnlVectorTypeCastOp.getType(); if (!isSupportedMemRefType(targetType) || !isSupportedMemRefType(sourceType)) return failure(); KrnlVectorTypeCastOp::Adaptor transformed(operands); MemRefDescriptor srcMemRefDesc(transformed.source()); Type targetStructType = typeConverter->convertType(krnlVectorTypeCastOp.getType()); if (!targetStructType) return failure(); Location loc = op->getLoc(); // Get memRefDescriptor, the new memref descriptor. MemRefDescriptor memRefDescriptor = MemRefDescriptor::undef(rewriter, loc, targetStructType); auto targetElementPtrType = memRefDescriptor.getElementPtrType(); // Set the new memref to the same buffer as the source memref. Value srcBuffer = srcMemRefDesc.allocatedPtr(rewriter, loc); Value targetBuffer = rewriter.create<LLVM::BitcastOp>( loc, targetElementPtrType, ArrayRef<Value>(srcBuffer)); memRefDescriptor.setAllocatedPtr(rewriter, loc, targetBuffer); // Set the new memref alignment to the same value as source memref. Value srcBufferAligned = srcMemRefDesc.alignedPtr(rewriter, loc); Value targetBufAligned = rewriter.create<LLVM::BitcastOp>( loc, targetElementPtrType, ArrayRef<Value>(srcBufferAligned)); memRefDescriptor.setAlignedPtr(rewriter, loc, targetBufAligned); int64_t offset; SmallVector<int64_t, 4> strides; if (failed(getStridesAndOffset(targetType, strides, offset))) return failure(); // Unhandled dynamic offset. if (offset == MemRefType::getDynamicStrideOrOffset()) return failure(); memRefDescriptor.setOffset( rewriter, loc, createIndexConstant(rewriter, loc, offset)); // Get the sizes of the memref: all but the last one are copied from the // source memref. If the dimension size was static, the target memref would // have the same size. SmallVector<Value, 4> sizes; sizes.reserve(targetType.getRank()); for (unsigned pos = 0, e = targetType.getRank() - 1; pos < e; ++pos) { int64_t dimSize = targetType.getDimSize(pos); if (dimSize == MemRefType::kDynamicSize) sizes.push_back(srcMemRefDesc.size(rewriter, loc, pos)); else sizes.push_back(createIndexConstant(rewriter, loc, dimSize)); } if (targetType.getShape().back() != MemRefType::kDynamicSize) { // The op is already verified to have the right size for the last // dimension. sizes.push_back( createIndexConstant(rewriter, loc, targetType.getShape().back())); } else { // We need to divide the dynamic size on the source by the vector width. // There is the implicit expectation that the last dimension of the // original memory is a multiple of the vector length. Value vecWidth = createIndexConstant(rewriter, loc, targetType.getElementType().cast<ShapedType>().getNumElements()); sizes.push_back(rewriter.create<LLVM::UDivOp>(loc, srcMemRefDesc.size(rewriter, loc, sourceType.getRank() - 1), vecWidth)); } assert(!sizes.empty() && "target memref rank can't be zero"); // Compute the total number of memref elements. Value cumulativeSize = sizes.front(); for (unsigned i = 1, e = sizes.size(); i < e; ++i) cumulativeSize = rewriter.create<LLVM::MulOp>( loc, getIndexType(), ArrayRef<Value>{cumulativeSize, sizes[i]}); // Calculate the strides. Value runningStride = nullptr; // Iterate strides in reverse order, compute runningStride and strideValues. unsigned nStrides = strides.size(); SmallVector<Value, 4> strideValues(nStrides, nullptr); for (auto indexedStride : llvm::enumerate(llvm::reverse(strides))) { int64_t index = nStrides - 1 - indexedStride.index(); if (strides[index] == MemRefType::getDynamicStrideOrOffset()) // Identity layout map is enforced in the match function, so we compute: // `runningStride *= sizes[index + 1]`. runningStride = runningStride ? rewriter.create<LLVM::MulOp>(loc, runningStride, sizes[index + 1]) : createIndexConstant(rewriter, loc, 1); else runningStride = createIndexConstant(rewriter, loc, strides[index]); strideValues[index] = runningStride; } // Fill size and stride descriptors in memref. for (auto indexedSize : llvm::enumerate(sizes)) { int64_t index = indexedSize.index(); memRefDescriptor.setSize(rewriter, loc, index, indexedSize.value()); memRefDescriptor.setStride(rewriter, loc, index, strideValues[index]); } rewriter.replaceOp(op, {memRefDescriptor}); return success(); } // Check if the MemRefType `type` is supported by the lowering. We currently // only support memrefs with identity maps. bool isSupportedMemRefType(MemRefType type) const { if (!typeConverter->convertType(type.getElementType())) return false; return type.getLayout().isIdentity(); } }; //===----------------------------------------------------------------------===// // KRNL to LLVM: KrnlRandomNormalOpLowering //===----------------------------------------------------------------------===// class KrnlRandomNormalOpLowering : public ConversionPattern { public: explicit KrnlRandomNormalOpLowering(MLIRContext *context) : ConversionPattern(KrnlRandomNormalOp::getOperationName(), 1, context) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { KrnlRandomNormalOpAdaptor operandAdaptor(operands); auto loc = op->getLoc(); mlir::Type inType = op->getOperand(2).getType(); // Get a symbol reference to the memcpy function, inserting it if necessary. ModuleOp parentModule = op->getParentOfType<ModuleOp>(); auto randomNormalFuncRef = getOrInsertRandomNormal(rewriter, parentModule, inType); // First operand. Type outputType = operandAdaptor.output() .getType() .cast<LLVM::LLVMStructType>() .getBody()[1]; Value alignedOutput = rewriter.create<LLVM::ExtractValueOp>( loc, outputType, operandAdaptor.output(), rewriter.getI64ArrayAttr(1)); // Memcpy call rewriter.create<CallOp>(loc, randomNormalFuncRef, ArrayRef<Type>({}), ArrayRef<Value>({alignedOutput, operandAdaptor.numberOfValues(), operandAdaptor.mean(), operandAdaptor.scale(), operandAdaptor.seed()})); rewriter.eraseOp(op); return success(); } }; } // end namespace void mlir::populateAffineAndKrnlToLLVMConversion(RewritePatternSet &patterns, MLIRContext *ctx, LLVMTypeConverter &typeConverter) { // TODO: look at what is done in // mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVMPass.cpp in function // LowerVectorToLLVMPass::runOnOperation() and see what we should do about it. // They run it in two steps, and add additional lowerings. vector::populateVectorToVectorCanonicalizationPatterns(patterns); // Removed in upgrade of LLVM: // vector::populateVectorSlicesLoweringPatterns(patterns); vector::populateVectorBroadcastLoweringPatterns(patterns); vector::populateVectorContractLoweringPatterns(patterns); vector::populateVectorTransposeLoweringPatterns(patterns); populateAffineToStdConversionPatterns(patterns); populateLoopToStdConversionPatterns(patterns); populateShapeToStandardConversionPatterns(patterns); populateVectorToLLVMMatrixConversionPatterns(typeConverter, patterns); populateVectorToLLVMConversionPatterns(typeConverter, patterns); populateVectorToLLVMMatrixConversionPatterns(typeConverter, patterns); populateStdExpandOpsPatterns(patterns); arith::populateArithmeticExpandOpsPatterns(patterns); populateMathToLLVMConversionPatterns(typeConverter, patterns); populateStdToLLVMConversionPatterns(typeConverter, patterns); populateMemRefToLLVMConversionPatterns(typeConverter, patterns); arith::populateArithmeticToLLVMConversionPatterns(typeConverter, patterns); populateReconcileUnrealizedCastsPatterns(patterns); patterns.insert<KrnlGlobalOpLowering, KrnlVectorTypeCastOpLowering>( ctx, typeConverter); patterns.insert<KrnlGetRefOpLowering>(ctx, typeConverter); patterns.insert<KrnlMemcpyOpLowering, KrnlEntryPointOpLowering>(ctx); patterns.insert<KrnlInstrumentOpLowering>(ctx); patterns.insert<KrnlRandomNormalOpLowering>(ctx); // Math library functions. patterns.insert<KrnlUnaryMathOpLowering<KrnlErfOp>>(ctx); patterns.insert<KrnlUnaryMathOpLowering<KrnlAcosOp>>(ctx); patterns.insert<KrnlUnaryMathOpLowering<KrnlAcoshOp>>(ctx); patterns.insert<KrnlUnaryMathOpLowering<KrnlAsinOp>>(ctx); patterns.insert<KrnlUnaryMathOpLowering<KrnlAsinhOp>>(ctx); patterns.insert<KrnlUnaryMathOpLowering<KrnlAtanOp>>(ctx); patterns.insert<KrnlUnaryMathOpLowering<KrnlAtanhOp>>(ctx); patterns.insert<KrnlUnaryMathOpLowering<KrnlTanOp>>(ctx); } //===----------------------------------------------------------------------===// // KRNL + Standard + Vector + Affine dialects lowering to LLVM. //===----------------------------------------------------------------------===// namespace { struct ConvertKrnlToLLVMPass : public PassWrapper<ConvertKrnlToLLVMPass, OperationPass<ModuleOp>> { StringRef getArgument() const override { return "convert-krnl-to-llvm"; } StringRef getDescription() const override { return "Lower the Krnl Affine and Std dialects to LLVM."; } void runOnOperation() final; }; } // end anonymous namespace void ConvertKrnlToLLVMPass::runOnOperation() { // Annotate ModuleOp with endian information so that LLVM global constants are // handled correctly by the other LLVM tools such as 'opt'. bool isLittleEndian = llvm::support::endian::system_endianness() == llvm::support::endianness::little; StringRef endian = isLittleEndian ? "e" : "E"; ModuleOp module = getOperation(); module->setAttr("llvm.data_layout", StringAttr::get(&getContext(), endian)); // Define the target for this lowering i.e. the LLVM dialect. ConversionTarget target(getContext()); target.addLegalDialect<LLVM::LLVMDialect>(); target.addLegalOp<ModuleOp>(); target.addIllegalOp<UnrealizedConversionCastOp>(); // Lower the MemRef types to a representation in LLVM. LowerToLLVMOptions options(&getContext()); options.emitCWrappers = true; LLVMTypeConverter typeConverter(&getContext(), options); // We have a combination of `krnl`, `affine`, `vector`, and `std` operations. // We lower in stages until all the code is in the LLVM dialect. RewritePatternSet patterns(&getContext()); populateAffineAndKrnlToLLVMConversion(patterns, &getContext(), typeConverter); // We want to completely lower to LLVM, so we use a `FullConversion`. This // ensures that only legal operations will remain after the conversion. if (failed( applyFullConversion(getOperation(), target, std::move(patterns)))) { signalPassFailure(); } } /// Create the pass for lowering `Krnl`, `Affine` and `Std` dialects to LLVM. std::unique_ptr<mlir::Pass> mlir::createConvertKrnlToLLVMPass() { return std::make_unique<ConvertKrnlToLLVMPass>(); }
%ifdef _X64_ [BITS 64] [SEGMENT .data] [EXTERN _g_VectorDelta] [EXTERN _g_PieceData] %ifdef OSX ;;; Note: The reason for this OSX stuff is that there is a bug in the mac ;;; version of nasm. See comments in data.c for more details. [GLOBAL g_NasmVectorDelta] [GLOBAL _g_NasmVectorDelta] g_NasmVectorDelta: _g_NasmVectorDelta: alignb 32, db 0 times 256 * 4 db 0 [GLOBAL g_NasmPieceData] [GLOBAL _g_NasmPieceData] g_NasmPieceData: _g_NasmPieceData: alignb 32, db 0 times 4 * 4 * 8 db 0 %else [EXTERN _g_VectorDelta] [EXTERN _g_PieceData] %endif [SEGMENT .text] %ifndef CROUTINES [GLOBAL LastBit] [GLOBAL _LastBit] ;; ;; ULONGLONG CDECL ;; LastBit(BITBOARD bb) ;; LastBit: _LastBit: int 3 bsr rax, rcx jnz .found xor rax, rax ret .found: add rax, 1 ret int 3 [GLOBAL FirstBit] [GLOBAL _FirstBit] ;; ;; ULONGLONG CDECL ;; FirstBit(BITBOARD bb) ;; FirstBit: _FirstBit: ;movq rcx, [rsp+8] bsf rax, rcx jnz .found xor rax, rax ret .found: add rax, 1 ret int 3 [GLOBAL CountBits] [GLOBAL _CountBits] ;; ;; ULONGLONG CDECL ;; CountBits(BITBOARD bb) ;; CountBits: _CountBits: xor rax, rax mov rcx, [esp+8] test rcx, rcx jz .done .again: add rax, 1 mov rdx, rcx sub rdx, 1 and rcx, rdx jnz .again .done: ret int 3 [GLOBAL GetAttacks] [GLOBAL _GetAttacks] db 43h,30h,50h,56h,72h,31h,47h,34h,54h,20h,32h,30h,30h db 36h,20h,53h,63h,30h,74h,74h,20h,47h,61h,73h,63h,34h iDelta dd -17 dd +15 %define uSide ebp+0x14 %define cSquare ebp+0x10 %define pos ebp+0xC %define pList ebp+8 ;; retaddr ebp+4 ;; old ebp ebp ;; old ebx ebp-4 ;; old esi ebp-8 ;; old edi ebp-0xC %define pOldList ebp-0x10 %define c ebp-0x14 %define x ebp-0x18 %define _cNonPawns 0x478 %define _uNonPawnCount 0x500 %define _rgSquare 0x0 ;; ;; void CDECL ;; GetAttacks(SEE_LIST *pList, ; ebp + 8 ;; POSITION *pos, ; ebp + 0xC ;; COOR cSquare, ; ebp + 0x10 ;; ULONG uSide) ; ebp + 0x14 ;; GetAttacks: _GetAttacks: int 3 %endif ; !CROUTINES [GLOBAL LockCompareExchange] [GLOBAL _LockCompareExchange] %define uComp esp+0xC %define uExch esp+8 %define pDest esp+4 ;; ;; ULONG CDECL ;; LockCompareExchange(void *dest, ; esp + 4 ;; ULONG exch, ; esp + 8 ;; ULONG comp) ; esp + C ;; LockCompareExchange: _LockCompareExchange: mov ecx, [pDest] mov edx, [uExch] mov eax, [uComp] lock cmpxchg dword [ecx], edx ret int 3 [GLOBAL LockIncrement] [GLOBAL _LockIncrement] ;; ;; ULONG CDECL ;; LockIncrement(ULONG *pDest) ;; LockIncrement: _LockIncrement: mov ecx, [pDest] mov eax, 1 lock xadd [ecx], eax add eax, 1 ret int 3 [GLOBAL LockDecrement] [GLOBAL _LockDecrement] ;; ;; ULONG CDECL ;; LockDecrement(ULONG *pDest) ;; LockDecrement: _LockDecrement: mov ecx, [pDest] mov eax, -1 lock xadd [ecx], eax add eax, -1 ret int 3 %endif ; X64
/*********************************************************************************** ** exvr-designer ** ** MIT License ** ** Copyright (c) [2018] [Florian Lance][EPFL-LNCO] ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ************************************************************************************/ #include "timeline.hpp" #include <QDebug> using namespace tool; using namespace tool::ex; bool Timeline::add_interval(const Interval &interval){ const double totalBefore = sum_intervals(); intervals.emplace_back(interval); merge(); const double totalAfter = sum_intervals(); return !almost_equal(totalBefore,totalAfter); } bool Timeline::remove_interval(const Interval &intervalToRemove){ const double totalBefore = sum_intervals(); std_v1<size_t> idToRemove; std_v1<Interval> intervalsToAdd; for(size_t ii = 0; ii < intervals.size(); ++ii){ Interval &interval = intervals[ii]; bool startInside = interval.inside(intervalToRemove.start); bool endInside = interval.inside(intervalToRemove.end); if(startInside && endInside){ intervalsToAdd.emplace_back(Interval{intervalToRemove.end, interval.end, IntervalKey{-1}}); interval.end = intervalToRemove.start; }else if(startInside){ interval.end = intervalToRemove.start; }else if(endInside){ interval.start = intervalToRemove.end; }else if(intervalToRemove.inside(interval.start) && intervalToRemove.inside(interval.end)){ idToRemove.emplace_back(ii); } } for(int ii = static_cast<int>(idToRemove.size())-1; ii >= 0; --ii){ intervals.erase(intervals.begin()+static_cast<int>(idToRemove[static_cast<size_t>(ii)])); } for(auto &i : intervalsToAdd){ intervals.emplace_back(std::move(i)); } std::sort(intervals.begin(), intervals.end(), compare_intervals); intervals.erase(std::remove_if(intervals.begin(), intervals.end(),[](Interval& i) { return (almost_equal<double>(i.length().v,0.)); // put your condition here }), intervals.end()); const double totalAfter = sum_intervals(); return !almost_equal(totalBefore,totalAfter); } void Timeline::cut(SecondsTS max){ std_v1<size_t> idToRemove; for(size_t ii = 0; ii < intervals.size(); ++ii){ Interval &interval = intervals[ii]; if(interval.inside(max)){ interval.end = max; }else if(interval.start.v > max.v){ idToRemove.emplace_back(ii); } } for(int ii = static_cast<int>(idToRemove.size())-1; ii >= 0; --ii){ intervals.erase(intervals.begin()+static_cast<int>(idToRemove[static_cast<size_t>(ii)])); } } double Timeline::sum_intervals() const{ double total = 0.; for(const auto &interval : intervals){ total += interval.length().v; } return total; } void Timeline::fill(SecondsTS length){ clean(); intervals.emplace_back(Interval{SecondsTS{0.},length, IntervalKey{-1}}); } void Timeline::clean(){ intervals.clear(); } void Timeline::merge(){ while(true){ std_v1<std::pair<size_t,size_t>> collides; for(size_t ii = 0; ii < intervals.size(); ++ii){ for(size_t jj = 0; jj < intervals.size(); ++jj){ if(ii == jj){ continue; } if(intervals[ii].collide(intervals[jj])){ // merge if collide collides.emplace_back(std::make_pair(ii,jj)); break; } } if(collides.size() > 0){ break; } } if(collides.size() == 0){ break; } Interval merged = merge_intervals(intervals[collides[0].first], intervals[collides[0].second]); if(collides[0].first < collides[0].second){ intervals.erase(intervals.begin()+static_cast<int>(collides[0].second)); intervals.erase(intervals.begin()+static_cast<int>(collides[0].first)); }else{ intervals.erase(intervals.begin()+static_cast<int>(collides[0].first)); intervals.erase(intervals.begin()+static_cast<int>(collides[0].second)); } intervals.emplace_back(merged); } std::sort(intervals.begin(), intervals.end(), compare_intervals); }
; =============================================================== ; Mar 2014 ; =============================================================== ; ; size_t b_array_append(b_array_t *a, int c) ; ; Append char to end of array, return index of appended char. ; ; =============================================================== SECTION code_clib SECTION code_adt_b_array PUBLIC asm_b_array_append, asm0_b_array_append EXTERN error_mc asm_b_array_append: ; enter : hl = array * ; bc = int c ; ; exit : bc = int c ; ; success ; ; de = & array.data[idx] ; hl = idx of appended char ; carry reset ; ; fail ; ; hl = -1 ; carry set ; ; uses : af, de, hl inc hl inc hl ; hl = & array.size asm0_b_array_append: ld e,(hl) inc hl ld d,(hl) ; de = array.size inc hl ; hl = & array.capacity ld a,(hl) inc hl cp e jr nz, room_available ; if size != capacity ld a,(hl) cp d jp z, error_mc ; if size == capacity room_available: ; bc = int c ; hl = & array.capacity + 1b ; de = array.size inc de ; size++ dec hl dec hl ; hl = & array.size + 1b ld (hl),d dec hl ld (hl),e ; array.size++ dec hl ld a,(hl) dec hl ld l,(hl) ld h,a ; hl = array.data dec de ; de = idx of char to append add hl,de ; hl = & array.data[idx] ld (hl),c ; append char ex de,hl ; de = & array.data[idx], hl = idx ret
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %rax push %rsi lea addresses_D_ht+0x17d68, %r14 nop xor %rsi, %rsi movl $0x61626364, (%r14) nop nop and $32653, %r10 pop %rsi pop %rax pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r15 push %r8 push %rdi // Load lea addresses_A+0x17468, %r10 nop add %rdi, %rdi mov (%r10), %r11w nop nop nop nop add $18177, %rdi // Faulty Load lea addresses_normal+0x1ef68, %rdi nop nop add $23769, %r10 movups (%rdi), %xmm6 vpextrq $1, %xmm6, %r8 lea oracles, %r11 and $0xff, %r8 shlq $12, %r8 mov (%r11,%r8,1), %r8 pop %rdi pop %r8 pop %r15 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_normal', 'AVXalign': True, 'size': 16, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 8}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_normal', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': True, 'size': 4, 'NT': False, 'same': False, 'congruent': 9}} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
; A345890: a(n) = n + (n - 1) * (n - pi(n)). ; 1,3,5,10,13,21,25,36,49,64,71,89,97,118,141,166,177,205,217,248,281,316,331,369,409,451,495,541,561,610,631,683,737,793,851,911,937,1000,1065,1132,1161,1231,1261,1334,1409,1486,1519,1599,1681,1765,1851,1939,1977,2068 mov $1,$0 seq $1,62298 ; Number of nonprimes <= n. mul $1,$0 add $0,$1 add $0,1
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: ; ; SetJump.Asm ; ; Abstract: ; ; Implementation of SetJump() on x64. ; ;------------------------------------------------------------------------------ %include "Nasm.inc" DEFAULT REL SECTION .text extern InternalAssertJumpBuffer ;------------------------------------------------------------------------------ ; UINTN ; EFIAPI ; SetJump ( ; OUT BASE_LIBRARY_JUMP_BUFFER *JumpBuffer ; ); ;------------------------------------------------------------------------------ global SetJump SetJump: push rcx add rsp, -0x20 call InternalAssertJumpBuffer add rsp, 0x20 pop rcx pop rdx xor rax, rax mov [rcx + 0xF8], rax ; save 0 to SSP mov [rcx], rbx mov [rcx + 8], rsp mov [rcx + 0x10], rbp mov [rcx + 0x18], rdi mov [rcx + 0x20], rsi mov [rcx + 0x28], r12 mov [rcx + 0x30], r13 mov [rcx + 0x38], r14 mov [rcx + 0x40], r15 mov [rcx + 0x48], rdx ; save non-volatile fp registers stmxcsr [rcx + 0x50] movdqu [rcx + 0x58], xmm6 movdqu [rcx + 0x68], xmm7 movdqu [rcx + 0x78], xmm8 movdqu [rcx + 0x88], xmm9 movdqu [rcx + 0x98], xmm10 movdqu [rcx + 0xA8], xmm11 movdqu [rcx + 0xB8], xmm12 movdqu [rcx + 0xC8], xmm13 movdqu [rcx + 0xD8], xmm14 movdqu [rcx + 0xE8], xmm15 xor rax, rax jmp rdx
/* file: model.cpp */ /******************************************************************************* * Copyright 2014-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <jni.h> #include "daal.h" #include "common_helpers.h" #include "com_intel_daal_algorithms_stump_regression_Model.h" using namespace daal; using namespace daal::algorithms; JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_stump_regression_Model_cGetSplitFeature(JNIEnv *, jobject, jlong self) { return (jlong)(unpackModel<stump::regression::Model>(self)->getSplitFeature()); } JNIEXPORT jdouble JNICALL Java_com_intel_daal_algorithms_stump_regression_Model_cGetSplitValue(JNIEnv *, jobject, jlong self) { return (jdouble)(unpackModel<stump::regression::Model>(self)->getSplitValue<double>()); } JNIEXPORT jdouble JNICALL Java_com_intel_daal_algorithms_stump_regression_Model_cGetLeftValue(JNIEnv *, jobject, jlong self) { return (jdouble)(unpackModel<stump::regression::Model>(self)->getLeftValue<double>()); } JNIEXPORT jdouble JNICALL Java_com_intel_daal_algorithms_stump_regression_Model_cGetRightValue(JNIEnv *, jobject, jlong self) { return (jdouble)(unpackModel<stump::regression::Model>(self)->getRightValue<double>()); }
db 0 ; species ID placeholder db 78, 84, 78, 100, 109, 85 ; hp atk def spd sat sdf db FIRE, FLYING ; type db 45 ; catch rate db 209 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F12_5 ; gender ratio db 100 ; unknown 1 db 20 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/charizard/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_MEDIUM_SLOW ; growth rate dn EGG_MONSTER, EGG_DRAGON ; egg groups ; tm/hm learnset tmhm DYNAMICPUNCH, HEADBUTT, CURSE, ROAR, TOXIC, ROCK_SMASH, HIDDEN_POWER, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, ENDURE, FRUSTRATION, IRON_TAIL, DRAGONBREATH, EARTHQUAKE, RETURN, DIG, MUD_SLAP, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SANDSTORM, FIRE_BLAST, SWIFT, DEFENSE_CURL, REST, ATTRACT, STEEL_WING, FIRE_PUNCH, FURY_CUTTER, CUT, FLY, STRENGTH, FLAMETHROWER ; end
; A065358: The Jacob's Ladder sequence: a(n) = Sum_{k=1..n} (-1)^pi(k), where pi = A000720. ; 0,1,0,1,2,1,0,1,2,3,4,3,2,3,4,5,6,5,4,5,6,7,8,7,6,5,4,3,2,3,4,3,2,1,0,-1,-2,-1,0,1,2,1,0,1,2,3,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,3,2,3,4,5,6,7,8,7,6,5,4,5,6,5,4,3,2,1,0,1,2,3,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6,5,4,3 lpb $0 mov $2,$0 sub $0,1 seq $2,65357 ; a(n) = (-1)^pi(n) where pi(n) is the number of primes <= n. add $1,$2 lpe mov $0,$1
#include "callid.hxx" #if SERVER_SOURCE #include "protocol.h" #include "binder.h" #else #include "gnproto.h" #include "gncompress.h" #endif namespace GNET { static GNET::Protocol::Type _state_GLoginClient[] = { UserEnter::PROTOCOL_TYPE, UserEnterResp::PROTOCOL_TYPE, UserWelcome::PROTOCOL_TYPE, UserLeave::PROTOCOL_TYPE, SetMainShow::PROTOCOL_TYPE, SwitchClassShow::PROTOCOL_TYPE, CreateWhiteBoard::PROTOCOL_TYPE, AddCourseWare::PROTOCOL_TYPE, CreateTalkGroup::PROTOCOL_TYPE, SetClassState::PROTOCOL_TYPE, SetClassMode::PROTOCOL_TYPE, SendTextMsg::PROTOCOL_TYPE, ClassAction::PROTOCOL_TYPE, WhiteBoardEvent::PROTOCOL_TYPE, Error_::PROTOCOL_TYPE, EvaluateClass::PROTOCOL_TYPE, ClassInfoRsp::PROTOCOL_TYPE, ReturnCourse::PROTOCOL_TYPE, ReturnCourse::PROTOCOL_TYPE, KickOut::PROTOCOL_TYPE, MediaServerReq::PROTOCOL_TYPE, MediaServerResp::PROTOCOL_TYPE, MediaAddrNotify::PROTOCOL_TYPE, NotifyTalkGroup::PROTOCOL_TYPE, NotifyTalkGroupResp::PROTOCOL_TYPE, NotifyVideoList::PROTOCOL_TYPE, QueryPreCWares::PROTOCOL_TYPE, QueryPreCWares::PROTOCOL_TYPE, QueryPreCWaresResp::PROTOCOL_TYPE, QueryPreCWaresResp::PROTOCOL_TYPE, SetTeacherVedio::PROTOCOL_TYPE, KeepAlive::PROTOCOL_TYPE, RefreshVideoListReq::PROTOCOL_TYPE, RefreshVideoListResp::PROTOCOL_TYPE, MobileConnectClassReq::PROTOCOL_TYPE, MobileConnectClassResp::PROTOCOL_TYPE, UpdateCodeReq::PROTOCOL_TYPE, UpdateCodeResp::PROTOCOL_TYPE, ChooseMobile::PROTOCOL_TYPE, ChooseMobileResp::PROTOCOL_TYPE, Kick::PROTOCOL_TYPE, PromoteAsAssistant::PROTOCOL_TYPE, CancelAssistant::PROTOCOL_TYPE, MesgReminder::PROTOCOL_TYPE, UpdateCourseInfo::PROTOCOL_TYPE, ClassGoOn::PROTOCOL_TYPE, ClassRecord::PROTOCOL_TYPE, ClassRecord::PROTOCOL_TYPE, ClassDelayTimeOut::PROTOCOL_TYPE, CommitCourseWares::PROTOCOL_TYPE, Login::PROTOCOL_TYPE, LoginRet::PROTOCOL_TYPE, LoginRet_DB::PROTOCOL_TYPE, TokenValidate::PROTOCOL_TYPE, TokenValidateResp::PROTOCOL_TYPE, QueryUser::PROTOCOL_TYPE, ReturnUser::PROTOCOL_TYPE, QueryUserList::PROTOCOL_TYPE, QueryUserListResp::PROTOCOL_TYPE, QueryUserEdu::PROTOCOL_TYPE, ReturnUserEdu::PROTOCOL_TYPE, QueryCourse::PROTOCOL_TYPE, QueryToken::PROTOCOL_TYPE, ReturnToken::PROTOCOL_TYPE, FeedBack::PROTOCOL_TYPE, MesgReq::PROTOCOL_TYPE, MesgResp::PROTOCOL_TYPE, QueryAutoLoginToken::PROTOCOL_TYPE, AutoLoginTokenRsp::PROTOCOL_TYPE, OnLineNotify::PROTOCOL_TYPE, MobileConnectReq::PROTOCOL_TYPE, MobileConnectResp::PROTOCOL_TYPE, MobileOff::PROTOCOL_TYPE, QueryOnClasses::PROTOCOL_TYPE, OnClassesResp::PROTOCOL_TYPE, }; GNET::Protocol::Manager::Session::State state_GLoginClient(_state_GLoginClient, #ifdef SERVER_SOURCE sizeof(_state_GLoginClient) / sizeof(GNET::Protocol::Type), 120,"GLoginClient"); #else sizeof(_state_GLoginClient) / sizeof(GNET::Protocol::Type), 120); #endif };
;GLOBAL SYSTEM NAMES AND CONSTANTS. ;SCREEN PARAMETERS, PIXELS AND ATTRIBUTES. SCREEN_ADDR EQU #4000 SCREEN_SIZE EQU #1800 SCREEN_ATTRIB EQU #5800 ATTRIB_SIZE EQU #300 SCREEN_X_SIZE EQU #20 SCREEN_Y_SIZE EQU #18 ;KEMPSTON JOYSTICK BITS TO CHECK AND PORT. KEMPSTON_PORT EQU #1F KEMPSTON_MASK EQU %00011111 ;LOW KEMPSTON_RIGHT EQU #00 KEMPSTON_LEFT EQU #01 KEMPSTON_DOWN EQU #02 KEMPSTON_UP EQU #03 KEMPSTON_FIRE EQU #04 ;AY MODULE REMOVE LATER TO DATA SECTION. ; ORG #C000 ;MOD: INCBIN "MOD.C" ;MAIN PART STARTS FROM 24K, 40KB MAX. ORG #6000 LD HL,#0000 ;SET STACK TO TOP ADD HL,SP ;OF CODE PART LD SP,#5E00 ;RESERVED FOR IM2 PUSH HL ;STORE FOR SAFE PUSH AF ;REMOVE LATER PUSH BC PUSH DE PUSH HL PUSH IX PUSH IY ;SET INTERRUPT ;JR NO_IM2 DI LD HL,#5EFF ;IM2_ADDR LD BC,IM2 ;+FF FROM STACK LD (HL),C INC HL LD (HL),B LD A,#5E ;SET HIGHER PART LD I,A IM 2 EI ;INTS 50 FPS NO_IM2: LD A,0 LD (ACTIVE_LOCATION),A CALL INIT_GAME OR A LD DE,#6000 LD HL,BINARY_DATA_START SBC HL,DE OR A LD HL,FIRST_FREE_BYTE SBC HL,DE ;CALL DRAW_LOCATION ;XOR A ;CALL CREATE_SCENE CALL GAME_MAIN_CYCLE ;LD IX,BOB ;CALL DRAW_ANIMATION TO_RET: LD A,1 ;RESTORE BORDER OUT (#FE),A POP IY ;RESTORE REGS POP IX POP HL POP DE POP BC POP AF POP HL LD SP,HL ;RESTORE STACK RET ;GLOBAL STATIC VARIABLES. ;GLOBAL GAME CONSTANTS AND VARIABLES. SPRITE_MOV EQU %00000001 SPRITE_AND EQU %00000010 SPRITE_OR EQU %00000100 SPRITE_A_O EQU %00001000 SPRITE_SAV EQU %00010000 SPRITE_MSK EQU %00011111 RANDOM_INIT EQU %10101010 WORLD_SIZE_X EQU 1024 WORLD_SIZE_Y EQU 32 ;X AND Y IN PIXELS WORLD_LOCATIONS EQU 4 STARS_ON_SKY EQU 150 STARS_POSITION EQU 16 ;AFTER STATUS BAR STARS_SIZE EQU 24 ;2 ATTRIBUTES BG_LOC_POS_X EQU #00 ;BACKGROUND BG_LOC_POS_Y EQU #05 ;LOCATION START BG_LOC_SIZE_X EQU #20 ;AND BOTH SIZES BG_LOC_SIZE_Y EQU #10 BG_LOC_BYTES EQU #1000 ;MEM SIZE ROAD_POSY EQU #15 ;ROAD Y POSITION GAME_BORDER EQU #00 ;BLACK UNLESS DBG BG_DEFAULT_A EQU %01000111 BG_DEBUG_A EQU %01111000 ;ATTRIB BG_DEFAULT_BT EQU %00000000 ;BYTE TO BG_DEBUG_BT EQU %11111111 ;FILL ;BOB POSITIONS MUST BE EQUAL ON ASSEMBLE BOB_START_X: EQU #07 ;DEFAULT BOB_START_Y: EQU #13 BOB_SZ_X EQU #04 ;BOB SIZES BOB_SZ_Y EQU #04 HEROES_IN_GAME EQU 2 ITEMS_MAX EQU #02 ;OBJECT TYPES AND ADRESSES. OBJ_EMPTY EQU #00 OBJ_LAMP_ON EQU #01 OBJ_LAMP_OFF EQU #02 ;OBJECT RESERVED OBJ_LIGHT EQU #04 OBJ_BONE EQU #05 OBJ_FLOWERS EQU #06 OBJ_KEYS EQU #07 OBJ_OIL EQU #08 OBJ_MHOLE EQU #09 OBJ_DOG_DBG EQU #10 OBJ_CAPE_DBG EQU #11 ;ITEMS TABLE WITH ANIMATION AND INVENTORY ;IMAGES. 4 BYTES FOR EVERY ITEM. IMG_OFFSET EQU #02 ;FOR STATUS BAR ITEMS_TABLE: DW #0000 DW SB_ITEM_BLANK DW LAMP_ON DW #0000 DW LAMP_OFF DW #0000 DW #0000 ;RESERVED DW #0000 DW LIGHT DW SB_LIGHT_ITEM DW BONE DW SB_BONE_ITEM DW FLOWERS DW SB_FLOWERS_ITEM DW KEY DW SB_KEY_ITEM ;SYSTEM VARIABLES KEMPSTON: DUP 07 DB #00 ;EVERY INTERRUPT EDUP ;PREVIOUS PUSHES KEMPSTON_TOP: DB #00 ;TOP FOR QUE KEMPSTON_DEEP: EQU #08 ;FOR MOVING KEMPSTON_INACTIVE: DB #00 BOB_INACTIVE EQU #80 ;TIMER FOR STAND BOB_RIGHT_ACT: DB #00 BOB_LEFT_ACT: DB #00 BOB_SPEED EQU #08 ;BOB SPEED ;GAME VARIABLES STARS: DUP STARS_ON_SKY DW #0000 EDUP ACTIVE_LOCATION:DB #00 ;HERO LOCATION ACT_LOC_ADDR: DW GAME_WORLD GAME_IM2: DB #00 GAME_TIMER: DB #00 ;ALL TIME FOR BOB BAR_ATTRIB: DB %01010111 ;RED DB %01110111 ;YELLOW DB %01100111 ;GREEN ;TYPES OF ACTION FOR CHARACTERS EMPTY_ACTION EQU #00 CHAR_STAND EQU #01 CHAR_MOVE_LR EQU #02 CHAR_MOVE_RL EQU #03 SIZEOF_CHAR EQU #10 ;IN BYTES ;CHARACTERS GLOBAL VARIABLES. HEROES_TABLE: HERO_BOB: BOB_ACTION_T: DB CHAR_MOVE_LR BOB_ACTION_F: DB %00000000 ;FLAGS BOB_ANIMATION: DW BOB_WALK_LR ;ANIMATION ADDR BOB_POS_Y: DB BOB_START_Y ;ACTIVE POS BOB_POS_X: DB BOB_START_X BOB_PREV_Y: DB BOB_START_Y ;PREVIOS BOB_PREV_X: DB BOB_START_X BOB_SIZE_Y: DB #04 ;SIZES BOB_SIZE_X: DB #04 BOB_RESTORE: DW BOB_R1 ;STORE BOB_ENERGY: DB #03 ;BOB ENERGY BOB_ITEM_1: DB OBJ_EMPTY ITEM_FLAGS_1: DB %00000000 BOB_ITEM_2: DB OBJ_LIGHT ITEM_FLAGS_2: DB %10000100 BOB_ITEM_3: DB OBJ_EMPTY ;FOR DROP ITEM_FLAGS_3: DB %00000000 AREAS_OFFSET EQU #08 SIZEOF_AREA EQU #0007 ;MOVE AND EXIT OBJECTS_OFFSET EQU #03 ;OFFSET SIZEOF_OBJECT EQU #08 ;IN BYTES GAME_WORLD: LOC_1_ENTRANCE: DW LOCATION_1 LOC_2_SHOP: DW LOCATION_2 ;LOC_2A_FLOWERS: DW LOCATION_2A LOC_3__MALL: DW LOCATION_3 ;LOC_3A_MARKET: DW LOCATION_3A LOC_4_HOUSE: DW LOCATION_4 ;STANDARD OBJECTS USING ANIM STRUCTURE ;MAIN CHARACTER STRUCTURES OF THE GAME. ;INITIALIZATION OF GAME PARAMETERS. ;MAY BE NOT NEEDED. INIT_GAME: PUSH AF PUSH BC PUSH DE PUSH HL PUSH IX PUSH IY ;CLEAR ALL SCREEN AND SET BORDER LD D,BG_DEFAULT_BT ;LD D,BG_DEBUG_BT LD E,BG_DEFAULT_A ;LD E,BG_DEBUG_A CALL CLEAR_SCREEN LD A,GAME_BORDER OUT (#FE),A ;DRAW A RANDOM STARS ON SKY. LD B,STARS_ON_SKY INIT_1: CALL RANDOM AND %00011111 ;FOR 16 PIXELS CP STARS_SIZE JR C,INIT_2 RES 3,A INIT_2: ADD A,STARS_POSITION LD E,A CALL RANDOM LD D,A CALL SET_PIXEL DJNZ INIT_1 ;DRAW STATUS BAR AND ITEMS LD DE,#0001 ;DRAW DECORATIONS LD BC,#0102 LD HL,SB_DAT_L LD A,SPRITE_MOV CALL DRAW_SPRITE LD DE,#1301 CALL DRAW_SPRITE LD B,11 LD DE,#0102 LD HL,SB_DAT_M SBAR_1: PUSH BC LD BC,#0101 CALL DRAW_SPRITE INC D POP BC DJNZ SBAR_1 LD B,11 LD DE,#1402 SBAR_2: PUSH BC LD BC,#0101 CALL DRAW_SPRITE INC D POP BC DJNZ SBAR_2 LD HL,SB_DAT_R LD DE,#0C01 LD BC,#0102 CALL DRAW_SPRITE LD DE,#1F01 CALL DRAW_SPRITE LD HL,SB_HEART_OFF ;ENERGY LD DE,#0200 LD BC,#0302 CALL DRAW_SPRITE LD B,2 LD HL,SB_HEART_ON LD DE,#0500 SBAR_3: PUSH BC LD BC,#0302 CALL DRAW_SPRITE INC D INC D INC D POP BC DJNZ SBAR_3 LD H,%00000010 ;COLORS FOR ENERGY LD L,%00000100 ;COLOR FOR TIMER LD IX,#5801 ;ADDRESSES LD IY,#5814 LD BC,#0B02 LD DE,#0020 SBAR_5: PUSH IX PUSH IY PUSH BC SBAR_4: LD (IX+0),H LD (IY+0),L INC IX INC IY DJNZ SBAR_4 POP BC POP IY POP IX ADD IX,DE ADD IY,DE DEC C JR NZ,SBAR_5 CALL UPDATE_ITEMS LD BC,#0603 ;COLORS FOR ITEMS LD DE,#0020 LD HL,#580D LD A,%00000111 SBAR_7: PUSH HL PUSH BC SBAR_6: LD (HL),A INC HL DJNZ SBAR_6 POP BC POP HL ADD HL,DE DEC C JR NZ,SBAR_7 LD HL,SB_GAME_TIMER ;TIMER LD DE,#1400 LD BC,#0B02 LD A,SPRITE_MOV CALL DRAW_SPRITE ;DRAW FIRST LOCATION ON START INIT_GE:CALL DRAW_LOCATION POP IY POP IX POP HL POP DE POP BC POP AF RET ;CREATE SCENE, ON EVERY FRAME IN GAME, ;DRAW/UPDATE ALL OBJECTS IF NEEDED ;ON SCREEN, SAVE BACKGROUND FOR HERO. ;SCENE MUST HAVE AT LEAST ONE OBJECT ;NO CHECKS FOR DATA RANGES. ;TIMINGS FOR GAME_IM2 IN BITS. ;[00] DRAW OBJECTS ;[01] DRAW BOB ;[10] DRAW CHARACTERS, LATER. CREATE_SCENE: PUSH AF PUSH BC PUSH DE PUSH HL PUSH IX PUSH IY ;CHECK FRAME COUNTER LD A,(GAME_IM2) BIT 0,A ;IF OBJECTS JR NZ,SCENE_1 ;DRAW OBJECTS ON LOCATION SCENE_2:LD IX,(ACT_LOC_ADDR) LD B,(IX) ;OBJECTS COUNTER LD A,B ;NO OBJECTS OR A JP Z,SCENE_R ;CHECK TO HEROES LD L,(IX+OBJECTS_OFFSET) LD H,(IX+OBJECTS_OFFSET+1) SCENE_3:PUSH HL POP IY BIT 7,(IY+5) JR Z,SCENE_4 LD E,(IY+0) LD D,(IY+1) PUSH DE POP IX ;IX - ANIM ADDR LD A,(IY+2) LD (IX+0),A LD A,(IY+3) LD (IX+1),A CALL DRAW_ANIMATION SCENE_4:LD DE,SIZEOF_OBJECT ADD HL,DE DJNZ SCENE_3 JR SCENE_R SCENE_1: ;DRAW BOB ON ACTIVE LOCATION ;RESTORE BACKGROUND FROM BOB PREVIOUS POS LD A,(ACTIVE_LOCATION) LD DE,(BOB_PREV_Y) LD HL,(BOB_RESTORE) LD BC,(BOB_SIZE_Y) LD A,SPRITE_MOV CALL DRAW_SPRITE LD IX,(BOB_ANIMATION) ;DRAW NEW LD DE,(BOB_POS_Y) LD (IX+0),D LD (IX+1),E CALL DRAW_ANIMATION ;JR SCENE_R SCENE_5: ;DRAW OTHER CHARACTERS ON LOCATION SCENE_R:POP IY POP IX POP HL POP DE POP BC POP AF RET ;GAME MAIN CYCLE. GAME_MAIN_CYCLE: PUSH AF PUSH BC PUSH DE PUSH HL PUSH IX PUSH IY ;JP GAME_R ;LD BC,#0100 ;MAIN CYCLE GAME_1: PUSH BC HALT CALL CREATE_SCENE ;LD A,#06 ;LOGIC PERFRORM ;OUT (#FE),A ;LD A,1 ;LD (KEMPSTON),A ;TODO MOVING LOGIC LD A,(GAME_IM2) BIT 0,A JR NZ,GAME_2 ;NOT BOB FRAME CALL MOVE_BOB_KEMPSTON GAME_2: LD A,(KEMPSTON) BIT KEMPSTON_FIRE,A JP Z,GAME_3 CALL BOB_ACTION_KEMPSTON GAME_3: ;LD A,#04 ;EXTRA PERFORMANCE ;OUT (#FE),A POP BC ;DEC BC ;LD A,B ;OR C JP GAME_1 GAME_R: POP IY POP IX POP HL POP DE POP BC POP AF RET ;UPDATE ITEMS ON STATUS BAR. ;USING VARIABLES OF BOB ITEMS. UPDATE_ITEMS: PUSH AF PUSH BC PUSH DE PUSH HL LD B,ITEMS_MAX LD C,#0D ;FIRST ITEM X LD HL,BOB_ITEM_1 UPD_I1: PUSH BC PUSH HL LD A,(HL) SLA A ;4 BYTES SLA A ADD A,IMG_OFFSET ;2 BYTES FOR TAB LD D,#00 LD E,A LD HL,ITEMS_TABLE ADD HL,DE LD E,(HL) INC HL LD D,(HL) EX DE,HL LD D,C LD E,0 LD BC,#0303 LD A,SPRITE_MOV CALL DRAW_SPRITE POP HL POP BC LD A,C ADD A,3 LD C,A INC HL ;WITH FLAG INC HL DJNZ UPD_I1 POP HL POP DE POP BC POP AF RET ;USING ITEMS IN BOTH HANDS AND GAME LOGIC. BOB_ACTION_KEMPSTON: PUSH AF PUSH BC PUSH DE PUSH HL PUSH IX PUSH IY LD IX,(ACT_LOC_ADDR) LD B,(IX+0) ;NO OBJECTS LD A,B OR A JP Z,BOBA_R LD E,(IX+3) LD D,(IX+4) PUSH DE POP IY ;IY - OBJECTS BOBA_0: BIT 7,(IY+5) ;IF EXIST JP Z,BOBA_1 LD A,(IY+7) ;RANGES LD DE,(BOB_POS_Y) SUB E JP C,BOBA_1 ;IF LOWER CP BOB_SZ_Y ;IN RANGE Y JP NC,BOBA_1 LD A,(IY+6) SUB D JP C,BOBA_1 ;IF RIGHTER CP BOB_SZ_X ;CHECK RANGE X JP NC,BOBA_1 BIT 0,(IY+5) ;CHECK TYPE JP NZ,BOBA_1 ;IF DECORATION BIT 1,(IY+5) JR Z,BOBA_2 ;IF ACTIVE OBJ ;ACTIVE OBJECT WITH USE ITEMS LD A,(IY+4) CP OBJ_LAMP_OFF JR NZ,BOBA_1 LD A,(BOB_ITEM_1) CP OBJ_LIGHT JR NZ,BOBA_A0 LD E,OBJ_EMPTY ;DELETE ITEM LD D,%00000000 LD (BOB_ITEM_1),DE JR BOBA_A1 BOBA_A0:LD A,(BOB_ITEM_2) CP OBJ_LIGHT JP NZ,BOBA_R ;NO ITEM LIGHT LD E,OBJ_EMPTY ;DELETE ITEM LD D,%00000000 LD (BOB_ITEM_2),DE BOBA_A1:LD DE,LAMP_ON ;SWITCH ON LAMP LD (IY+0),E LD (IY+1),D LD A,OBJ_LAMP_ON LD (IY+4),A CALL DRAW_LOCATION CALL UPDATE_ITEMS JP BOBA_R BOBA_2: BIT 2,(IY+5) ;CAN PICK OBJECT JP Z,BOBA_1 LD DE,(BOB_ITEM_2) ;PICK OBJECT LD (BOB_ITEM_3),DE LD DE,(BOB_ITEM_1) ;WITH FLAG LD (BOB_ITEM_2),DE LD A,(IY+4) ;OBJ TO PICK LD (BOB_ITEM_1),A LD A,(IY+5) LD (ITEM_FLAGS_1),A CALL UPDATE_ITEMS RES 7,(IY+5) ;NOT EXIST CALL DRAW_LOCATION LD A,(BOB_ITEM_3) OR A ;NEED TO DROP JP Z,BOBA_R LD A,#02 JR BOBA_D BOBA_1: DEC B JP Z,BOBA_4 LD DE,SIZEOF_OBJECT ADD IY,DE ;NEXT ITEM JP BOBA_0 ;AFTER CYCLE CHECK FOR DROP ITEMS BOBA_4: LD A,(ITEM_FLAGS_1) BIT 3,A ;CHECK FOR DROP JR Z,BOBA_5 LD A,#00 JR BOBA_D BOBA_5: LD A,(ITEM_FLAGS_2) BIT 3,A JP Z,BOBA_R LD A,#01 BOBA_D: BIT 7,(IY+5) ;FIRST FREE JR Z,BOBA_D2 LD DE,SIZEOF_OBJECT ADD IY,DE ;TO FIRST FREE DJNZ BOBA_D ; BOBA_D2:LD HL,BOB_ITEM_1;DROP ITEM A = N SLA A LD E,A LD D,0 ADD HL,DE LD B,(HL) ;B = ITEM TO DROP LD A,OBJ_EMPTY ;CLEAR ITEM LD (HL),A INC HL LD C,(HL) ;C = FLAGS LD A,%00000000 LD (HL),A LD HL,ITEMS_TABLE LD A,B SLA A ;A * 4 BYTES SLA A LD E,A ;D = 0 AS UPPER ADD HL,DE LD E,(HL) ;REWRITE EMPTY OBJ INC HL LD D,(HL) LD (IY+0),E ;ADDR OF ANIM LD (IY+1),D LD A,(BOB_POS_X) ADD A,BOB_SZ_X DEC A LD (IY+2),A LD (IY+6),A ;NEW POSITION OBJ LD A,(BOB_POS_Y) ADD A,BOB_SZ_Y DEC A LD (IY+3),A LD (IY+7),A LD (IY+4),B ;OBJ TYPE LD (IY+5),C ;FLAG CALL DRAW_LOCATION CALL UPDATE_ITEMS JP BOBA_R BOBA_R: POP IY POP IX POP HL POP DE POP BC POP AF RET ;MOVING CHARACTER WITH KEMPSTON JOYSTICK. ;USING GLOBAL VARIABLES: ;"KEMPSTON" - INPUT FROM IM2. ;HERO_BOB - SEE ALL NAMED DATA. ;LOCATIONS FOR MOVE LIMITS. MOVE_BOB_KEMPSTON: PUSH AF PUSH BC PUSH DE PUSH HL PUSH IX LD DE,(BOB_POS_Y) ;D - X LD (BOB_PREV_Y),DE ;E - Y LD A,(KEMPSTON) BIT KEMPSTON_RIGHT,A JR Z,MB_K1 INC D JR MB_K4 MB_K1: BIT KEMPSTON_LEFT,A JR Z,MB_K2 LD A,D ;FOR C-FLAG ADD OR A JR Z,MB_K4 DEC D JR MB_K4 MB_K2: BIT KEMPSTON_DOWN,A JR Z,MB_K3 INC E JR MB_K4 MB_K3: BIT KEMPSTON_UP,A JP Z,MB_K5 ;NOTHING TO MOVE LD A,E ;FOR C-FLAG ADD OR A JR Z,MB_K4 DEC E MB_K4: LD BC,(BOB_SIZE_Y) PUSH DE POP HL ;DE LEFT-UP ADD HL,BC ;HL RIGHT-DOWN LD IX,(ACT_LOC_ADDR) LD B,(IX+1) ;B - MOVE AREAS LD A,B OR A JP Z,MB_K5 ;NO AREAS LD C,(IX+2) ;EXIT AREAS PUSH BC LD BC,AREAS_OFFSET ADD IX,BC ;IX - AREAS POP BC MB_K6: PUSH BC LD B,(IX+0) LD A,D ;X CP B JR C,MB_KNA ;NOT IN AREA LD B,(IX+1) LD A,E CP B JR C,MB_KNA ;CORRECT IN DATA LD A,(IX+2) ;RIGHT DOWN CP H JR C,MB_KNA LD A,(IX+3) CP L JR C,MB_KNA POP BC LD (BOB_POS_Y),DE ;IN AREA LD A,(BOB_PREV_Y) CP E JR NZ,MB_KLOC PUSH HL LD A,(BOB_PREV_X) CP D JR NC,MB_K9 LD A,(BOB_RIGHT_ACT) ;SPEED CP BOB_SPEED JP NC,MB_KS1 LD DE,(BOB_PREV_Y) LD (BOB_POS_Y),DE JP MB_KS3 MB_KS1: XOR A LD (BOB_RIGHT_ACT),A LD HL,BOB_WALK_LR LD A,CHAR_MOVE_LR LD (BOB_ACTION_T),A JR MB_K10 MB_K9: LD A,(BOB_LEFT_ACT) ;SPEED L CP BOB_SPEED JP NC,MB_KS2 LD DE,(BOB_PREV_Y) LD (BOB_POS_Y),DE JP MB_KS3 MB_KS2: XOR A LD (BOB_LEFT_ACT),A LD HL,BOB_WALK_RL LD A,CHAR_MOVE_RL LD (BOB_ACTION_T),A MB_K10: LD (BOB_ANIMATION),HL MB_KS3: POP HL JR MB_KLOC MB_KNA: LD BC,SIZEOF_AREA ADD IX,BC ;NEXT AREA POP BC DJNZ MB_K6 JP MB_K5 ;NOT IN AREA MB_KLOC:LD A,C ;CHECK FOR EXITS OR A JR Z,MB_K5 LD A,B ;MOVE OK OR A ;CHECK EXITS JR Z,MB_K7 ;ADD TO IX EXTRA PUSH DE LD DE,SIZEOF_AREA MB_K8: ADD IX,DE DJNZ MB_K8 POP DE ;IX - EXIT AREAS MB_K7: LD B,(IX+0) LD A,D ;X CP B JR C,MB_KNE ;NOT IN EXIT AREA LD B,(IX+1) LD A,E CP B JR C,MB_KNE ;CORRECT IN DATA LD A,(IX+2) ;RIGHT DOWN CP H JR C,MB_KNE LD A,(IX+3) CP L JR C,MB_KNE LD A,(IX+4) ;CHANGE LOCATION LD (ACTIVE_LOCATION),A LD D,(IX+5) ;BOB NEW POSITION LD E,(IX+6) LD (BOB_POS_Y),DE LD (BOB_PREV_Y),DE CALL DRAW_LOCATION JR MB_K5 MB_KNE: PUSH DE LD DE,SIZEOF_AREA ADD IX,DE POP DE DEC C JR NZ,MB_K7 MB_K5: LD A,(KEMPSTON_INACTIVE) CP BOB_INACTIVE JR C,MB_KR LD A,(BOB_ACTION_T) CP CHAR_MOVE_LR JR NZ,MB_K12 LD HL,BOB_STAND_R JR MB_K13 MB_K12: CP CHAR_MOVE_RL JR NZ,MB_KR LD HL,BOB_STAND_L MB_K13: LD A,CHAR_STAND LD (BOB_ACTION_T),A LD (BOB_ANIMATION),HL MB_KR: POP IX POP HL POP DE POP BC POP AF RET ;DRAW GAME ACTIVE LOCATION ON SCREEN. ;LOCATION, ROAD AND STATUS BAR. ;USING GLOBAL VARIABLES: ;ACTIVE_LOCATION - 0..3. DRAW_LOCATION: PUSH AF PUSH BC PUSH DE PUSH HL PUSH IX PUSH IY ;JP DLOC_8 LD HL,LOCATION_1 ;CALCULATE ACTIVE LOCATION ADDRESS LD HL,GAME_WORLD LD A,(ACTIVE_LOCATION) SLA A LD E,A LD D,#00 ADD HL,DE LD E,(HL) INC HL LD D,(HL) LD (ACT_LOC_ADDR),DE ;JP DLT ;WITHOUT ATTRIB ;CLEAR ATTRIBUTES FROM LAMPS LD HL,SCREEN_ATTRIB LD DE,#00A0 ADD HL,DE LD BC,#0260 DCLR_1: LD A,%01000111 LD (HL),A INC HL DEC BC LD A,B OR C JR NZ,DCLR_1 ;DRAW MAIN BACKGROUND IN LOCATION DLT: LD IX,(ACT_LOC_ADDR) LD L,(IX+5) ;BACKGROUND LD H,(IX+6) DLOC_1: LD A,SPRITE_MOV LD D,BG_LOC_POS_X LD E,BG_LOC_POS_Y LD B,BG_LOC_SIZE_X LD C,BG_LOC_SIZE_Y CALL DRAW_SPRITE ;JP DLOC_T ;WITHOUT ROAD LD A,#10 ;DRAW ROAD LD BC,#0203 ;ROAD SIZE LD DE,#0015 ;ROAD POSITION LD HL,ROAD_TILE DLOC_3: PUSH AF LD A,SPRITE_MOV CALL DRAW_SPRITE POP AF INC D INC D DEC A JR NZ,DLOC_3 ;DRAW ALL OBJECTS IN LOCATION DLOC_T: LD IX,(ACT_LOC_ADDR) LD B,(IX) ;OBJECTS COUNTER LD A,B ;NO OBJECTS OR A JP Z,DLOC_8 ;CHECK TO HEROES LD L,(IX+OBJECTS_OFFSET) LD H,(IX+OBJECTS_OFFSET+1) DLOC_6: PUSH HL POP IY BIT 7,(IY+5) ;IF NOT EXIST JP Z,DLOC_7 LD E,(IY+0) LD D,(IY+1) PUSH DE POP IX ;IX - ANIM ADDR LD A,(IY+2) LD (IX+0),A LD A,(IY+3) LD (IX+1),A BIT 5,(IX+5) ;IF STATIC OBJECT JR Z,DLOC_9 SET 6,(IX+5) ;REDRAW ONCE DLOC_9: CALL DRAW_ANIMATION RES 6,(IX+5) LD A,(IY+4) CP OBJ_LAMP_OFF JR NZ,DLOC_7 ;DRAW LAMP SHADES PUSH HL PUSH BC LD B,8 LD A,(IY+2) ADD A,#02 ;SIZE OF SHADE LD D,A LD E,BG_LOC_POS_Y LMP_S1: PUSH BC LD HL,LAMP_SHAD_L LD A,E LD BC,#0202 LD A,SPRITE_AND CALL DRAW_SPRITE POP BC INC E INC E DJNZ LMP_S1 LD E,ROAD_POSY LD BC,#0303 LD HL,LAMP_SHAD_R LD A,SPRITE_AND CALL DRAW_SPRITE LD HL,LAMP_SHAD_B LD E,BG_LOC_POS_Y INC D ;DARK PART INC D LD A,SCREEN_X_SIZE SUB (IY+2) SUB (IX+2) ;SUB #02 ;SIZE OF SHADE LD B,A LD C,SCREEN_Y_SIZE-BG_LOC_POS_Y LMP_S3: PUSH BC PUSH DE LD A,C CP #04 ;ROAD SIZE + 1 JR NC,LMP_S4 ;IF SHADE TO ROAD INC D DEC B OR A JR LMP_S2 LMP_S4: SCF ;FIRST ATTRIB LMP_S2 PUSH BC LD BC,#0101 LD A,SPRITE_MOV ;CALL DRAW_SPRITE JR C,LMP_S5 PUSH DE ;SET ATTRIBUTES PUSH HL LD HL,#0000 LD A,E ;Y TO H AND %00011000 RRA RRA RRA LD H,A LD A,E AND %00000111 RRCA RRCA RRCA OR D ;ADD X POSITION LD L,A LD DE,SCREEN_ATTRIB ADD HL,DE LD (HL),%01000001 POP HL POP DE LMP_S5: POP BC ;AFTER ATTRIB INC D OR A DJNZ LMP_S2 POP DE INC E POP BC DEC C JR NZ,LMP_S3 POP BC POP HL DLOC_7: LD DE,SIZEOF_OBJECT ADD HL,DE DEC B JP NZ,DLOC_6 ;NEXT OBJECT ;STORE BACKGROUND FOR LOCAL CHARACTERS DLOC_8: LD DE,(BOB_POS_Y) LD BC,(BOB_SIZE_Y) LD IY,BOB_R1 LD A,SPRITE_SAV CALL DRAW_SPRITE DRAW_LR:POP IY POP IX POP HL POP DE POP BC POP AF RET ;IM2 INTERRUPT PART OF CODE. IM2: DI PUSH AF PUSH BC PUSH DE PUSH HL PUSH IX PUSH IY ; LD A,1 ;PERFORMANCE ; OUT (#FE),A IN A,(KEMPSTON_PORT) AND KEMPSTON_MASK LD (KEMPSTON),A JR NZ,IM2_1 LD A,(KEMPSTON_INACTIVE) INC A LD (KEMPSTON_INACTIVE),A JR IM2_2 IM2_1: BIT KEMPSTON_RIGHT,A JR Z,IM2_3 LD A,(BOB_RIGHT_ACT) INC A LD (BOB_RIGHT_ACT),A JR IM2_2 IM2_3: BIT KEMPSTON_LEFT,A JR Z,IM2_2 LD A,(BOB_LEFT_ACT) INC A LD (BOB_LEFT_ACT),A IM2_2: LD A,(GAME_IM2) INC A LD (GAME_IM2),A ; CALL MOD ;CALL AY-PLAYER. IM2_R: POP IY POP IX POP HL POP DE POP BC POP AF EI RETI CREDITS:DB " LONELY LAMPS GAME! ",0 DB " CREATED BY ",0 DB " 8-BIT TEA PARTY! ",0 DB " ",0 DB " IDEAS, STORY, ORG ",0 DB " DMITRY GALASHIN ",0 DB " ",0 DB " HEROES & ITEM GRAPHICS ",0 DB " EUGENE MASLOV ",0 DB " ",0 DB " LOCATIONS GRAPHICS ",0 DB " ZERDROS ",0 DB " ",0 DB " CODE ",0 DB " ALEXANDER SEROV ",0 DB " ",0 DB " SPECIAL THANKS TO: ",0 DB " VASILY KOLCHIN ",0 DB " ROMAN NOTKOV ",0 DB " VLADIMIR SMIRNOV ",0 DB " ",0 DB " AUTUMN 2019 ",0 ;LIBRARY FUNCTIONS FOR GAME INCLUDE "LIBRARY.A",0 BINARY_DATA_START: DB #00 INCLUDE "LLAMPS_D.A",1 ;BINARY GFX DATA BOB_M1: INCBIN "BOB_MSK1.C",64 BOB_M2: INCBIN "BOB_MSK2.C",64 BOB_1_1: INCBIN "BOB_P1F1.C",64 BOB_1_2: INCBIN "BOB_P1F2.C",64 BOB_1_3: INCBIN "BOB_P1F3.C",64 BOB_2_1: INCBIN "BOB_P2F1.C",64 BOB_2_2: INCBIN "BOB_P2F2.C",64 BOB_2_3: INCBIN "BOB_P2F3.C",64 BOB_2_4: ;INCBIN "BOB_P2F4.C",64 BOB_I_M1: INCBIN "BOBIMSK1.C",64 BOB_I_M2: INCBIN "BOBIMSK2.C",64 BOB_I_1_1: INCBIN "BOBIP1F1.C",64 BOB_I_1_2: INCBIN "BOBIP1F2.C",64 BOB_I_1_3: INCBIN "BOBIP1F3.C",64 BOB_I_2_1: INCBIN "BOBIP2F1.C",64 BOB_I_2_2: INCBIN "BOBIP2F2.C",64 BOB_I_2_3: INCBIN "BOBIP2F3.C",64 BOB_I_2_4: ;INCBIN "BOB_P3F4.C",64 LAMP_DAT_M0: INCBIN "LMPP2MSK.C",80 LAMP_DAT_0: INCBIN "LMP_P2F1.C",80 LAMP_DAT_M1: INCBIN "LMPP1MSK.C",96 LAMP_DAT_M2: INCBIN "LMP1AMSK.C",96 LAMP_DAT_1: INCBIN "LMP_P1F1.C",96 LAMP_DAT_2: INCBIN "LMP_P1F2.C",96 LAMP_DAT_3: INCBIN "LMP_P1F3.C",96 DOG_DAT_0: INCBIN "DOG_F1.C",96 DOG_DAT_3: INCBIN "DOG_F3.C",96 DOG_MSK_0: INCBIN "DOG_MSK.C",96 CAPE_DAT_0: INCBIN "CLOAK_F1.C",80 CAPE_DAT_6: INCBIN "CLOAK_F6.C",80 CAPE_MSK_0: INCBIN "CLOAK_M.C",80 LAMP_SHAD_B: DUP 08 DB #00 EDUP LAMP_SHAD_L: INCBIN "LMPSHD.C",32 LAMP_SHAD_R: INCBIN "ROADSHD.C",72 LOC_DATA_0: INCBIN "BG01.C",4096 LOC_DATA_1: INCBIN "BG02.C",4096 LOC_DATA_2: INCBIN "BG03.C",4096 LOC_DATA_3: INCBIN "BG04.C",4096 ROAD_TILE: INCBIN "TILE2X3.C" LIGHT_DAT: INCBIN "LIGHT.C",8 BONE_DAT: INCBIN "BONE.C",8 BONE_MSK: INCBIN "BONE_MSK.C",8 FLOWERS_DAT: INCBIN "FMRS_SML.C",8 KEYS_DAT: INCBIN "KEYS.C",8 OIL_DAT: INCBIN "OIL.C",48 OIL_MSK: INCBIN "OIL_MSK.C",48 MHOLE_DAT: INCBIN "MHOLE.C",48 MHOLE_MSK: INCBIN "MHOLEMSK.C",48 SB_DAT_L: INCBIN "SBL_A.C",16 SB_DAT_M: INCBIN "SBM_A.C",8 SB_DAT_R: INCBIN "SBR_A.C",16 SB_HEART_ON: INCBIN "LH_ON.C",48 SB_HEART_OFF: INCBIN "LH_OFF.C",48 SB_ITEM_BLANK: INCBIN "SBI_BLNK.C",72 SB_GAME_TIMER: INCBIN "SB_TIME.C",176 SB_BONE_ITEM: INCBIN "BONEICON.C",72 SB_KEY_ITEM: INCBIN "KEY_ICON.C",72 SB_LIGHT_ITEM: INCBIN "LIGHTICN.C",72 SB_FLOWERS_ITEM:INCBIN "FLWRSICN.C",72 FIRST_FREE_BYTE: DB #00
; A103177: (7*3^n + 2n + 5)/4. ; 3,7,18,50,145,429,1280,3832,11487,34451,103342,310014,930029,2790073,8370204,25110596,75331771,225995295,677985866,2033957578,6101872713,18305618117,54916854328,164750562960,494251688855,1482755066539 mov $1,$0 seq $1,237930 ; a(n) = 3^(n+1) + (3^n-1)/2. add $0,$1 sub $0,3 div $0,2 add $0,3
; A169176: Number of reduced words of length n in Coxeter group on 19 generators S_i with relations (S_i)^2 = (S_i S_j)^27 = I. ; Submitted by Jamie Morken(s4) ; 1,19,342,6156,110808,1994544,35901792,646232256,11632180608,209379250944,3768826516992,67838877305856,1221099791505408,21979796247097344,395636332447752192,7121453984059539456 mov $1,$0 mov $0,1 mov $2,18 pow $2,$1 mul $0,$2 div $0,18 add $2,$0 mov $0,$2
/* * DrawingHelpers.cpp * * Created on: May 31, 2016 * Author: hatem */ #include "op_simu/DrawingHelpers.h" #include <stdarg.h> #include <stdio.h> #include <cmath> #include "op_utility/UtilityH.h" #include "op_planner/PlanningHelpers.h" #include <GL/freeglut.h> using namespace std; using namespace PlannerHNS; using namespace UtilityHNS; namespace Graphics { DrawingHelpers::DrawingHelpers() { // TODO Auto-generated constructor stub } DrawingHelpers::~DrawingHelpers() { // TODO Auto-generated destructor stub } void DrawingHelpers::DrawString(float x, float y, GLvoid* font_style, char* format, ...) { glDisable(GL_LIGHTING); va_list args; char buffer[1000], *s; va_start(args, format); vsprintf(buffer, format, args); va_end(args); //GLuint ox = x; GLuint oy = y; glRasterPos2f(x, y); for (s = buffer; *s; s++) { if(*s == ',') { x += 220; y = oy; glRasterPos2f(x, y); continue; } else if(*s == '\n') { y+=12; glRasterPos2f(x, y); continue; } glutBitmapCharacter(font_style, *s); } glEnable(GL_LIGHTING); } void DrawingHelpers::DrawGrid(const double& x, const double& y, const double& w, const double& h, const double& cell_l) { glPushMatrix(); int nVerticalLisne = floor(w/cell_l); int nHorizontalLines = floor(h/cell_l); glBegin(GL_LINES); glColor3ub(210,210,210); double incr = y; for(int r=0; r<= nHorizontalLines; r++) { glNormal3f(1.0, 1.0, 1.0); glVertex3f(x, incr, 0); glVertex3f(x+w, incr, 0); incr+=cell_l; } double incc = x; for(int r=0; r<= nVerticalLisne; r++) { glNormal3f(1.0, 1.0, 1.0); glVertex3f(incc, y, 0); glVertex3f(incc, y + h, 0); incc+=cell_l; } glEnd(); glPopMatrix(); } void DrawingHelpers::DrawArrow(const double& x, const double& y, const double& a) { const int nSlicesStacks = 50; const double percent = 20.0; const double innerPercent = 15.0; double half_length = 10/2.0; glPushMatrix(); //Draw one cylender and cone glTranslated(x, y, 0.5); glRotated(a*RAD2DEG, 0,0,1); //X Axis glPushMatrix(); glColor3ub(200,200,200); glRotated(90, 0,1,0); glutSolidCylinder(half_length/percent, half_length,nSlicesStacks,nSlicesStacks); glTranslated(0,0,half_length); glColor3f(1,1,0); glutSolidCone(half_length/innerPercent, half_length/innerPercent,nSlicesStacks,nSlicesStacks); glPopMatrix(); glPopMatrix(); } void DrawingHelpers::DrawCustomOrigin(const double& x, const double& y, const double& z, const int& yaw, const int& roll, const int& pitch, const double& length) { const int nSlicesStacks = 50; const double percent = 20.0; const double innerPercent = 15.0; double half_length = length/2.0; glPushMatrix(); //Draw one cylender and cone glTranslated(x, y, z); glRotated(yaw, 0,0,1); glRotated(roll, 1,0,0); glRotated(pitch, 0,1,0); //Z Axis glPushMatrix(); glColor3f(0.65,0.65,0.65); glutSolidCylinder(half_length/percent, half_length,nSlicesStacks,nSlicesStacks); glTranslated(0,0,half_length); glColor3f(0,0,1); glutSolidCone(half_length/innerPercent, half_length/innerPercent,nSlicesStacks,nSlicesStacks); glPopMatrix(); //X Axis glPushMatrix(); glColor3f(0.65,0.65,0.65); glRotated(90, 0,1,0); glutSolidCylinder(half_length/percent, half_length,nSlicesStacks,nSlicesStacks); glTranslated(0,0,half_length); glColor3f(1,1,0); glutSolidCone(half_length/innerPercent, half_length/innerPercent,nSlicesStacks,nSlicesStacks); glPopMatrix(); // //Y Axis glPushMatrix(); glColor3f(0.65,0.65,0.65); glRotated(90, 1,0,0); glutSolidCylinder(half_length/percent, half_length, nSlicesStacks, nSlicesStacks); glTranslated(0,0,half_length); glColor3f(1,0,0); glutSolidCone(half_length/innerPercent, half_length/innerPercent, nSlicesStacks,nSlicesStacks); glPopMatrix(); //glDisable(GL_LIGHTING); glPopMatrix(); } vector<vector<float> > DrawingHelpers::PreparePathForDrawing(const std::vector<PlannerHNS::WayPoint>& path, std::vector<std::vector<PlannerHNS::WayPoint> >& redyForDraw, double w, double resolution) { vector<vector<float> > colorProfiles; if(path.size() < 2) return colorProfiles; int size = path.size(); WayPoint p1 = path[0]; WayPoint p2 =p1; WayPoint prev_point = p1; WayPoint center, prev_center ,pa, pb, pc, pd; double a = 0; double prev_angle = 0; vector<WayPoint> four_temp; vector<float> color_vector; for(int i=0; i < size ; i++) { color_vector.clear(); four_temp.clear(); pa = p2 = path[i]; color_vector.push_back(p1.v/12.0); color_vector.push_back(p1.v/12.0); color_vector.push_back(p1.v/12.0); colorProfiles.push_back(color_vector); if(distance2points(p1.pos, p2.pos) < resolution) continue; center.pos.x = p1.pos.x + (p2.pos.x-p1.pos.x)/2.0; center.pos.y = p1.pos.y + (p2.pos.y-p1.pos.y)/2.0; a = atan2(p2.pos.y- p1.pos.y, p2.pos.x- p1.pos.x); pa.pos.x = p1.pos.x - w * cos(a - M_PI/2.0); pa.pos.y = p1.pos.y - w * sin(a - M_PI/2.0); pa.pos.z = p1.pos.z; pb.pos.x = p1.pos.x + w * cos(a - M_PI/2.0); pb.pos.y = p1.pos.y + w * sin(a - M_PI/2.0); pb.pos.z = p1.pos.z; pc.pos.x = p2.pos.x + w * cos(a - M_PI/2.0); pc.pos.y = p2.pos.y + w * sin(a - M_PI/2.0); pc.pos.z = p2.pos.z; pd.pos.x = p2.pos.x - w * cos(a - M_PI/2.0); pd.pos.y = p2.pos.y - w * sin(a - M_PI/2.0); pd.pos.z = p2.pos.z; if(!(prev_point.pos.x == p1.pos.x && prev_point.pos.y == p1.pos.y)) { prev_angle = atan2(p1.pos.y- prev_point.pos.y, p1.pos.x- prev_point.pos.x); pa.pos.x = p1.pos.x - w * cos(prev_angle - M_PI/2.0); pa.pos.y = p1.pos.y - w * sin(prev_angle - M_PI/2.0); pb.pos.x = p1.pos.x + w * cos(prev_angle - M_PI/2.0); pb.pos.y = p1.pos.y + w * sin(prev_angle - M_PI/2.0); } four_temp.push_back(pa); four_temp.push_back(pb); four_temp.push_back(pc); four_temp.push_back(pd); redyForDraw.push_back(four_temp); prev_point = p1; p1 = p2; } return colorProfiles; } void DrawingHelpers::DrawPrePreparedPolygons(std::vector<std::vector<PlannerHNS::WayPoint> >& path, double z, float color[3],int nSkipPoints, const std::vector<std::vector<float> >* colorProfile) { if(!colorProfile) glColor3f(color[0], color[1], color[2]); for(unsigned int i=0; i< path.size(); i+=nSkipPoints) { if(path[i].size() == 4) { if(path[i][0].pLane && (path[i][0].pLane->pRightLane || path[i][0].pLane->pLeftLane)) glColor3f(1, 0, 0); else if(colorProfile) { glColor3f(color[0]*(*colorProfile)[i][0], color[1] * (*colorProfile)[i][1], color[2] * (*colorProfile)[i][2]); } glBegin(GL_POLYGON); glNormal3f(0.0, 0.0, 0.1); // glVertex3f(path[i][0].p.x, path[i][0].p.y,path[i][0].p.z+z); // glVertex3f(path[i][1].p.x, path[i][1].p.y,path[i][1].p.z+z); // glVertex3f(path[i][2].p.x, path[i][2].p.y,path[i][2].p.z+z); // glVertex3f(path[i][3].p.x, path[i][3].p.y,path[i][3].p.z+z); glVertex3f(path[i][0].pos.x, path[i][0].pos.y,z); glVertex3f(path[i][1].pos.x, path[i][1].pos.y,z); glVertex3f(path[i][2].pos.x, path[i][2].pos.y,z); //glVertex3f((path[i][2].p.x+path[i][1].p.x)/2.0, (path[i][2].p.y+path[i][1].p.y)/2.0,z); glVertex3f(path[i][3].pos.x, path[i][3].pos.y,z); glEnd(); } } } void DrawingHelpers::DrawCostPath(const std::vector<PlannerHNS::WayPoint*>& path_points, const double& z, const double& width) { if(path_points.size()==0) return; WayPoint p1 = *path_points[0]; float color[3] = {0,0,0}; double max_cost = 0; for(unsigned int i=0; i < path_points.size(); i++) { if(path_points.at(i)->cost > max_cost) max_cost = path_points.at(i)->cost; } int size = path_points.size(); for(int i=0; i < size; i++) { p1 = *path_points[i]; double norm_cost = path_points.at(i)->cost / max_cost * 2.0; if(norm_cost <= 1.0) { color[0] = norm_cost; color[1] = 1.0; } else if(norm_cost > 1.0) { color[0] = 1.0; color[1] = 2.0 - norm_cost; } glColor3f(color[0], color[1], color[2]); //DrawLinePoygonFromCenterX(p1, z, p2, z, width, 0, prev_point); DrawWideEllipse(p1.pos.x, p1.pos.y, z, 0.5, 0.5, 0.25, color); } } void DrawingHelpers::DrawWidePath(const std::vector<PlannerHNS::WayPoint>& path_points, const double& z, const double& width, float color[3], bool bGadient) { if(path_points.size()==0) return; WayPoint p1 = path_points[0]; WayPoint p2 = p1; float localColor[3] = {color[0],color[1],color[2]}; int size = path_points.size(); WayPoint prev_point = p1; for(int i=1; i < size; i+=2) { p2 = path_points[i]; if(bGadient) { localColor[0] = color[0] * (float)(i+20)*3/(float)size; localColor[1] = color[1] * (float)(i+20)*3/(float)size; localColor[2] = color[2] * (float)(i+20)*3/(float)size; } if(p2.bDir == BACKWARD_DIR) glColor3f(1,0, 0); else glColor3f(localColor[0],localColor[1],localColor[2]); DrawLinePoygonFromCenterX(p1, z, p2, z, width, 0, prev_point); prev_point = p1; p1 = p2; } } void DrawingHelpers::DrawLinePoygonline(const PlannerHNS::GPSPoint& p1, const PlannerHNS::GPSPoint& p2, const double& w) { GPSPoint center, prev_center ,pa, pb, pc, pd, prev_pa,prev_pb; double a = 0; center.x = p1.x + (p2.x-p1.x)/2.0; center.y = p1.y + (p2.y-p1.y)/2.0; a = atan2(p2.y- p1.y, p2.x- p1.x); pa.x = p1.x - w * cos(a - M_PI/2.0); pa.y = p1.y - w * sin(a - M_PI/2.0); pb.x = p1.x + w * cos(a - M_PI/2.0); pb.y = p1.y + w * sin(a - M_PI/2.0); pc.x = p2.x + w * cos(a - M_PI/2.0); pc.y = p2.y + w * sin(a - M_PI/2.0); pd.x = p2.x - w * cos(a - M_PI/2.0); pd.y = p2.y - w * sin(a - M_PI/2.0); glBegin(GL_POLYGON); glNormal3f(0.1, 0.1, 0.1); glVertex3f(pa.x, pa.y, p1.z); glVertex3f(pb.x, pb.y, p1.z); glVertex3f(pc.x, pc.y, p2.z); glVertex3f(pd.x, pd.y, p2.z); glEnd(); } void DrawingHelpers::DrawLinePoygonFromCenterX(const PlannerHNS::WayPoint& p1, const double& z, const PlannerHNS::WayPoint& p2, const double& z2, const double& w, const double& h, PlannerHNS::WayPoint& prev_point) { GPSPoint center, prev_center ,pa, pb, pc, pd, prev_pa,prev_pb; double a = 0; double prev_angle = 0; center.x = p1.pos.x + (p2.pos.x-p1.pos.x)/2.0; center.y = p1.pos.y + (p2.pos.y-p1.pos.y)/2.0; a = atan2(p2.pos.y- p1.pos.y, p2.pos.x- p1.pos.x); pa.x = p1.pos.x - w * cos(a - M_PI/2.0); pa.y = p1.pos.y - w * sin(a - M_PI/2.0); pb.x = p1.pos.x + w * cos(a - M_PI/2.0); pb.y = p1.pos.y + w * sin(a - M_PI/2.0); pc.x = p2.pos.x + w * cos(a - M_PI/2.0); pc.y = p2.pos.y + w * sin(a - M_PI/2.0); pd.x = p2.pos.x - w * cos(a - M_PI/2.0); pd.y = p2.pos.y - w * sin(a - M_PI/2.0); if(!(prev_point.pos.x == p1.pos.x && prev_point.pos.y == p1.pos.y)) { prev_angle = atan2(p1.pos.y- prev_point.pos.y, p1.pos.x- prev_point.pos.x); pa.x = p1.pos.x - w * cos(prev_angle - M_PI/2.0); pa.y = p1.pos.y - w * sin(prev_angle - M_PI/2.0); pb.x = p1.pos.x + w * cos(prev_angle - M_PI/2.0); pb.y = p1.pos.y + w * sin(prev_angle - M_PI/2.0); } glBegin(GL_POLYGON); glNormal3f(0.1, 0.1, 0.1); glVertex3f(pa.x, pa.y,z); glVertex3f(pb.x, pb.y, z); glVertex3f(pc.x, pc.y,z); glVertex3f(pd.x, pd.y, z); glEnd(); } void DrawingHelpers::DrawCustomCarModel(const PlannerHNS::WayPoint& pose,const double& steeringAngle, const std::vector<PlannerHNS::GPSPoint>& carPoints,float color[3], const double& angleFix) { if(carPoints.size() == 4) { double z_margin = 0.05; glPushMatrix(); glTranslated(pose.pos.x, pose.pos.y, pose.pos.z); glRotated(pose.pos.a*RAD2DEG + angleFix, 0,0,1); for(unsigned int i = 0; i < 4; i++) { glBegin(GL_LINE_STRIP); //glColor3f(0,1,1); glColor3f(color[0],color[1],color[2]); glVertex3f(carPoints[i].x, carPoints[i].y, carPoints[i].z); glVertex3f(carPoints[i].x, carPoints[i].y, carPoints[i].z+1); glEnd(); } glBegin(GL_POLYGON); //glColor3f(0,0,1); glColor3f(color[0],color[0],color[2]); glVertex3f(carPoints[0].x, carPoints[0].y, carPoints[0].z+z_margin); glVertex3f(carPoints[1].x, carPoints[1].y, carPoints[1].z+z_margin); glVertex3f(carPoints[2].x, carPoints[2].y, carPoints[2].z+z_margin); glVertex3f(carPoints[3].x, carPoints[3].y, carPoints[3].z+z_margin); glVertex3f(carPoints[0].x, carPoints[0].y, carPoints[0].z+z_margin); glVertex3f(carPoints[0].x, carPoints[0].y, carPoints[0].z+z_margin); glVertex3f(carPoints[2].x, carPoints[2].y, carPoints[2].z+z_margin); glVertex3f(carPoints[1].x, carPoints[1].y, carPoints[1].z+z_margin); glVertex3f(carPoints[3].x, carPoints[3].y, carPoints[3].z+z_margin); glEnd(); glBegin(GL_LINE_LOOP); glColor3f(color[0],color[0],color[2]); glVertex3f(carPoints[0].x, carPoints[0].y, carPoints[0].z+1); glVertex3f(carPoints[1].x, carPoints[1].y, carPoints[1].z+1); glVertex3f(carPoints[2].x, carPoints[2].y, carPoints[2].z+1); glVertex3f(carPoints[3].x, carPoints[3].y, carPoints[3].z+1); glVertex3f(carPoints[0].x, carPoints[0].y, carPoints[0].z+1); glVertex3f(carPoints[0].x, carPoints[0].y, carPoints[0].z+1); glVertex3f(carPoints[2].x, carPoints[2].y, carPoints[2].z+1); glVertex3f(carPoints[1].x, carPoints[1].y, carPoints[1].z+1); glVertex3f(carPoints[3].x, carPoints[3].y, carPoints[3].z+1); glEnd(); double width = fabs(carPoints[0].x - carPoints[2].x); double length = fabs(carPoints[0].y - carPoints[2].y); double innerRad = 1.0; double scale_factor = 0.1; glColor3f(0.05,0.05,0.05); glPushMatrix(); glTranslated(width/2.0,length/2.0 - 0.5,0); glScaled(scale_factor, scale_factor, scale_factor); glRotated(90, 0,0,1); glRotated(90, 1,0,0); glutSolidTorus(innerRad, 3.0, 20, 20); glPopMatrix(); glPushMatrix(); glTranslated(-width/2.0,length/2.0 - 0.5,0); glScaled(scale_factor, scale_factor, scale_factor); glRotated(90, 0,0,1); glRotated(90, 1,0,0); glutSolidTorus(innerRad, 3.0, 20, 20); glPopMatrix(); glPushMatrix(); glTranslated(width/2.0,-length/2.0 + 0.5,0); glScaled(scale_factor, scale_factor, scale_factor); glRotated(90+steeringAngle*RAD2DEG, 0,0,1); glRotated(90, 1,0,0); glutSolidTorus(innerRad, 3.0, 20, 20); glPopMatrix(); glPushMatrix(); glTranslated(-width/2.0,-length/2.0 + 0.5,0); glScaled(scale_factor, scale_factor, scale_factor); glRotated(90+steeringAngle*RAD2DEG, 0,0,1); glRotated(90, 1,0,0); glutSolidTorus(innerRad, 3.0, 20, 20); glPopMatrix(); glPopMatrix(); } DrawCustomOrigin(pose.pos.x, pose.pos.y, pose.pos.z, pose.pos.a*RAD2DEG, 0,0, 2); } GLMmodel* DrawingHelpers::LoadModel(const char* fileName) { GLMmodel* pmodel = glmReadOBJ((char*)fileName); if (!pmodel) exit(0); glmUnitize(pmodel); glmFacetNormals(pmodel); glmVertexNormals(pmodel, 90.0); return pmodel; } void DrawingHelpers::DrawModel(GLMmodel* pmod,double length, double width, double height, double x, double y,double z, double heading, double pitch , double roll ) { if (pmod) { if(!glIsEnabled(GL_LIGHTING)) glEnable(GL_LIGHTING); glPushMatrix(); glTranslated(x,y,z); glRotated(heading*RAD2DEG,0.0, 0.0, 1.0); glRotated(pitch*RAD2DEG,0.0, 1.0, 0.0); glRotated(roll*RAD2DEG,1.0, 0.0, 0.0); glScaled(length, width, height); glmDraw(pmod, GLM_FLAT | GLM_MATERIAL ); glPopMatrix(); glDisable(GL_LIGHTING); } } void DrawingHelpers::DrawFilledEllipse(float x, float y, float z, float width, float height) { glDisable(GL_LIGHTING); glBegin(GL_TRIANGLE_FAN); //All triangles fan out starting with this point glVertex3f (x,y,z); for (float i = 0; i <=M_PI*2*RAD2DEG; i+=0.1) { glVertex3f(x + width*cos(i), y+height*sin(i), z); } glEnd(); glEnable(GL_LIGHTING); } void DrawingHelpers::DrawWideEllipse(float x, float y, float z, float outer_width, float outer_height, float inner_width,float color[3]) { //std::vector<WayPoint> ellipse_points; glColor3f(color[0], color[1], color[2]); GPSPoint p1 = GPSPoint(x + outer_width*cos(0),y + outer_height*sin(0),z,0); GPSPoint p2 = p1; for (float i = 0.1; i <= M_PI*2 + 0.1; i+=0.1) { //ellipse_points.push_back(WayPoint(x + outer_width*cos(i), y+outer_height*sin(i), z, 0)); p2.x = x + outer_width*cos(i); p2.y = y + outer_height*sin(i); p2.z = z; DrawLinePoygonline(p1,p2, outer_width - inner_width); p1 = p2; } //DrawWidePath(ellipse_points, z, outer_width - inner_width,color); } void DrawingHelpers::DrawSimpleEllipse(float x, float y, float z, float outer_width, float outer_height) { glBegin(GL_LINE_STRIP); for (float jj = 0; jj <=M_PI*2.0; jj+=0.1) { glVertex3f(x + outer_width*cos(jj), y+ outer_height*sin(jj),z); } glEnd(); } void DrawingHelpers::DrawPedal(float x, float y, float z, float width, float height, float inner_height, float color[3]) { GPSPoint pa, pb, pc, pd; double w2 = width/2.0; double h2 = height/2.0; pa.x = x - w2; pa.y = y - h2; pb.x = x + w2; pb.y = y - h2; pc.x = x + w2; pc.y = y + h2; pd.x = x - w2; pd.y = y + h2; glBegin(GL_LINE_LOOP); glVertex3f(pa.x, pa.y, z); glVertex3f(pb.x, pb.y, z); glVertex3f(pc.x, pc.y, z); glVertex3f(pd.x, pd.y, z); glEnd(); GPSPoint p1(x, y + h2, z, 0); GPSPoint p2(x, y + h2 - inner_height, z, 0); glColor3f(color[0], color[1], color[2]); DrawLinePoygonline(p1,p2,w2); } } /* namespace Graphics */
; A020336: Numbers whose base-8 representation is the juxtaposition of two identical strings. ; 9,18,27,36,45,54,63,520,585,650,715,780,845,910,975,1040,1105,1170,1235,1300,1365,1430,1495,1560,1625,1690,1755,1820,1885,1950,2015,2080,2145,2210,2275,2340,2405,2470,2535,2600,2665,2730,2795,2860,2925,2990,3055 mov $1,1 mov $2,$0 add $2,2 mov $3,3 mov $5,$0 add $0,1 lpb $0 sub $0,4 add $1,$0 add $2,3 trn $2,$1 mov $0,$2 add $4,$3 mov $3,$1 add $4,$1 mul $4,2 mov $1,$4 add $1,$4 add $3,$1 mov $4,$1 lpe mov $1,4 sub $3,1 add $1,$3 lpb $5 add $1,9 sub $5,1 lpe add $1,3
TITLE PRACTICE PROBLEM 9 .MODEL SMALL .DATA STR1 DB 'Enter 3 single digit umbers: $' STR2 DB 'Sum = $' .CODE MAIN PROC MOV DX, @DATA MOV DS, DX LEA DX, STR1 ;1st string MOV AH, 9 INT 21h MOV AH,1 ;1st input INT 21h MOV CH, AL MOV AH,1 ;2nd input INT 21h ADD CH, AL SUB CH, '0' MOV AH,1 ;3rd input INT 21h ADD CH, AL SUB CH, '0' MOV CL, CH MOV AH, 2 ;new line MOV DL, 0Dh INT 21h MOV DL, 0Ah INT 21h LEA DX, STR2 ;2nd string MOV AH, 9 INT 21h MOV AH, 2 ;PRINTING SUM MOV DL, CL INT 21h MOV AH, 4Ch ;RETURN INT 21h MAIN ENDP END MAIN
; A315511: Coordination sequence Gal.4.139.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,6,11,17,21,27,32,38,44,49,55,59,65,70,76,82,87,93,97,103,108,114,120,125,131,135,141,146,152,158,163,169,173,179,184,190,196,201,207,211,217,222,228,234,239,245,249,255,260,266 mov $3,$0 lpb $0,1 add $1,$0 lpb $0,1 sub $0,7 sub $1,1 lpe mod $0,2 add $1,$0 div $1,2 sub $1,1 lpe add $1,1 mov $2,$3 mul $2,5 add $1,$2
[ BITS 32 ] [ ORG 0x0 ] VidBuffer equ 0x200*(1+3) KeyPress equ VidBuffer+80*25*2 INFO: .Entrypoint: dd 0x200 .Vidbuffer: dd VidBuffer .Keypress: dd KeyPress .Stack: dd KeyPress+0x500 times 512-($-$$) db 0 Game: sub bx, 8 mov ds, bx .DrawUI: mov edi, VidBuffer+80*2*2 mov ecx, 80 .DrawUI.Loop1: mov byte [edi], '=' mov byte [edi+1], 0x0f inc edi inc edi loop .DrawUI.Loop1 xchg bx, bx mov edi, VidBuffer+80*2*(8+3)+(40-5)*2 mov ah, 0xF0 mov esi, SnakeText .DrawUI.Loop2: mov al, [esi] cmp al, 0 jz .DrawUI.PostLoop2 mov [edi], ax inc esi inc edi inc edi jmp .DrawUI.Loop2 .DrawUI.PostLoop2: add edi, 80*2-5*2-21*2 mov ah, 0x0F mov esi, SnakeHelp .DrawUI.Loop3: mov al, [esi] cmp al, 0 jz .DrawUI.PostLoop3 mov [edi], ax inc esi inc edi inc edi jmp .DrawUI.Loop3 .DrawUI.PostLoop3: mov byte [KeyPress], 0 mov ecx, 1 int 0x30 cmp byte [KeyPress], 0x39 je .StartGame cmp byte [KeyPress], 0x10 jne .DrawUI.PostLoop3 mov ecx, 4 int 0x30 ; exit iret ; if failed, crash .StartGame: mov al, [KeyPress] mov ah, [KeyPress] mov [Random], ax mov word [HeadX], (40)+(11<<(1*8)) mov word [EndX], (40)+(8<<(1*8)) mov word [FoodX], 0 mov byte [Length], 3 mov byte [HeadDirection], 1 mov edi, VidBuffer+80*2*3 mov ecx, 80*(25-3) .DrawUI.ClearLoop: mov word [edi], 0 inc edi inc edi loop .DrawUI.ClearLoop mov edi, VidBuffer+80*2*(8+3)+40*2 mov cx, 0xAA02 mov word [edi], cx add edi, 80*2 mov word [edi], cx add edi, 80*2 mov word [edi], cx .Main: mov byte [KeyPress], 0 mov ecx, 1 int 0x30 cmp byte [KeyPress], 0 jnz .keyPressed inc byte [CountOfCycles] .Move: mov al, [CountOfCycles] cmp al, 100 jl .Main cmp byte [FoodX], 0 jnz .Move.CheckFood mov al, [Random] cmp al, 80 jb .Move.FoodXSelected mov bl, 80 div bl .Move.FoodXSelected: mov byte [FoodX], ah mov dl, [Random+1] cmp dl, 21 jb .Move.FoodYSelected mov bx, 21 mov al, dl xor edx, edx div bx .Move.FoodYSelected: mov byte [FoodY], dl mov edi, VidBuffer xor eax, eax xor ebx, ebx mov al, [FoodY] add al, 3 mov cl, 80 mul cl mov bl, [FoodX] add ax, bx shl ax, 1 add di, ax mov word [edi], 0xEE00 .Move.CheckFood: mov al, [HeadX] cmp [FoodX], al jne .Move.DrawSegment mov al, [HeadY] cmp [FoodY], al jne .Move.DrawSegment inc byte [Length] mov byte [FoodX], 0 .Move.DrawSegment: xchg bx, bx mov byte [CountOfCycles], 0 mov edi, VidBuffer xor eax, eax xor ebx, ebx mov al, [HeadY] add al, 3 mov cl, 80 mul cl mov bl, [HeadX] add ax, bx shl ax, 1 add di, ax mov al, [HeadDirection] mov byte [edi], al mov byte [edi+1], 0xAA mov al, [HeadDirection] test byte [HeadDirection], 1 jnz .Move.Horiz .Move.Vert: test al, 2 jz .Move.Vert.1 cmp byte [HeadY], 21 je .Move.Vert.1 inc byte [HeadY] .Move.Vert.1: test al, 2 jnz .Move.Vert.2 cmp byte [HeadY], 0 je .Move.Vert.2 dec byte [HeadY] .Move.Vert.2: jmp .Move.CheckSnake .Move.Horiz: test al, 2 jz .Move.Horiz.1 cmp byte [HeadX], 0 je .Move.Horiz.1 dec byte [HeadX] .Move.Horiz.1: test al, 2 jnz .Move.Horiz.2 cmp byte [HeadX], 79 je .Move.Horiz.2 inc byte [HeadX] .Move.Horiz.2: .Move.CheckSnake: mov bh, 0 mov al, [HeadY] add al, 3 mov bl, 80 mul bl mov bh, 0 mov bl, [HeadX] add ax, bx and eax, 0x0000FFFF shl eax, 1 add eax, VidBuffer cmp byte [eax+1], 0xAA je .GameOver .DeleteEnd: mov edi, VidBuffer xor eax, eax xor ebx, ebx mov al, [EndY] add al, 3 mov cl, 80 mul cl mov bl, [EndX] add ax, bx shl ax, 1 add di, ax mov al, [edi] mov byte [edi+1], 0x00 cmp byte [HeadDirection], 1 jl .DeleteEnd.Check1 je .DeleteEnd.Check2 cmp byte [HeadDirection], 4 jl .DeleteEnd.Check3 je .DeleteEnd.Check4 .DeleteEnd.Check1: cmp byte [HeadY], 0 jne .DeleteEnd.Exec jmp .Main .DeleteEnd.Check2: cmp byte [HeadX], 79 jne .DeleteEnd.Exec jmp .Main .DeleteEnd.Check3: cmp byte [HeadX], 24-3 jne .DeleteEnd.Exec jmp .Main .DeleteEnd.Check4: cmp byte [HeadX], 0 jne .DeleteEnd.Exec jmp .Main .DeleteEnd.Exec: test byte [edi], 1 jnz .DeleteEnd.Horiz .DeleteEnd.Vert: and ax, 2 add [EndY], al dec byte [EndY] jmp .Main .DeleteEnd.Horiz: and ax, 2 sub [EndX], al inc byte [EndX] jmp .Main .keyPressed: xor ebx, ebx mov bl, [CountOfCycles] mov al, [KeyPress] cmp al, 0x11 je .keyPressed.W cmp al, 0x1E je .keyPressed.A cmp al, 0x1F je .keyPressed.S cmp al, 0x20 je .keyPressed.D cmp al, 0x10 jne .Main .keyPressed.Q: mov ecx, 4 jmp .DrawUI .keyPressed.W: mov byte [HeadDirection], 0 cmp word [Random], 0 jp .keyPressed.W.1 add word [Random], bx jmp .keyPressed.ClearPressed .keyPressed.W.1: ror word [Random], 1 jmp .keyPressed.ClearPressed .keyPressed.A: mov byte [HeadDirection], 3 cmp word [Random], 0 jp .keyPressed.A.1 sub word [Random], bx jmp .keyPressed.ClearPressed .keyPressed.A.1: rol word [Random], 1 jmp .keyPressed.ClearPressed .keyPressed.S: mov byte [HeadDirection], 2 cmp word [Random], 0 jp .keyPressed.S.1 rol word [Random], 2 jmp .keyPressed.ClearPressed .keyPressed.S.1: sub word [Random], bx jmp .keyPressed.ClearPressed .keyPressed.D: mov byte [HeadDirection], 1 cmp word [Random], 0 jp .keyPressed.D.1 add word [Random], bx jmp .keyPressed.ClearPressed .keyPressed.D.1: ror word [Random], 2 .keyPressed.ClearPressed: jmp .Main .GameOver: mov edi, VidBuffer+80*2*(8+3)+(40-5)*2 mov ah, 0xF4 mov esi, SnakeGameOver .GameOver.Loop: mov al, [esi] cmp al, 0 jz .GameOver.PostLoop mov [edi], ax inc esi inc edi inc edi jmp .GameOver.Loop .GameOver.PostLoop: mov ecx, 1 int 0x30 cmp byte [KeyPress], 0x10 jne .GameOver.PostLoop jmp .DrawUI CountOfCycles: db 0 HeadX: db 40 HeadY: db 11 EndX: db 40 EndY: db 8 FoodX: db 0 FoodY: db 0 SnakeText: db 'SNAKE 0.2', 0 SnakeHelp: db 'Spacebar to begin, q to quit, WASD to move', 0 SnakeGameOver: db 'GAME OVER', 0 Random: dw 0 ; 010 000 000 000 HeadDirection: db 1 ; --> 000 - 0 001 - 1 000 - 2 100 - 3 Length: db 3 ; 000 000 010 000 Score: dd 0 times 512*3-($-Game) db 0
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: jmarantz@google.com (Joshua Marantz) // Unit-test CacheBatcher, using LRUCache, AsyncCache, and DelayCache. #include "pagespeed/kernel/cache/cache_batcher.h" #include <cstddef> #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/statistics.h" #include "pagespeed/kernel/base/thread_system.h" #include "pagespeed/kernel/base/timer.h" #include "pagespeed/kernel/cache/async_cache.h" #include "pagespeed/kernel/cache/cache_batcher_testing_peer.h" #include "pagespeed/kernel/cache/cache_test_base.h" #include "pagespeed/kernel/cache/delay_cache.h" #include "pagespeed/kernel/cache/lru_cache.h" #include "pagespeed/kernel/cache/threadsafe_cache.h" #include "pagespeed/kernel/cache/write_through_cache.h" #include "pagespeed/kernel/thread/queued_worker_pool.h" #include "pagespeed/kernel/thread/worker_test_base.h" #include "pagespeed/kernel/util/platform.h" #include "pagespeed/kernel/util/simple_stats.h" namespace { const size_t kMaxSize = 100; const int kMaxWorkers = 2; } namespace net_instaweb { class CacheBatcherTest : public CacheTestBase { protected: CacheBatcherTest() : expected_pending_(0) { thread_system_.reset(Platform::CreateThreadSystem()); statistics_.reset(new SimpleStats(thread_system_.get())); CacheBatcher::InitStats(statistics_.get()); lru_cache_.reset(new LRUCache(kMaxSize)); timer_.reset(thread_system_->NewTimer()); pool_.reset( new QueuedWorkerPool(kMaxWorkers, "cache", thread_system_.get())); threadsafe_cache_.reset(new ThreadsafeCache( lru_cache_.get(), thread_system_->NewMutex())); async_cache_.reset(new AsyncCache(threadsafe_cache_.get(), pool_.get())); delay_cache_.reset(new DelayCache(async_cache_.get(), thread_system_.get())); // Note: it is each test's responsibility to reset batcher_ with the backend // and options that it needs. set_mutex(thread_system_->NewMutex()); } // Make sure we shut down the worker pool prior to destructing AsyncCache. virtual void TearDown() { pool_->ShutDown(); } class SyncPointCallback : public CacheTestBase::Callback { public: explicit SyncPointCallback(CacheBatcherTest* test) : Callback(test), sync_point_(test->thread_system_.get()) { } virtual void Done(CacheInterface::KeyState state) { Callback::Done(state); sync_point_.Notify(); } virtual void Wait() { sync_point_.Wait(); } private: WorkerTestBase::SyncPoint sync_point_; }; virtual CacheInterface* Cache() { return batcher_.get(); } virtual Callback* NewCallback() { return new SyncPointCallback(this); } void ChangeBatcherConfig(const CacheBatcher::Options& options, CacheInterface* cache) { batcher_.reset(new CacheBatcher(options, cache, thread_system_->NewMutex(), statistics_.get())); } // After the Done() callback is be called, there is a slight delay // in the worker thread before the CacheBatcher knows it can // schedule another lookup. To test the sequences we want, wait // till the batcher catches up with our expectations. virtual void PostOpCleanup() { while ((num_in_flight_keys() != expected_pending_) || (async_cache_->outstanding_operations() != 0)) { timer_->SleepMs(1); } } void DelayKey(const GoogleString& key) { delay_cache_->DelayKey(key); ++expected_pending_; } void ReleaseKey(const GoogleString& key) { delay_cache_->ReleaseKey(key); --expected_pending_; } int num_in_flight_keys() { return peer_.num_in_flight_keys(batcher_.get()); } int LastBatchSize() { return peer_.last_batch_size(batcher_.get()); } scoped_ptr<LRUCache> lru_cache_; scoped_ptr<ThreadSystem> thread_system_; scoped_ptr<ThreadsafeCache> threadsafe_cache_; scoped_ptr<Timer> timer_; scoped_ptr<QueuedWorkerPool> pool_; scoped_ptr<AsyncCache> async_cache_; scoped_ptr<DelayCache> delay_cache_; scoped_ptr<SimpleStats> statistics_; scoped_ptr<CacheBatcher> batcher_; CacheBatcherTestingPeer peer_; int expected_pending_; }; // In this version, no keys are delayed, so the batcher has no opportunity // to batch. This test is copied from lru_cache_test.cc. Note that we are // going through the CacheBatcher/Delay/AsyncCache/ThreadsafeCache but the // LRUCache should be quiescent every time we look directly at it. TEST_F(CacheBatcherTest, PutGetDelete) { ChangeBatcherConfig(CacheBatcher::Options(), delay_cache_.get()); EXPECT_EQ(static_cast<size_t>(0), lru_cache_->size_bytes()); EXPECT_EQ(static_cast<size_t>(0), lru_cache_->num_elements()); CheckPut("Name", "Value"); CheckGet("Name", "Value"); EXPECT_EQ(static_cast<size_t>(9), lru_cache_->size_bytes()); EXPECT_EQ(static_cast<size_t>(1), lru_cache_->num_elements()); CheckNotFound("Another Name"); CheckPut("Name", "NewValue"); CheckGet("Name", "NewValue"); EXPECT_EQ(static_cast<size_t>(12), lru_cache_->size_bytes()); EXPECT_EQ(static_cast<size_t>(1), lru_cache_->num_elements()); CheckDelete("Name"); lru_cache_->SanityCheck(); CheckNotFound("Name"); EXPECT_EQ(static_cast<size_t>(0), lru_cache_->size_bytes()); EXPECT_EQ(static_cast<size_t>(0), lru_cache_->num_elements()); lru_cache_->SanityCheck(); } TEST_F(CacheBatcherTest, DelayN0NoParallelism) { CacheBatcher::Options options; options.max_parallel_lookups = 1; ChangeBatcherConfig(options, delay_cache_.get()); PopulateCache(4); // Delaying "n0" causes the fetches for "n1" and "n2" to be batched in // CacheBatcher. They can be executed once "n0" is released. DelayKey("n0"); Callback* n0 = InitiateGet("n0"); EXPECT_EQ(1, outstanding_fetches()); Callback* n1 = InitiateGet("n1"); Callback* not_found = InitiateGet("not found"); EXPECT_EQ(3, outstanding_fetches()); Callback* n2 = InitiateGet("n2"); EXPECT_EQ(4, outstanding_fetches()); ReleaseKey("n0"); WaitAndCheck(n0, "v0"); WaitAndCheck(n1, "v1"); WaitAndCheck(n2, "v2"); WaitAndCheckNotFound(not_found); // outstanding_fetches() won't be stable to look at until all 3 callback Waits // are called. EXPECT_EQ(0, outstanding_fetches()); EXPECT_EQ(3, LastBatchSize()); // Further fetches will execute immediately again. CheckGet("n3", "v3"); } TEST_F(CacheBatcherTest, DelayN0TwoWayParallelism) { CacheBatcher::Options options; options.max_parallel_lookups = 2; ChangeBatcherConfig(options, delay_cache_.get()); PopulateCache(8); DelayKey("n0"); Callback* n0 = InitiateGet("n0"); EXPECT_EQ(1, outstanding_fetches()); // We still have some parallelism available to us, so "n1" and "n2" will // complete even while "n0" is outstanding. CheckGet("n1", "v1"); CheckGet("n2", "v2"); ASSERT_EQ(1, num_in_flight_keys()); // Now block "n3" and look it up. n4 and n5 will now be delayed and batched. DelayKey("n3"); Callback* n3 = InitiateGet("n3"); Callback* not_found = InitiateGet("not found"); Callback* n4 = InitiateGet("n4"); EXPECT_EQ(4, outstanding_fetches()); // n0, n3, "not found", n4 Callback* n5 = InitiateGet("n5"); EXPECT_EQ(5, outstanding_fetches()); // Releasing n0 frees a thread and now n4 and n5 can be completed. ReleaseKey("n0"); WaitAndCheck(n0, "v0"); WaitAndCheckNotFound(not_found); WaitAndCheck(n4, "v4"); WaitAndCheck(n5, "v5"); EXPECT_EQ(1, outstanding_fetches()); EXPECT_EQ(3, LastBatchSize()); // Finally, release n3 and we are all clean. ReleaseKey("n3"); WaitAndCheck(n3, "v3"); } TEST_F(CacheBatcherTest, ExceedMaxPendingUniqueAndDrop) { CacheBatcher::Options options; options.max_parallel_lookups = 1; options.max_pending_gets = 4; ChangeBatcherConfig(options, delay_cache_.get()); PopulateCache(5); // Delaying "n0" causes the fetches for "n1" and "n2" to be batched in // CacheBatcher. They can be executed once "n0" is released. DelayKey("n0"); Callback* n0 = InitiateGet("n0"); EXPECT_EQ(1, outstanding_fetches()); Callback* n1 = InitiateGet("n1"); EXPECT_EQ(2, outstanding_fetches()); Callback* not_found = InitiateGet("not found"); EXPECT_EQ(3, outstanding_fetches()); Callback* n2 = InitiateGet("n2"); EXPECT_EQ(4, outstanding_fetches()); Callback* n3 = InitiateGet("n3"); // This will be dropped immediately and WaitAndCheckNotFound(n3); // reported as not found. EXPECT_EQ(1, statistics_->GetVariable("cache_batcher_dropped_gets")->Get()); ReleaseKey("n0"); WaitAndCheck(n0, "v0"); WaitAndCheck(n1, "v1"); WaitAndCheckNotFound(not_found); WaitAndCheck(n2, "v2"); // outstanding_fetches() won't be stable to look at until all 3 callback Waits // are called. EXPECT_EQ(0, outstanding_fetches()); EXPECT_EQ(3, LastBatchSize()); // Further fetches will execute immediately again. CheckGet("n4", "v4"); } TEST_F(CacheBatcherTest, ExceedMaxPendingDuplicateAndDrop) { // Similar to ExceedMaxPendingUniqueAndDrop, except that this fills the // queue with lookups of the same key. CacheBatcher::Options options; options.max_parallel_lookups = 1; options.max_pending_gets = 4; ChangeBatcherConfig(options, delay_cache_.get()); PopulateCache(5); // Delaying "n0" causes the fetches for "n1" to be batched in CacheBatcher. // They can be executed once "n0" is released. DelayKey("n0"); Callback* n0 = InitiateGet("n0"); EXPECT_EQ(1, outstanding_fetches()); Callback* n1_0 = InitiateGet("n1"); Callback* n1_1 = InitiateGet("n1"); Callback* n1_2 = InitiateGet("n1"); EXPECT_EQ(4, outstanding_fetches()); Callback* n1_3 = InitiateGet("n1"); // This will be dropped immediately and WaitAndCheckNotFound(n1_3); // reported as not found. EXPECT_EQ(1, statistics_->GetVariable("cache_batcher_dropped_gets")->Get()); ReleaseKey("n0"); WaitAndCheck(n0, "v0"); WaitAndCheck(n1_0, "v1"); WaitAndCheck(n1_1, "v1"); WaitAndCheck(n1_2, "v1"); // outstanding_fetches() won't be stable to look at until all 3 callback Waits // are called. EXPECT_EQ(0, outstanding_fetches()); EXPECT_EQ(1, LastBatchSize()); // Further fetches will execute immediately again. CheckGet("n4", "v4"); } TEST_F(CacheBatcherTest, ExceedMaxPendingInFlightAndDrop) { // Similar to ExceedMaxPendingUniqueAndDrop, except that this fills the // queue with lookups of different keys, lets them go into the // in_flight queue, then verifies that no more keys can be put into the // queue. CacheBatcher::Options options; options.max_parallel_lookups = 1; options.max_pending_gets = 3; ChangeBatcherConfig(options, delay_cache_.get()); PopulateCache(5); // Delaying "n0" causes subsequent fetches to be batched in CacheBatcher. // They can be executed once "n0" is released. DelayKey("n0"); Callback* n0 = InitiateGet("n0"); EXPECT_EQ(1, outstanding_fetches()); // Now fill the queue. // Note that ValidateCandidate is called ASAP, but fetches are in-memory until // Done is called (which happens only when DelayCache releases the key for // that callback). Callback* n1 = InitiateGet("n1"); EXPECT_EQ(2, outstanding_fetches()); Callback* n2 = InitiateGet("n2"); EXPECT_EQ(3, outstanding_fetches()); // n0, n1, n2 Callback* n3 = InitiateGet("n3"); // This should be dropped immediately EXPECT_EQ(3, outstanding_fetches()); // n0, n1, n2 WaitAndCheckNotFound(n3); DelayKey("n1"); DelayKey("n2"); ReleaseKey("n0"); WaitAndCheck(n0, "v0"); EXPECT_EQ(2, outstanding_fetches()); Callback* n0_dup = InitiateGet("n0"); EXPECT_EQ(3, outstanding_fetches()); // Now n-1 fetches are in flight, 1 fetch is queued, so we should not be able // to queue any more fetches. Callback* n0_drop = InitiateGet("n0"); WaitAndCheckNotFound(n0_drop); // Clean out in_flight_ and queue_. ReleaseKey("n1"); ReleaseKey("n2"); WaitAndCheck(n1, "v1"); WaitAndCheck(n2, "v2"); WaitAndCheck(n0_dup, "v0"); // Further fetches will execute immediately again. CheckGet("n4", "v4"); } TEST_F(CacheBatcherTest, CoalesceDuplicateGets) { CacheBatcher::Options options; options.max_parallel_lookups = 1; options.max_pending_gets = 10; ChangeBatcherConfig(options, delay_cache_.get()); PopulateCache(5); // Delay n0 so that the first lookup gets fired off immediately, but // subsequent lookups block until n0 is released. DelayKey("n0"); Callback* n0 = InitiateGet("n0"); EXPECT_EQ(1, outstanding_fetches()); Callback* n1 = InitiateGet("n1"); EXPECT_EQ(2, outstanding_fetches()); Callback* not_found = InitiateGet("not_found"); EXPECT_EQ(3, outstanding_fetches()); Callback* n2 = InitiateGet("n2"); EXPECT_EQ(4, outstanding_fetches()); Callback* not_found_dup = InitiateGet("not_found"); EXPECT_EQ(5, outstanding_fetches()); Callback* n1_dup = InitiateGet("n1"); n1_dup->set_invalid_key("n1"); EXPECT_EQ(6, outstanding_fetches()); ReleaseKey("n0"); WaitAndCheck(n0, "v0"); WaitAndCheck(n1, "v1"); WaitAndCheckNotFound(n1_dup); // Check duplicate non-validated hit. WaitAndCheck(n2, "v2"); WaitAndCheckNotFound(not_found); WaitAndCheckNotFound(not_found_dup); // Even though we initiated 4 gets, 2 were for the same key (n1), so we expect // 3 cache hits. Similarly, we expect 1 miss, even though we initiated 2 gets // for that key. EXPECT_EQ(3, lru_cache_->num_hits()); EXPECT_EQ(1, lru_cache_->num_misses()); } TEST_F(CacheBatcherTest, CoalesceDuplicateGetsParallel) { // Identical to CoalesceDuplicateGets, but with parallism. This is intended to // exercise CacheBatcher's internal synchronization and merging of in_flight_ // and queue_ gets. CacheBatcher::Options options; options.max_parallel_lookups = 2; options.max_pending_gets = 10; ChangeBatcherConfig(options, delay_cache_.get()); PopulateCache(5); DelayKey("n0"); Callback* n0 = InitiateGet("n0"); EXPECT_EQ(1, outstanding_fetches()); // n0 // n0 is in flight and delayed, but we still have one ready thread to use. // These gets should not interfere with CacheBatcher's ability to track the // in flight get of "n0". // // (We must delay "n1", to prevent a data race when we make one of its // fetches invalid.) DelayKey("n1"); Callback* n1 = InitiateGet("n1"); Callback* not_found = InitiateGet("not_found"); Callback* n2 = InitiateGet("n2"); Callback* not_found_dup = InitiateGet("not_found"); Callback* n1_dup = InitiateGet("n1"); n1_dup->set_invalid_key("n1"); ReleaseKey("n1"); WaitAndCheck(n1, "v1"); WaitAndCheckNotFound(n1_dup); // Check duplicate non-validated hit. WaitAndCheck(n2, "v2"); WaitAndCheckNotFound(not_found); WaitAndCheckNotFound(not_found_dup); EXPECT_EQ(1, outstanding_fetches()); ReleaseKey("n0"); WaitAndCheck(n0, "v0"); } TEST_F(CacheBatcherTest, CoalesceInFlightGet) { CacheBatcher::Options options; options.max_parallel_lookups = 1; ChangeBatcherConfig(options, delay_cache_.get()); PopulateCache(5); DelayKey("n0"); // The first fetch of n0 will be immediate, but will be stuck in flight until // n0 is released. Callback* n0 = InitiateGet("n0"); DelayKey("n1"); Callback* n1 = InitiateGet("n1"); // Should be queued behind n0. // Since there's already an in flight fetch of n0, this callback should // piggyback on it, rather than going into the queue for a separate request. Callback* n0_dup = InitiateGet("n0"); EXPECT_EQ(3, outstanding_fetches()); // When n0 is released, both fetches of n0 should be coalesced and be // completed by the same cache hit. ReleaseKey("n0"); WaitAndCheck(n0, "v0"); WaitAndCheck(n0_dup, "v0"); EXPECT_EQ(1, outstanding_fetches()); ReleaseKey("n1"); WaitAndCheck(n1, "v1"); EXPECT_EQ(0, outstanding_fetches()); EXPECT_EQ(2, lru_cache_->num_hits()); } TEST_F(CacheBatcherTest, CheckWriteThroughCacheCompatibility) { LRUCache small_cache(kMaxSize); LRUCache big_cache(kMaxSize); WriteThroughCache write_through_cache(&small_cache, &big_cache); CacheBatcher::Options options; options.max_parallel_lookups = 1; ChangeBatcherConfig(options, &write_through_cache); PopulateCache(5); // Make sure we find a valid value in L2 if it's shadowed by an invalid one // in L1. CheckPut(&small_cache, "Name", "invalid"); CheckPut(&big_cache, "Name", "valid"); set_invalid_value("invalid"); CheckNotFound(&small_cache, "Name"); CheckGet(&big_cache, "Name", "valid"); // Here's the interesting bit: make sure the write through cache still works // properly. CheckGet(batcher_.get(), "Name", "valid"); // Make sure we fixed up the small_cache_ CheckGet(&small_cache, "Name", "valid"); } } // namespace net_instaweb
bits 64 ; Arithemtic. add al, bl add al, sil add al, [rbx] add [ebx], al add al, [ebx] add [ebx], al add al, 0x10 add ax, bx add ax, r11w add ax, [rbx] add [ebx], ax add ax, [ebx] add [ebx], ax add ax, 0x1000 add eax, ebx add eax, r11d add eax, [rbx] add [rbx], eax add eax, [ebx] add [ebx], eax add eax, 0x10000000 add rax, rbx add rax, r11 add rax, [rbx] add [rbx], rax add rax, [ebx] add [ebx], rax add rax, 0x10000000 sub al, bl sub al, sil sub al, [rbx] sub [ebx], al sub al, [ebx] sub [ebx], al sub al, 0x10 sub ax, bx sub ax, r11w sub ax, [rbx] sub [ebx], ax sub ax, [ebx] sub [ebx], ax sub ax, 0x1000 sub eax, ebx sub eax, r11d sub eax, [rbx] sub [rbx], eax sub eax, [ebx] sub [ebx], eax sub eax, 0x10000000 sub rax, rbx sub rax, r11 sub rax, [rbx] sub [rbx], rax sub rax, [ebx] sub [ebx], rax sub rax, 0x10000000 adc al, bl adc al, sil adc al, [rbx] adc [ebx], al adc al, [ebx] adc [ebx], al adc al, 0x10 adc ax, bx adc ax, r11w adc ax, [rbx] adc [ebx], ax adc ax, [ebx] adc [ebx], ax adc ax, 0x1000 adc eax, ebx adc eax, r11d adc eax, [rbx] adc [rbx], eax adc eax, [ebx] adc [ebx], eax adc eax, 0x10000000 adc rax, rbx adc rax, r11 adc rax, [rbx] adc [rbx], rax adc rax, [ebx] adc [ebx], rax adc rax, 0x10000000 sbb al, bl sbb al, sil sbb al, [rbx] sbb [ebx], al sbb al, [ebx] sbb [ebx], al sbb al, 0x10 sbb ax, bx sbb ax, r11w sbb ax, [rbx] sbb [ebx], ax sbb ax, [ebx] sbb [ebx], ax sbb ax, 0x1000 sbb eax, ebx sbb eax, r11d sbb eax, [rbx] sbb [rbx], eax sbb eax, [ebx] sbb [ebx], eax sbb eax, 0x10000000 sbb rax, rbx sbb rax, r11 sbb rax, [rbx] sbb [rbx], rax sbb rax, [ebx] sbb [ebx], rax sbb rax, 0x10000000 and al, bl and al, sil and al, [rbx] and [ebx], al and al, [ebx] and [ebx], al and al, 0x10 and ax, bx and ax, r11w and ax, [rbx] and [ebx], ax and ax, [ebx] and [ebx], ax and ax, 0x1000 and eax, ebx and eax, r11d and eax, [rbx] and [rbx], eax and eax, [ebx] and [ebx], eax and eax, 0x10000000 and rax, rbx and rax, r11 and rax, [rbx] and [rbx], rax and rax, [ebx] and [ebx], rax and rax, 0x10000000 or al, bl or al, sil or al, [rbx] or [ebx], al or al, [ebx] or [ebx], al or al, 0x10 or ax, bx or ax, r11w or ax, [rbx] or [ebx], ax or ax, [ebx] or [ebx], ax or ax, 0x1000 or eax, ebx or eax, r11d or eax, [rbx] or [rbx], eax or eax, [ebx] or [ebx], eax or eax, 0x10000000 or rax, rbx or rax, r11 or rax, [rbx] or [rbx], rax or rax, [ebx] or [ebx], rax or rax, 0x10000000 xor al, bl xor al, sil xor al, [rbx] xor [ebx], al xor al, [ebx] xor [ebx], al xor al, 0x10 xor ax, bx xor ax, r11w xor ax, [rbx] xor [ebx], ax xor ax, [ebx] xor [ebx], ax xor ax, 0x1000 xor eax, ebx xor eax, r11d xor eax, [rbx] xor [rbx], eax xor eax, [ebx] xor [ebx], eax xor eax, 0x10000000 xor rax, rbx xor rax, r11 xor rax, [rbx] xor [rbx], rax xor rax, [ebx] xor [ebx], rax xor rax, 0x10000000 cmp al, bl cmp al, sil cmp al, [rbx] cmp [ebx], al cmp al, [ebx] cmp [ebx], al cmp al, 0x10 cmp ax, bx cmp ax, r11w cmp ax, [rbx] cmp [ebx], ax cmp ax, [ebx] cmp [ebx], ax cmp ax, 0x1000 cmp eax, ebx cmp eax, r11d cmp eax, [rbx] cmp [rbx], eax cmp eax, [ebx] cmp [ebx], eax cmp eax, 0x10000000 cmp rax, rbx cmp rax, r11 cmp rax, [rbx] cmp [rbx], rax cmp rax, [ebx] cmp [ebx], rax cmp rax, 0x10000000 test eax, 1 test rax, 1 test eax, r14d test rax, r14 test byte [rbx], 1 test word [rbx], 1 test dword [rbx], 1 test qword [rbx], 1 test byte [rbx], al test word [rbx], ax test dword [rbx], eax test qword [rbx], rax ; Data transfer. mov al, byte 0xBD mov ax, word 0xBDBD mov eax, dword 0xBDBDBDBD mov rax, qword 0xBDBDBDBDBDBDBDBD mov al, [qword 0xBDBDBDBDBDBDBDBD] mov ax, [qword 0xBDBDBDBDBDBDBDBD] mov eax, [qword 0xBDBDBDBDBDBDBDBD] mov rax, [qword 0xBDBDBDBDBDBDBDBD] mov [qword 0xBDBDBDBDBDBDBDBD], al mov [qword 0xBDBDBDBDBDBDBDBD], ax mov [qword 0xBDBDBDBDBDBDBDBD], eax mov [qword 0xBDBDBDBDBDBDBDBD], rax xlatb xchg al, cl xchg ax, cx xchg eax, ecx xchg rax, rcx xchg rax, [rbx] xchg rax, [ebx] ; Unary opcodes. inc al inc r15b inc ax inc r15w inc eax inc r15d inc rax inc r15 inc byte [rbx] inc word [rbx] inc dword [rbx] inc qword [rbx] dec al dec r15b dec ax dec r15w dec eax dec r15d dec rax dec r15 dec byte [rbx] dec word [rbx] dec dword [rbx] dec qword [rbx] not al not r15b not ax not r15w not eax not r15d not rax not r15 not byte [rbx] not word [rbx] not dword [rbx] not qword [rbx] neg al neg r15b neg ax neg r15w neg eax neg r15d neg rax neg r15 neg byte [rbx] neg word [rbx] neg dword [rbx] neg qword [rbx] div al div r15b div ax div r15w div eax div r15d div rax div r15 div byte [rbx] div word [rbx] div dword [rbx] div qword [rbx] mul al mul r15b mul ax mul r15w mul eax mul r15d mul rax mul r15 mul byte [rbx] mul word [rbx] mul dword [rbx] mul qword [rbx] idiv al idiv r15b idiv ax idiv r15w idiv eax idiv r15d idiv rax idiv r15 idiv byte [rbx] idiv word [rbx] idiv dword [rbx] idiv qword [rbx] imul al imul r15b imul ax imul r15w imul eax imul r15d imul rax imul r15 imul byte [rbx] imul word [rbx] imul dword [rbx] imul qword [rbx] ; Shift/rotate rol al, 1 rol al, 100 rol al, cl rol byte [rbx], 1 rol byte [rbx], cl rol ax, 1 rol ax, 100 rol ax, cl rol word [rbx], 1 rol word [rbx], 100 rol word [rbx], cl rol dword [rbx], 1 rol dword [rbx], 100 rol dword [rbx], cl rol qword [rbx], 1 rol qword [rbx], 100 rol qword [rbx], cl ror al, 1 ror al, 100 ror al, cl ror byte [rbx], 1 ror byte [rbx], cl ror ax, 1 ror ax, 100 ror ax, cl ror word [rbx], 1 ror word [rbx], 100 ror word [rbx], cl ror dword [rbx], 1 ror dword [rbx], 100 ror dword [rbx], cl ror qword [rbx], 1 ror qword [rbx], 100 ror qword [rbx], cl rcl al, 1 rcl al, 100 rcl al, cl rcl byte [rbx], 1 rcl byte [rbx], cl rcl ax, 1 rcl ax, 100 rcl ax, cl rcl word [rbx], 1 rcl word [rbx], 100 rcl word [rbx], cl rcl dword [rbx], 1 rcl dword [rbx], 100 rcl dword [rbx], cl rcl qword [rbx], 1 rcl qword [rbx], 100 rcl qword [rbx], cl rcr al, 1 rcr al, 100 rcr al, cl rcr byte [rbx], 1 rcr byte [rbx], cl rcr ax, 1 rcr ax, 100 rcr ax, cl rcr word [rbx], 1 rcr word [rbx], 100 rcr word [rbx], cl rcr dword [rbx], 1 rcr dword [rbx], 100 rcr dword [rbx], cl rcr qword [rbx], 1 rcr qword [rbx], 100 rcr qword [rbx], cl shl al, 1 shl al, 100 shl al, cl shl byte [rbx], 1 shl byte [rbx], cl shl ax, 1 shl ax, 100 shl ax, cl shl word [rbx], 1 shl word [rbx], 100 shl word [rbx], cl shl dword [rbx], 1 shl dword [rbx], 100 shl dword [rbx], cl shl qword [rbx], 1 shl qword [rbx], 100 shl qword [rbx], cl shr al, 1 shr al, 100 shr al, cl shr byte [rbx], 1 shr byte [rbx], cl shr ax, 1 shr ax, 100 shr ax, cl shr word [rbx], 1 shr word [rbx], 100 shr word [rbx], cl shr dword [rbx], 1 shr dword [rbx], 100 shr dword [rbx], cl shr qword [rbx], 1 shr qword [rbx], 100 shr qword [rbx], cl sar al, 1 sar al, 100 sar al, cl sar byte [rbx], 1 sar byte [rbx], cl sar ax, 1 sar ax, 100 sar ax, cl sar word [rbx], 1 sar word [rbx], 100 sar word [rbx], cl sar dword [rbx], 1 sar dword [rbx], 100 sar dword [rbx], cl sar qword [rbx], 1 sar qword [rbx], 100 sar qword [rbx], cl ; imul with 3 operands imul ax, cx, 100 imul ax, [rbx], 100 imul eax, ecx, 100 imul eax, [rbx], 100 imul rax, rcx, 100 imul rax, [rbx], 100 ; String movsb movsw movsd movsq stosb stosw stosd stosq lodsb lodsw lodsd lodsq scasb scasw scasd scasq cmpsb cmpsb cmpsw cmpsd cmpsq ; I/O insb insw insd outsb outsw outsd in al, 0x10 in ax, 0x10 in al, dx in ax, dx out 0x10, al out 0x10, ax out dx, al out dx, ax ; Prefixes. lock add qword [rdi + 0x1000], 1 lock xacquire add dword [rax], 1 lock xrelease sub qword [rsi + rdi * 8 - 0x1000], 2 xrelease mov byte [rbp + 0x1000], spl rep stosb rep lodsb repnz scasw repz cmpsq
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x6ef1, %rsi lea addresses_UC_ht+0x120ac, %rdi clflush (%rdi) dec %r12 mov $20, %rcx rep movsl nop nop nop nop nop sub %rax, %rax lea addresses_UC_ht+0xcb28, %r11 nop nop xor %r13, %r13 mov $0x6162636465666768, %rcx movq %rcx, (%r11) nop nop nop nop nop xor $41809, %rax lea addresses_normal_ht+0x19a48, %rsi lea addresses_WC_ht+0xb3c8, %rdi nop nop nop nop nop cmp $11134, %rdx mov $83, %rcx rep movsq nop nop nop nop cmp %rax, %rax lea addresses_normal_ht+0x91c8, %r11 nop nop nop nop nop and $23996, %rax movups (%r11), %xmm5 vpextrq $1, %xmm5, %rdx nop nop nop add %r12, %r12 lea addresses_WC_ht+0xe4e4, %r13 nop sub %rdi, %rdi movl $0x61626364, (%r13) nop nop nop inc %rdi lea addresses_UC_ht+0xcecf, %r12 nop nop nop nop nop dec %rsi movups (%r12), %xmm4 vpextrq $1, %xmm4, %r11 nop sub $60810, %rax lea addresses_WC_ht+0x122a8, %r12 nop xor $19154, %r13 mov (%r12), %eax nop inc %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r15 push %rbp push %rbx push %rcx push %rdx // Store lea addresses_WC+0x163c8, %r15 nop nop nop nop sub %rcx, %rcx movw $0x5152, (%r15) nop nop nop nop cmp %r11, %r11 // Load lea addresses_A+0xe0e0, %rcx nop nop sub $26212, %rbp movb (%rcx), %dl nop nop dec %r15 // Faulty Load lea addresses_WC+0x163c8, %rbx nop nop sub %r13, %r13 vmovups (%rbx), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $0, %xmm2, %r11 lea oracles, %r15 and $0xff, %r11 shlq $12, %r11 mov (%r15,%r11,1), %r11 pop %rdx pop %rcx pop %rbx pop %rbp pop %r15 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 3, 'size': 1, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 4, 'size': 8, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 7, 'size': 16, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 1, 'size': 4, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 5, 'size': 4, 'same': False, 'NT': False}} {'4f': 61, '06': 44, '00': 12579, '02': 10, '44': 9128, '50': 7} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; Generate references to any portions of ACIA ; code that must be part of every compile that ; uses the ACIA. PUBLIC _acia_need EXTERN _acia_init defc _acia_need = _acia_init ; The ACIA must be initialized before main is called SECTION code_crt_init call _acia_init
; ******************************************************************************************** ; ******************************************************************************************** ; ; Name : hexstr.asm ; Purpose : .. ; Created : 15th Nov 1991 ; Updated : 4th Jan 2021 ; Authors : Fred Bowen ; ; ******************************************************************************************** ; ******************************************************************************************** hexd jsr chknum phw poker ; save linnum [910911] jsr getadr ; 2 byte val in (poker) lda #4 jsr strspa ldy #0 lda poker+1 jsr hexit lda poker jsr hexit pla ; restore linnum sta poker+1 pla sta poker +lbra chrd1 ; pla,pla,jmp putnew hexit pha lsr lsr lsr lsr jsr dohex pla dohex and #$0f cmp #$0a bcc l143_1 adc #6 l143_1 adc #'0' phx ldx #dsctmp+1 jsr sta_far_ram1 ; sta (dsctmp+1),y plx iny rts ;.end ; ******************************************************************************************** ; ; Date Changes ; ==== ======= ; ; ********************************************************************************************
/* * Copyright (c) 2008, Willow Garage, 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 the Willow Garage, 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 <gtest/gtest.h> #include <tf/transform_listener.h> #include <sys/time.h> void seed_rand() { //Seed random number generator with current microseond count timeval temp_time_struct; gettimeofday(&temp_time_struct,NULL); srand(temp_time_struct.tv_usec); }; void generate_rand_vectors(double scale, uint64_t runs, std::vector<double>& xvalues, std::vector<double>& yvalues, std::vector<double>&zvalues) { seed_rand(); for ( uint64_t i = 0; i < runs ; i++ ) { xvalues[i] = 1.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; yvalues[i] = 1.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; zvalues[i] = 1.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; } } using namespace tf; TEST(transform_listener, resolve) { ros::NodeHandle n("~"); tf::TransformListener tl; //no prefix EXPECT_STREQ("id", tl.resolve("id").c_str()); n.setParam("tf_prefix", "a_tf_prefix"); tf::TransformListener tp; std::string prefix_str = tf::getPrefixParam(n); EXPECT_STREQ("a_tf_prefix", prefix_str.c_str()); EXPECT_STREQ("a_tf_prefix/id", tf::resolve(prefix_str, "id").c_str()); EXPECT_STREQ("a_tf_prefix/id", tp.resolve("id").c_str()); } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "transform_listener_unittest"); return RUN_ALL_TESTS(); }
<% from pwnlib.shellcraft.thumb.linux import syscall %> <%page args="fd, params"/> <%docstring> Invokes the syscall stty. See 'man 2 stty' for more information. Arguments: fd(int): fd params(sgttyb): params </%docstring> ${syscall('SYS_stty', fd, params)}
user/_stressfs: file format elf64-littleriscv Disassembly of section .text: 0000000000000000 <main>: #include "kernel/fs.h" #include "kernel/fcntl.h" int main(int argc, char *argv[]) { 0: dd010113 addi sp,sp,-560 4: 22113423 sd ra,552(sp) 8: 22813023 sd s0,544(sp) c: 20913c23 sd s1,536(sp) 10: 21213823 sd s2,528(sp) 14: 1c00 addi s0,sp,560 int fd, i; char path[] = "stressfs0"; 16: 00001797 auipc a5,0x1 1a: 92278793 addi a5,a5,-1758 # 938 <malloc+0x11c> 1e: 6398 ld a4,0(a5) 20: fce43823 sd a4,-48(s0) 24: 0087d783 lhu a5,8(a5) 28: fcf41c23 sh a5,-40(s0) char data[512]; printf("stressfs starting\n"); 2c: 00001517 auipc a0,0x1 30: 8dc50513 addi a0,a0,-1828 # 908 <malloc+0xec> 34: 00000097 auipc ra,0x0 38: 72a080e7 jalr 1834(ra) # 75e <printf> memset(data, 'a', sizeof(data)); 3c: 20000613 li a2,512 40: 06100593 li a1,97 44: dd040513 addi a0,s0,-560 48: 00000097 auipc ra,0x0 4c: 136080e7 jalr 310(ra) # 17e <memset> for(i = 0; i < 4; i++) 50: 4481 li s1,0 52: 4911 li s2,4 if(fork() > 0) 54: 00000097 auipc ra,0x0 58: 37a080e7 jalr 890(ra) # 3ce <fork> 5c: 00a04563 bgtz a0,66 <main+0x66> for(i = 0; i < 4; i++) 60: 2485 addiw s1,s1,1 62: ff2499e3 bne s1,s2,54 <main+0x54> break; printf("write %d\n", i); 66: 85a6 mv a1,s1 68: 00001517 auipc a0,0x1 6c: 8b850513 addi a0,a0,-1864 # 920 <malloc+0x104> 70: 00000097 auipc ra,0x0 74: 6ee080e7 jalr 1774(ra) # 75e <printf> path[8] += i; 78: fd844783 lbu a5,-40(s0) 7c: 9cbd addw s1,s1,a5 7e: fc940c23 sb s1,-40(s0) fd = open(path, O_CREATE | O_RDWR); 82: 20200593 li a1,514 86: fd040513 addi a0,s0,-48 8a: 00000097 auipc ra,0x0 8e: 38c080e7 jalr 908(ra) # 416 <open> 92: 892a mv s2,a0 94: 44d1 li s1,20 for(i = 0; i < 20; i++) // printf(fd, "%d\n", i); write(fd, data, sizeof(data)); 96: 20000613 li a2,512 9a: dd040593 addi a1,s0,-560 9e: 854a mv a0,s2 a0: 00000097 auipc ra,0x0 a4: 356080e7 jalr 854(ra) # 3f6 <write> for(i = 0; i < 20; i++) a8: 34fd addiw s1,s1,-1 aa: f4f5 bnez s1,96 <main+0x96> close(fd); ac: 854a mv a0,s2 ae: 00000097 auipc ra,0x0 b2: 350080e7 jalr 848(ra) # 3fe <close> printf("read\n"); b6: 00001517 auipc a0,0x1 ba: 87a50513 addi a0,a0,-1926 # 930 <malloc+0x114> be: 00000097 auipc ra,0x0 c2: 6a0080e7 jalr 1696(ra) # 75e <printf> fd = open(path, O_RDONLY); c6: 4581 li a1,0 c8: fd040513 addi a0,s0,-48 cc: 00000097 auipc ra,0x0 d0: 34a080e7 jalr 842(ra) # 416 <open> d4: 892a mv s2,a0 d6: 44d1 li s1,20 for (i = 0; i < 20; i++) read(fd, data, sizeof(data)); d8: 20000613 li a2,512 dc: dd040593 addi a1,s0,-560 e0: 854a mv a0,s2 e2: 00000097 auipc ra,0x0 e6: 30c080e7 jalr 780(ra) # 3ee <read> for (i = 0; i < 20; i++) ea: 34fd addiw s1,s1,-1 ec: f4f5 bnez s1,d8 <main+0xd8> close(fd); ee: 854a mv a0,s2 f0: 00000097 auipc ra,0x0 f4: 30e080e7 jalr 782(ra) # 3fe <close> wait(0); f8: 4501 li a0,0 fa: 00000097 auipc ra,0x0 fe: 2e4080e7 jalr 740(ra) # 3de <wait> exit(0); 102: 4501 li a0,0 104: 00000097 auipc ra,0x0 108: 2d2080e7 jalr 722(ra) # 3d6 <exit> 000000000000010c <strcpy>: #include "kernel/fcntl.h" #include "user/user.h" char* strcpy(char *s, const char *t) { 10c: 1141 addi sp,sp,-16 10e: e422 sd s0,8(sp) 110: 0800 addi s0,sp,16 char *os; os = s; while((*s++ = *t++) != 0) 112: 87aa mv a5,a0 114: 0585 addi a1,a1,1 116: 0785 addi a5,a5,1 118: fff5c703 lbu a4,-1(a1) 11c: fee78fa3 sb a4,-1(a5) 120: fb75 bnez a4,114 <strcpy+0x8> ; return os; } 122: 6422 ld s0,8(sp) 124: 0141 addi sp,sp,16 126: 8082 ret 0000000000000128 <strcmp>: int strcmp(const char *p, const char *q) { 128: 1141 addi sp,sp,-16 12a: e422 sd s0,8(sp) 12c: 0800 addi s0,sp,16 while(*p && *p == *q) 12e: 00054783 lbu a5,0(a0) 132: cb91 beqz a5,146 <strcmp+0x1e> 134: 0005c703 lbu a4,0(a1) 138: 00f71763 bne a4,a5,146 <strcmp+0x1e> p++, q++; 13c: 0505 addi a0,a0,1 13e: 0585 addi a1,a1,1 while(*p && *p == *q) 140: 00054783 lbu a5,0(a0) 144: fbe5 bnez a5,134 <strcmp+0xc> return (uchar)*p - (uchar)*q; 146: 0005c503 lbu a0,0(a1) } 14a: 40a7853b subw a0,a5,a0 14e: 6422 ld s0,8(sp) 150: 0141 addi sp,sp,16 152: 8082 ret 0000000000000154 <strlen>: uint strlen(const char *s) { 154: 1141 addi sp,sp,-16 156: e422 sd s0,8(sp) 158: 0800 addi s0,sp,16 int n; for(n = 0; s[n]; n++) 15a: 00054783 lbu a5,0(a0) 15e: cf91 beqz a5,17a <strlen+0x26> 160: 0505 addi a0,a0,1 162: 87aa mv a5,a0 164: 4685 li a3,1 166: 9e89 subw a3,a3,a0 168: 00f6853b addw a0,a3,a5 16c: 0785 addi a5,a5,1 16e: fff7c703 lbu a4,-1(a5) 172: fb7d bnez a4,168 <strlen+0x14> ; return n; } 174: 6422 ld s0,8(sp) 176: 0141 addi sp,sp,16 178: 8082 ret for(n = 0; s[n]; n++) 17a: 4501 li a0,0 17c: bfe5 j 174 <strlen+0x20> 000000000000017e <memset>: void* memset(void *dst, int c, uint n) { 17e: 1141 addi sp,sp,-16 180: e422 sd s0,8(sp) 182: 0800 addi s0,sp,16 char *cdst = (char *) dst; int i; for(i = 0; i < n; i++){ 184: ca19 beqz a2,19a <memset+0x1c> 186: 87aa mv a5,a0 188: 1602 slli a2,a2,0x20 18a: 9201 srli a2,a2,0x20 18c: 00a60733 add a4,a2,a0 cdst[i] = c; 190: 00b78023 sb a1,0(a5) for(i = 0; i < n; i++){ 194: 0785 addi a5,a5,1 196: fee79de3 bne a5,a4,190 <memset+0x12> } return dst; } 19a: 6422 ld s0,8(sp) 19c: 0141 addi sp,sp,16 19e: 8082 ret 00000000000001a0 <strchr>: char* strchr(const char *s, char c) { 1a0: 1141 addi sp,sp,-16 1a2: e422 sd s0,8(sp) 1a4: 0800 addi s0,sp,16 for(; *s; s++) 1a6: 00054783 lbu a5,0(a0) 1aa: cb99 beqz a5,1c0 <strchr+0x20> if(*s == c) 1ac: 00f58763 beq a1,a5,1ba <strchr+0x1a> for(; *s; s++) 1b0: 0505 addi a0,a0,1 1b2: 00054783 lbu a5,0(a0) 1b6: fbfd bnez a5,1ac <strchr+0xc> return (char*)s; return 0; 1b8: 4501 li a0,0 } 1ba: 6422 ld s0,8(sp) 1bc: 0141 addi sp,sp,16 1be: 8082 ret return 0; 1c0: 4501 li a0,0 1c2: bfe5 j 1ba <strchr+0x1a> 00000000000001c4 <gets>: char* gets(char *buf, int max) { 1c4: 711d addi sp,sp,-96 1c6: ec86 sd ra,88(sp) 1c8: e8a2 sd s0,80(sp) 1ca: e4a6 sd s1,72(sp) 1cc: e0ca sd s2,64(sp) 1ce: fc4e sd s3,56(sp) 1d0: f852 sd s4,48(sp) 1d2: f456 sd s5,40(sp) 1d4: f05a sd s6,32(sp) 1d6: ec5e sd s7,24(sp) 1d8: 1080 addi s0,sp,96 1da: 8baa mv s7,a0 1dc: 8a2e mv s4,a1 int i, cc; char c; for(i=0; i+1 < max; ){ 1de: 892a mv s2,a0 1e0: 4481 li s1,0 cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; if(c == '\n' || c == '\r') 1e2: 4aa9 li s5,10 1e4: 4b35 li s6,13 for(i=0; i+1 < max; ){ 1e6: 89a6 mv s3,s1 1e8: 2485 addiw s1,s1,1 1ea: 0344d863 bge s1,s4,21a <gets+0x56> cc = read(0, &c, 1); 1ee: 4605 li a2,1 1f0: faf40593 addi a1,s0,-81 1f4: 4501 li a0,0 1f6: 00000097 auipc ra,0x0 1fa: 1f8080e7 jalr 504(ra) # 3ee <read> if(cc < 1) 1fe: 00a05e63 blez a0,21a <gets+0x56> buf[i++] = c; 202: faf44783 lbu a5,-81(s0) 206: 00f90023 sb a5,0(s2) if(c == '\n' || c == '\r') 20a: 01578763 beq a5,s5,218 <gets+0x54> 20e: 0905 addi s2,s2,1 210: fd679be3 bne a5,s6,1e6 <gets+0x22> for(i=0; i+1 < max; ){ 214: 89a6 mv s3,s1 216: a011 j 21a <gets+0x56> 218: 89a6 mv s3,s1 break; } buf[i] = '\0'; 21a: 99de add s3,s3,s7 21c: 00098023 sb zero,0(s3) return buf; } 220: 855e mv a0,s7 222: 60e6 ld ra,88(sp) 224: 6446 ld s0,80(sp) 226: 64a6 ld s1,72(sp) 228: 6906 ld s2,64(sp) 22a: 79e2 ld s3,56(sp) 22c: 7a42 ld s4,48(sp) 22e: 7aa2 ld s5,40(sp) 230: 7b02 ld s6,32(sp) 232: 6be2 ld s7,24(sp) 234: 6125 addi sp,sp,96 236: 8082 ret 0000000000000238 <stat>: int stat(const char *n, struct stat *st) { 238: 1101 addi sp,sp,-32 23a: ec06 sd ra,24(sp) 23c: e822 sd s0,16(sp) 23e: e426 sd s1,8(sp) 240: e04a sd s2,0(sp) 242: 1000 addi s0,sp,32 244: 892e mv s2,a1 int fd; int r; fd = open(n, O_RDONLY); 246: 4581 li a1,0 248: 00000097 auipc ra,0x0 24c: 1ce080e7 jalr 462(ra) # 416 <open> if(fd < 0) 250: 02054563 bltz a0,27a <stat+0x42> 254: 84aa mv s1,a0 return -1; r = fstat(fd, st); 256: 85ca mv a1,s2 258: 00000097 auipc ra,0x0 25c: 1d6080e7 jalr 470(ra) # 42e <fstat> 260: 892a mv s2,a0 close(fd); 262: 8526 mv a0,s1 264: 00000097 auipc ra,0x0 268: 19a080e7 jalr 410(ra) # 3fe <close> return r; } 26c: 854a mv a0,s2 26e: 60e2 ld ra,24(sp) 270: 6442 ld s0,16(sp) 272: 64a2 ld s1,8(sp) 274: 6902 ld s2,0(sp) 276: 6105 addi sp,sp,32 278: 8082 ret return -1; 27a: 597d li s2,-1 27c: bfc5 j 26c <stat+0x34> 000000000000027e <atoi>: int atoi(const char *s) { 27e: 1141 addi sp,sp,-16 280: e422 sd s0,8(sp) 282: 0800 addi s0,sp,16 int n; n = 0; while('0' <= *s && *s <= '9') 284: 00054603 lbu a2,0(a0) 288: fd06079b addiw a5,a2,-48 28c: 0ff7f793 andi a5,a5,255 290: 4725 li a4,9 292: 02f76963 bltu a4,a5,2c4 <atoi+0x46> 296: 86aa mv a3,a0 n = 0; 298: 4501 li a0,0 while('0' <= *s && *s <= '9') 29a: 45a5 li a1,9 n = n*10 + *s++ - '0'; 29c: 0685 addi a3,a3,1 29e: 0025179b slliw a5,a0,0x2 2a2: 9fa9 addw a5,a5,a0 2a4: 0017979b slliw a5,a5,0x1 2a8: 9fb1 addw a5,a5,a2 2aa: fd07851b addiw a0,a5,-48 while('0' <= *s && *s <= '9') 2ae: 0006c603 lbu a2,0(a3) 2b2: fd06071b addiw a4,a2,-48 2b6: 0ff77713 andi a4,a4,255 2ba: fee5f1e3 bgeu a1,a4,29c <atoi+0x1e> return n; } 2be: 6422 ld s0,8(sp) 2c0: 0141 addi sp,sp,16 2c2: 8082 ret n = 0; 2c4: 4501 li a0,0 2c6: bfe5 j 2be <atoi+0x40> 00000000000002c8 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 2c8: 1141 addi sp,sp,-16 2ca: e422 sd s0,8(sp) 2cc: 0800 addi s0,sp,16 char *dst; const char *src; dst = vdst; src = vsrc; if (src > dst) { 2ce: 02b57463 bgeu a0,a1,2f6 <memmove+0x2e> while(n-- > 0) 2d2: 00c05f63 blez a2,2f0 <memmove+0x28> 2d6: 1602 slli a2,a2,0x20 2d8: 9201 srli a2,a2,0x20 2da: 00c507b3 add a5,a0,a2 dst = vdst; 2de: 872a mv a4,a0 *dst++ = *src++; 2e0: 0585 addi a1,a1,1 2e2: 0705 addi a4,a4,1 2e4: fff5c683 lbu a3,-1(a1) 2e8: fed70fa3 sb a3,-1(a4) while(n-- > 0) 2ec: fee79ae3 bne a5,a4,2e0 <memmove+0x18> src += n; while(n-- > 0) *--dst = *--src; } return vdst; } 2f0: 6422 ld s0,8(sp) 2f2: 0141 addi sp,sp,16 2f4: 8082 ret dst += n; 2f6: 00c50733 add a4,a0,a2 src += n; 2fa: 95b2 add a1,a1,a2 while(n-- > 0) 2fc: fec05ae3 blez a2,2f0 <memmove+0x28> 300: fff6079b addiw a5,a2,-1 304: 1782 slli a5,a5,0x20 306: 9381 srli a5,a5,0x20 308: fff7c793 not a5,a5 30c: 97ba add a5,a5,a4 *--dst = *--src; 30e: 15fd addi a1,a1,-1 310: 177d addi a4,a4,-1 312: 0005c683 lbu a3,0(a1) 316: 00d70023 sb a3,0(a4) while(n-- > 0) 31a: fee79ae3 bne a5,a4,30e <memmove+0x46> 31e: bfc9 j 2f0 <memmove+0x28> 0000000000000320 <memcmp>: int memcmp(const void *s1, const void *s2, uint n) { 320: 1141 addi sp,sp,-16 322: e422 sd s0,8(sp) 324: 0800 addi s0,sp,16 const char *p1 = s1, *p2 = s2; while (n-- > 0) { 326: ca05 beqz a2,356 <memcmp+0x36> 328: fff6069b addiw a3,a2,-1 32c: 1682 slli a3,a3,0x20 32e: 9281 srli a3,a3,0x20 330: 0685 addi a3,a3,1 332: 96aa add a3,a3,a0 if (*p1 != *p2) { 334: 00054783 lbu a5,0(a0) 338: 0005c703 lbu a4,0(a1) 33c: 00e79863 bne a5,a4,34c <memcmp+0x2c> return *p1 - *p2; } p1++; 340: 0505 addi a0,a0,1 p2++; 342: 0585 addi a1,a1,1 while (n-- > 0) { 344: fed518e3 bne a0,a3,334 <memcmp+0x14> } return 0; 348: 4501 li a0,0 34a: a019 j 350 <memcmp+0x30> return *p1 - *p2; 34c: 40e7853b subw a0,a5,a4 } 350: 6422 ld s0,8(sp) 352: 0141 addi sp,sp,16 354: 8082 ret return 0; 356: 4501 li a0,0 358: bfe5 j 350 <memcmp+0x30> 000000000000035a <memcpy>: void * memcpy(void *dst, const void *src, uint n) { 35a: 1141 addi sp,sp,-16 35c: e406 sd ra,8(sp) 35e: e022 sd s0,0(sp) 360: 0800 addi s0,sp,16 return memmove(dst, src, n); 362: 00000097 auipc ra,0x0 366: f66080e7 jalr -154(ra) # 2c8 <memmove> } 36a: 60a2 ld ra,8(sp) 36c: 6402 ld s0,0(sp) 36e: 0141 addi sp,sp,16 370: 8082 ret 0000000000000372 <my_strcat>: // functions added by us char* my_strcat(char* destination, const char* source) { 372: 1141 addi sp,sp,-16 374: e422 sd s0,8(sp) 376: 0800 addi s0,sp,16 int i, j; // move to the end of destination string for (i = 0; destination[i] != '\0'; i++); 378: 00054783 lbu a5,0(a0) 37c: c7a9 beqz a5,3c6 <my_strcat+0x54> 37e: 00150713 addi a4,a0,1 382: 87ba mv a5,a4 384: 4685 li a3,1 386: 9e99 subw a3,a3,a4 388: 00f6863b addw a2,a3,a5 38c: 0785 addi a5,a5,1 38e: fff7c703 lbu a4,-1(a5) 392: fb7d bnez a4,388 <my_strcat+0x16> // i now points to terminating null character in destination // Appends characters of source to the destination string for (j = 0; source[j] != '\0'; j++) 394: 0005c683 lbu a3,0(a1) 398: ca8d beqz a3,3ca <my_strcat+0x58> 39a: 4785 li a5,1 destination[i + j] = source[j]; 39c: 00f60733 add a4,a2,a5 3a0: 972a add a4,a4,a0 3a2: fed70fa3 sb a3,-1(a4) for (j = 0; source[j] != '\0'; j++) 3a6: 0007881b sext.w a6,a5 3aa: 0785 addi a5,a5,1 3ac: 00f58733 add a4,a1,a5 3b0: fff74683 lbu a3,-1(a4) 3b4: f6e5 bnez a3,39c <my_strcat+0x2a> // null terminate destination string destination[i + j] = '\0'; 3b6: 0106063b addw a2,a2,a6 3ba: 962a add a2,a2,a0 3bc: 00060023 sb zero,0(a2) // destination is returned by standard strcat() return destination; 3c0: 6422 ld s0,8(sp) 3c2: 0141 addi sp,sp,16 3c4: 8082 ret for (i = 0; destination[i] != '\0'; i++); 3c6: 4601 li a2,0 3c8: b7f1 j 394 <my_strcat+0x22> for (j = 0; source[j] != '\0'; j++) 3ca: 4801 li a6,0 3cc: b7ed j 3b6 <my_strcat+0x44> 00000000000003ce <fork>: # generated by usys.pl - do not edit #include "kernel/syscall.h" .global fork fork: li a7, SYS_fork 3ce: 4885 li a7,1 ecall 3d0: 00000073 ecall ret 3d4: 8082 ret 00000000000003d6 <exit>: .global exit exit: li a7, SYS_exit 3d6: 4889 li a7,2 ecall 3d8: 00000073 ecall ret 3dc: 8082 ret 00000000000003de <wait>: .global wait wait: li a7, SYS_wait 3de: 488d li a7,3 ecall 3e0: 00000073 ecall ret 3e4: 8082 ret 00000000000003e6 <pipe>: .global pipe pipe: li a7, SYS_pipe 3e6: 4891 li a7,4 ecall 3e8: 00000073 ecall ret 3ec: 8082 ret 00000000000003ee <read>: .global read read: li a7, SYS_read 3ee: 4895 li a7,5 ecall 3f0: 00000073 ecall ret 3f4: 8082 ret 00000000000003f6 <write>: .global write write: li a7, SYS_write 3f6: 48c1 li a7,16 ecall 3f8: 00000073 ecall ret 3fc: 8082 ret 00000000000003fe <close>: .global close close: li a7, SYS_close 3fe: 48d5 li a7,21 ecall 400: 00000073 ecall ret 404: 8082 ret 0000000000000406 <kill>: .global kill kill: li a7, SYS_kill 406: 4899 li a7,6 ecall 408: 00000073 ecall ret 40c: 8082 ret 000000000000040e <exec>: .global exec exec: li a7, SYS_exec 40e: 489d li a7,7 ecall 410: 00000073 ecall ret 414: 8082 ret 0000000000000416 <open>: .global open open: li a7, SYS_open 416: 48bd li a7,15 ecall 418: 00000073 ecall ret 41c: 8082 ret 000000000000041e <mknod>: .global mknod mknod: li a7, SYS_mknod 41e: 48c5 li a7,17 ecall 420: 00000073 ecall ret 424: 8082 ret 0000000000000426 <unlink>: .global unlink unlink: li a7, SYS_unlink 426: 48c9 li a7,18 ecall 428: 00000073 ecall ret 42c: 8082 ret 000000000000042e <fstat>: .global fstat fstat: li a7, SYS_fstat 42e: 48a1 li a7,8 ecall 430: 00000073 ecall ret 434: 8082 ret 0000000000000436 <link>: .global link link: li a7, SYS_link 436: 48cd li a7,19 ecall 438: 00000073 ecall ret 43c: 8082 ret 000000000000043e <mkdir>: .global mkdir mkdir: li a7, SYS_mkdir 43e: 48d1 li a7,20 ecall 440: 00000073 ecall ret 444: 8082 ret 0000000000000446 <chdir>: .global chdir chdir: li a7, SYS_chdir 446: 48a5 li a7,9 ecall 448: 00000073 ecall ret 44c: 8082 ret 000000000000044e <dup>: .global dup dup: li a7, SYS_dup 44e: 48a9 li a7,10 ecall 450: 00000073 ecall ret 454: 8082 ret 0000000000000456 <getpid>: .global getpid getpid: li a7, SYS_getpid 456: 48ad li a7,11 ecall 458: 00000073 ecall ret 45c: 8082 ret 000000000000045e <sbrk>: .global sbrk sbrk: li a7, SYS_sbrk 45e: 48b1 li a7,12 ecall 460: 00000073 ecall ret 464: 8082 ret 0000000000000466 <sleep>: .global sleep sleep: li a7, SYS_sleep 466: 48b5 li a7,13 ecall 468: 00000073 ecall ret 46c: 8082 ret 000000000000046e <uptime>: .global uptime uptime: li a7, SYS_uptime 46e: 48b9 li a7,14 ecall 470: 00000073 ecall ret 474: 8082 ret 0000000000000476 <trace>: .global trace trace: li a7, SYS_trace 476: 48d9 li a7,22 ecall 478: 00000073 ecall ret 47c: 8082 ret 000000000000047e <wait_stat>: .global wait_stat wait_stat: li a7, SYS_wait_stat 47e: 48dd li a7,23 ecall 480: 00000073 ecall ret 484: 8082 ret 0000000000000486 <putc>: static char digits[] = "0123456789ABCDEF"; static void putc(int fd, char c) { 486: 1101 addi sp,sp,-32 488: ec06 sd ra,24(sp) 48a: e822 sd s0,16(sp) 48c: 1000 addi s0,sp,32 48e: feb407a3 sb a1,-17(s0) write(fd, &c, 1); 492: 4605 li a2,1 494: fef40593 addi a1,s0,-17 498: 00000097 auipc ra,0x0 49c: f5e080e7 jalr -162(ra) # 3f6 <write> } 4a0: 60e2 ld ra,24(sp) 4a2: 6442 ld s0,16(sp) 4a4: 6105 addi sp,sp,32 4a6: 8082 ret 00000000000004a8 <printint>: static void printint(int fd, int xx, int base, int sgn) { 4a8: 7139 addi sp,sp,-64 4aa: fc06 sd ra,56(sp) 4ac: f822 sd s0,48(sp) 4ae: f426 sd s1,40(sp) 4b0: f04a sd s2,32(sp) 4b2: ec4e sd s3,24(sp) 4b4: 0080 addi s0,sp,64 4b6: 84aa mv s1,a0 char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 4b8: c299 beqz a3,4be <printint+0x16> 4ba: 0805c863 bltz a1,54a <printint+0xa2> neg = 1; x = -xx; } else { x = xx; 4be: 2581 sext.w a1,a1 neg = 0; 4c0: 4881 li a7,0 4c2: fc040693 addi a3,s0,-64 } i = 0; 4c6: 4701 li a4,0 do{ buf[i++] = digits[x % base]; 4c8: 2601 sext.w a2,a2 4ca: 00000517 auipc a0,0x0 4ce: 48650513 addi a0,a0,1158 # 950 <digits> 4d2: 883a mv a6,a4 4d4: 2705 addiw a4,a4,1 4d6: 02c5f7bb remuw a5,a1,a2 4da: 1782 slli a5,a5,0x20 4dc: 9381 srli a5,a5,0x20 4de: 97aa add a5,a5,a0 4e0: 0007c783 lbu a5,0(a5) 4e4: 00f68023 sb a5,0(a3) }while((x /= base) != 0); 4e8: 0005879b sext.w a5,a1 4ec: 02c5d5bb divuw a1,a1,a2 4f0: 0685 addi a3,a3,1 4f2: fec7f0e3 bgeu a5,a2,4d2 <printint+0x2a> if(neg) 4f6: 00088b63 beqz a7,50c <printint+0x64> buf[i++] = '-'; 4fa: fd040793 addi a5,s0,-48 4fe: 973e add a4,a4,a5 500: 02d00793 li a5,45 504: fef70823 sb a5,-16(a4) 508: 0028071b addiw a4,a6,2 while(--i >= 0) 50c: 02e05863 blez a4,53c <printint+0x94> 510: fc040793 addi a5,s0,-64 514: 00e78933 add s2,a5,a4 518: fff78993 addi s3,a5,-1 51c: 99ba add s3,s3,a4 51e: 377d addiw a4,a4,-1 520: 1702 slli a4,a4,0x20 522: 9301 srli a4,a4,0x20 524: 40e989b3 sub s3,s3,a4 putc(fd, buf[i]); 528: fff94583 lbu a1,-1(s2) 52c: 8526 mv a0,s1 52e: 00000097 auipc ra,0x0 532: f58080e7 jalr -168(ra) # 486 <putc> while(--i >= 0) 536: 197d addi s2,s2,-1 538: ff3918e3 bne s2,s3,528 <printint+0x80> } 53c: 70e2 ld ra,56(sp) 53e: 7442 ld s0,48(sp) 540: 74a2 ld s1,40(sp) 542: 7902 ld s2,32(sp) 544: 69e2 ld s3,24(sp) 546: 6121 addi sp,sp,64 548: 8082 ret x = -xx; 54a: 40b005bb negw a1,a1 neg = 1; 54e: 4885 li a7,1 x = -xx; 550: bf8d j 4c2 <printint+0x1a> 0000000000000552 <vprintf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void vprintf(int fd, const char *fmt, va_list ap) { 552: 7119 addi sp,sp,-128 554: fc86 sd ra,120(sp) 556: f8a2 sd s0,112(sp) 558: f4a6 sd s1,104(sp) 55a: f0ca sd s2,96(sp) 55c: ecce sd s3,88(sp) 55e: e8d2 sd s4,80(sp) 560: e4d6 sd s5,72(sp) 562: e0da sd s6,64(sp) 564: fc5e sd s7,56(sp) 566: f862 sd s8,48(sp) 568: f466 sd s9,40(sp) 56a: f06a sd s10,32(sp) 56c: ec6e sd s11,24(sp) 56e: 0100 addi s0,sp,128 char *s; int c, i, state; state = 0; for(i = 0; fmt[i]; i++){ 570: 0005c903 lbu s2,0(a1) 574: 18090f63 beqz s2,712 <vprintf+0x1c0> 578: 8aaa mv s5,a0 57a: 8b32 mv s6,a2 57c: 00158493 addi s1,a1,1 state = 0; 580: 4981 li s3,0 if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 582: 02500a13 li s4,37 if(c == 'd'){ 586: 06400c13 li s8,100 printint(fd, va_arg(ap, int), 10, 1); } else if(c == 'l') { 58a: 06c00c93 li s9,108 printint(fd, va_arg(ap, uint64), 10, 0); } else if(c == 'x') { 58e: 07800d13 li s10,120 printint(fd, va_arg(ap, int), 16, 0); } else if(c == 'p') { 592: 07000d93 li s11,112 putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]); 596: 00000b97 auipc s7,0x0 59a: 3bab8b93 addi s7,s7,954 # 950 <digits> 59e: a839 j 5bc <vprintf+0x6a> putc(fd, c); 5a0: 85ca mv a1,s2 5a2: 8556 mv a0,s5 5a4: 00000097 auipc ra,0x0 5a8: ee2080e7 jalr -286(ra) # 486 <putc> 5ac: a019 j 5b2 <vprintf+0x60> } else if(state == '%'){ 5ae: 01498f63 beq s3,s4,5cc <vprintf+0x7a> for(i = 0; fmt[i]; i++){ 5b2: 0485 addi s1,s1,1 5b4: fff4c903 lbu s2,-1(s1) 5b8: 14090d63 beqz s2,712 <vprintf+0x1c0> c = fmt[i] & 0xff; 5bc: 0009079b sext.w a5,s2 if(state == 0){ 5c0: fe0997e3 bnez s3,5ae <vprintf+0x5c> if(c == '%'){ 5c4: fd479ee3 bne a5,s4,5a0 <vprintf+0x4e> state = '%'; 5c8: 89be mv s3,a5 5ca: b7e5 j 5b2 <vprintf+0x60> if(c == 'd'){ 5cc: 05878063 beq a5,s8,60c <vprintf+0xba> } else if(c == 'l') { 5d0: 05978c63 beq a5,s9,628 <vprintf+0xd6> } else if(c == 'x') { 5d4: 07a78863 beq a5,s10,644 <vprintf+0xf2> } else if(c == 'p') { 5d8: 09b78463 beq a5,s11,660 <vprintf+0x10e> printptr(fd, va_arg(ap, uint64)); } else if(c == 's'){ 5dc: 07300713 li a4,115 5e0: 0ce78663 beq a5,a4,6ac <vprintf+0x15a> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 5e4: 06300713 li a4,99 5e8: 0ee78e63 beq a5,a4,6e4 <vprintf+0x192> putc(fd, va_arg(ap, uint)); } else if(c == '%'){ 5ec: 11478863 beq a5,s4,6fc <vprintf+0x1aa> putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 5f0: 85d2 mv a1,s4 5f2: 8556 mv a0,s5 5f4: 00000097 auipc ra,0x0 5f8: e92080e7 jalr -366(ra) # 486 <putc> putc(fd, c); 5fc: 85ca mv a1,s2 5fe: 8556 mv a0,s5 600: 00000097 auipc ra,0x0 604: e86080e7 jalr -378(ra) # 486 <putc> } state = 0; 608: 4981 li s3,0 60a: b765 j 5b2 <vprintf+0x60> printint(fd, va_arg(ap, int), 10, 1); 60c: 008b0913 addi s2,s6,8 610: 4685 li a3,1 612: 4629 li a2,10 614: 000b2583 lw a1,0(s6) 618: 8556 mv a0,s5 61a: 00000097 auipc ra,0x0 61e: e8e080e7 jalr -370(ra) # 4a8 <printint> 622: 8b4a mv s6,s2 state = 0; 624: 4981 li s3,0 626: b771 j 5b2 <vprintf+0x60> printint(fd, va_arg(ap, uint64), 10, 0); 628: 008b0913 addi s2,s6,8 62c: 4681 li a3,0 62e: 4629 li a2,10 630: 000b2583 lw a1,0(s6) 634: 8556 mv a0,s5 636: 00000097 auipc ra,0x0 63a: e72080e7 jalr -398(ra) # 4a8 <printint> 63e: 8b4a mv s6,s2 state = 0; 640: 4981 li s3,0 642: bf85 j 5b2 <vprintf+0x60> printint(fd, va_arg(ap, int), 16, 0); 644: 008b0913 addi s2,s6,8 648: 4681 li a3,0 64a: 4641 li a2,16 64c: 000b2583 lw a1,0(s6) 650: 8556 mv a0,s5 652: 00000097 auipc ra,0x0 656: e56080e7 jalr -426(ra) # 4a8 <printint> 65a: 8b4a mv s6,s2 state = 0; 65c: 4981 li s3,0 65e: bf91 j 5b2 <vprintf+0x60> printptr(fd, va_arg(ap, uint64)); 660: 008b0793 addi a5,s6,8 664: f8f43423 sd a5,-120(s0) 668: 000b3983 ld s3,0(s6) putc(fd, '0'); 66c: 03000593 li a1,48 670: 8556 mv a0,s5 672: 00000097 auipc ra,0x0 676: e14080e7 jalr -492(ra) # 486 <putc> putc(fd, 'x'); 67a: 85ea mv a1,s10 67c: 8556 mv a0,s5 67e: 00000097 auipc ra,0x0 682: e08080e7 jalr -504(ra) # 486 <putc> 686: 4941 li s2,16 putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]); 688: 03c9d793 srli a5,s3,0x3c 68c: 97de add a5,a5,s7 68e: 0007c583 lbu a1,0(a5) 692: 8556 mv a0,s5 694: 00000097 auipc ra,0x0 698: df2080e7 jalr -526(ra) # 486 <putc> for (i = 0; i < (sizeof(uint64) * 2); i++, x <<= 4) 69c: 0992 slli s3,s3,0x4 69e: 397d addiw s2,s2,-1 6a0: fe0914e3 bnez s2,688 <vprintf+0x136> printptr(fd, va_arg(ap, uint64)); 6a4: f8843b03 ld s6,-120(s0) state = 0; 6a8: 4981 li s3,0 6aa: b721 j 5b2 <vprintf+0x60> s = va_arg(ap, char*); 6ac: 008b0993 addi s3,s6,8 6b0: 000b3903 ld s2,0(s6) if(s == 0) 6b4: 02090163 beqz s2,6d6 <vprintf+0x184> while(*s != 0){ 6b8: 00094583 lbu a1,0(s2) 6bc: c9a1 beqz a1,70c <vprintf+0x1ba> putc(fd, *s); 6be: 8556 mv a0,s5 6c0: 00000097 auipc ra,0x0 6c4: dc6080e7 jalr -570(ra) # 486 <putc> s++; 6c8: 0905 addi s2,s2,1 while(*s != 0){ 6ca: 00094583 lbu a1,0(s2) 6ce: f9e5 bnez a1,6be <vprintf+0x16c> s = va_arg(ap, char*); 6d0: 8b4e mv s6,s3 state = 0; 6d2: 4981 li s3,0 6d4: bdf9 j 5b2 <vprintf+0x60> s = "(null)"; 6d6: 00000917 auipc s2,0x0 6da: 27290913 addi s2,s2,626 # 948 <malloc+0x12c> while(*s != 0){ 6de: 02800593 li a1,40 6e2: bff1 j 6be <vprintf+0x16c> putc(fd, va_arg(ap, uint)); 6e4: 008b0913 addi s2,s6,8 6e8: 000b4583 lbu a1,0(s6) 6ec: 8556 mv a0,s5 6ee: 00000097 auipc ra,0x0 6f2: d98080e7 jalr -616(ra) # 486 <putc> 6f6: 8b4a mv s6,s2 state = 0; 6f8: 4981 li s3,0 6fa: bd65 j 5b2 <vprintf+0x60> putc(fd, c); 6fc: 85d2 mv a1,s4 6fe: 8556 mv a0,s5 700: 00000097 auipc ra,0x0 704: d86080e7 jalr -634(ra) # 486 <putc> state = 0; 708: 4981 li s3,0 70a: b565 j 5b2 <vprintf+0x60> s = va_arg(ap, char*); 70c: 8b4e mv s6,s3 state = 0; 70e: 4981 li s3,0 710: b54d j 5b2 <vprintf+0x60> } } } 712: 70e6 ld ra,120(sp) 714: 7446 ld s0,112(sp) 716: 74a6 ld s1,104(sp) 718: 7906 ld s2,96(sp) 71a: 69e6 ld s3,88(sp) 71c: 6a46 ld s4,80(sp) 71e: 6aa6 ld s5,72(sp) 720: 6b06 ld s6,64(sp) 722: 7be2 ld s7,56(sp) 724: 7c42 ld s8,48(sp) 726: 7ca2 ld s9,40(sp) 728: 7d02 ld s10,32(sp) 72a: 6de2 ld s11,24(sp) 72c: 6109 addi sp,sp,128 72e: 8082 ret 0000000000000730 <fprintf>: void fprintf(int fd, const char *fmt, ...) { 730: 715d addi sp,sp,-80 732: ec06 sd ra,24(sp) 734: e822 sd s0,16(sp) 736: 1000 addi s0,sp,32 738: e010 sd a2,0(s0) 73a: e414 sd a3,8(s0) 73c: e818 sd a4,16(s0) 73e: ec1c sd a5,24(s0) 740: 03043023 sd a6,32(s0) 744: 03143423 sd a7,40(s0) va_list ap; va_start(ap, fmt); 748: fe843423 sd s0,-24(s0) vprintf(fd, fmt, ap); 74c: 8622 mv a2,s0 74e: 00000097 auipc ra,0x0 752: e04080e7 jalr -508(ra) # 552 <vprintf> } 756: 60e2 ld ra,24(sp) 758: 6442 ld s0,16(sp) 75a: 6161 addi sp,sp,80 75c: 8082 ret 000000000000075e <printf>: void printf(const char *fmt, ...) { 75e: 711d addi sp,sp,-96 760: ec06 sd ra,24(sp) 762: e822 sd s0,16(sp) 764: 1000 addi s0,sp,32 766: e40c sd a1,8(s0) 768: e810 sd a2,16(s0) 76a: ec14 sd a3,24(s0) 76c: f018 sd a4,32(s0) 76e: f41c sd a5,40(s0) 770: 03043823 sd a6,48(s0) 774: 03143c23 sd a7,56(s0) va_list ap; va_start(ap, fmt); 778: 00840613 addi a2,s0,8 77c: fec43423 sd a2,-24(s0) vprintf(1, fmt, ap); 780: 85aa mv a1,a0 782: 4505 li a0,1 784: 00000097 auipc ra,0x0 788: dce080e7 jalr -562(ra) # 552 <vprintf> } 78c: 60e2 ld ra,24(sp) 78e: 6442 ld s0,16(sp) 790: 6125 addi sp,sp,96 792: 8082 ret 0000000000000794 <free>: static Header base; static Header *freep; void free(void *ap) { 794: 1141 addi sp,sp,-16 796: e422 sd s0,8(sp) 798: 0800 addi s0,sp,16 Header *bp, *p; bp = (Header*)ap - 1; 79a: ff050693 addi a3,a0,-16 for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 79e: 00000797 auipc a5,0x0 7a2: 1ca7b783 ld a5,458(a5) # 968 <freep> 7a6: a805 j 7d6 <free+0x42> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 7a8: 4618 lw a4,8(a2) 7aa: 9db9 addw a1,a1,a4 7ac: feb52c23 sw a1,-8(a0) bp->s.ptr = p->s.ptr->s.ptr; 7b0: 6398 ld a4,0(a5) 7b2: 6318 ld a4,0(a4) 7b4: fee53823 sd a4,-16(a0) 7b8: a091 j 7fc <free+0x68> } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 7ba: ff852703 lw a4,-8(a0) 7be: 9e39 addw a2,a2,a4 7c0: c790 sw a2,8(a5) p->s.ptr = bp->s.ptr; 7c2: ff053703 ld a4,-16(a0) 7c6: e398 sd a4,0(a5) 7c8: a099 j 80e <free+0x7a> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 7ca: 6398 ld a4,0(a5) 7cc: 00e7e463 bltu a5,a4,7d4 <free+0x40> 7d0: 00e6ea63 bltu a3,a4,7e4 <free+0x50> { 7d4: 87ba mv a5,a4 for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 7d6: fed7fae3 bgeu a5,a3,7ca <free+0x36> 7da: 6398 ld a4,0(a5) 7dc: 00e6e463 bltu a3,a4,7e4 <free+0x50> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 7e0: fee7eae3 bltu a5,a4,7d4 <free+0x40> if(bp + bp->s.size == p->s.ptr){ 7e4: ff852583 lw a1,-8(a0) 7e8: 6390 ld a2,0(a5) 7ea: 02059813 slli a6,a1,0x20 7ee: 01c85713 srli a4,a6,0x1c 7f2: 9736 add a4,a4,a3 7f4: fae60ae3 beq a2,a4,7a8 <free+0x14> bp->s.ptr = p->s.ptr; 7f8: fec53823 sd a2,-16(a0) if(p + p->s.size == bp){ 7fc: 4790 lw a2,8(a5) 7fe: 02061593 slli a1,a2,0x20 802: 01c5d713 srli a4,a1,0x1c 806: 973e add a4,a4,a5 808: fae689e3 beq a3,a4,7ba <free+0x26> } else p->s.ptr = bp; 80c: e394 sd a3,0(a5) freep = p; 80e: 00000717 auipc a4,0x0 812: 14f73d23 sd a5,346(a4) # 968 <freep> } 816: 6422 ld s0,8(sp) 818: 0141 addi sp,sp,16 81a: 8082 ret 000000000000081c <malloc>: return freep; } void* malloc(uint nbytes) { 81c: 7139 addi sp,sp,-64 81e: fc06 sd ra,56(sp) 820: f822 sd s0,48(sp) 822: f426 sd s1,40(sp) 824: f04a sd s2,32(sp) 826: ec4e sd s3,24(sp) 828: e852 sd s4,16(sp) 82a: e456 sd s5,8(sp) 82c: e05a sd s6,0(sp) 82e: 0080 addi s0,sp,64 Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 830: 02051493 slli s1,a0,0x20 834: 9081 srli s1,s1,0x20 836: 04bd addi s1,s1,15 838: 8091 srli s1,s1,0x4 83a: 0014899b addiw s3,s1,1 83e: 0485 addi s1,s1,1 if((prevp = freep) == 0){ 840: 00000517 auipc a0,0x0 844: 12853503 ld a0,296(a0) # 968 <freep> 848: c515 beqz a0,874 <malloc+0x58> base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 84a: 611c ld a5,0(a0) if(p->s.size >= nunits){ 84c: 4798 lw a4,8(a5) 84e: 02977f63 bgeu a4,s1,88c <malloc+0x70> 852: 8a4e mv s4,s3 854: 0009871b sext.w a4,s3 858: 6685 lui a3,0x1 85a: 00d77363 bgeu a4,a3,860 <malloc+0x44> 85e: 6a05 lui s4,0x1 860: 000a0b1b sext.w s6,s4 p = sbrk(nu * sizeof(Header)); 864: 004a1a1b slliw s4,s4,0x4 p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 868: 00000917 auipc s2,0x0 86c: 10090913 addi s2,s2,256 # 968 <freep> if(p == (char*)-1) 870: 5afd li s5,-1 872: a895 j 8e6 <malloc+0xca> base.s.ptr = freep = prevp = &base; 874: 00000797 auipc a5,0x0 878: 0fc78793 addi a5,a5,252 # 970 <base> 87c: 00000717 auipc a4,0x0 880: 0ef73623 sd a5,236(a4) # 968 <freep> 884: e39c sd a5,0(a5) base.s.size = 0; 886: 0007a423 sw zero,8(a5) if(p->s.size >= nunits){ 88a: b7e1 j 852 <malloc+0x36> if(p->s.size == nunits) 88c: 02e48c63 beq s1,a4,8c4 <malloc+0xa8> p->s.size -= nunits; 890: 4137073b subw a4,a4,s3 894: c798 sw a4,8(a5) p += p->s.size; 896: 02071693 slli a3,a4,0x20 89a: 01c6d713 srli a4,a3,0x1c 89e: 97ba add a5,a5,a4 p->s.size = nunits; 8a0: 0137a423 sw s3,8(a5) freep = prevp; 8a4: 00000717 auipc a4,0x0 8a8: 0ca73223 sd a0,196(a4) # 968 <freep> return (void*)(p + 1); 8ac: 01078513 addi a0,a5,16 if((p = morecore(nunits)) == 0) return 0; } } 8b0: 70e2 ld ra,56(sp) 8b2: 7442 ld s0,48(sp) 8b4: 74a2 ld s1,40(sp) 8b6: 7902 ld s2,32(sp) 8b8: 69e2 ld s3,24(sp) 8ba: 6a42 ld s4,16(sp) 8bc: 6aa2 ld s5,8(sp) 8be: 6b02 ld s6,0(sp) 8c0: 6121 addi sp,sp,64 8c2: 8082 ret prevp->s.ptr = p->s.ptr; 8c4: 6398 ld a4,0(a5) 8c6: e118 sd a4,0(a0) 8c8: bff1 j 8a4 <malloc+0x88> hp->s.size = nu; 8ca: 01652423 sw s6,8(a0) free((void*)(hp + 1)); 8ce: 0541 addi a0,a0,16 8d0: 00000097 auipc ra,0x0 8d4: ec4080e7 jalr -316(ra) # 794 <free> return freep; 8d8: 00093503 ld a0,0(s2) if((p = morecore(nunits)) == 0) 8dc: d971 beqz a0,8b0 <malloc+0x94> for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 8de: 611c ld a5,0(a0) if(p->s.size >= nunits){ 8e0: 4798 lw a4,8(a5) 8e2: fa9775e3 bgeu a4,s1,88c <malloc+0x70> if(p == freep) 8e6: 00093703 ld a4,0(s2) 8ea: 853e mv a0,a5 8ec: fef719e3 bne a4,a5,8de <malloc+0xc2> p = sbrk(nu * sizeof(Header)); 8f0: 8552 mv a0,s4 8f2: 00000097 auipc ra,0x0 8f6: b6c080e7 jalr -1172(ra) # 45e <sbrk> if(p == (char*)-1) 8fa: fd5518e3 bne a0,s5,8ca <malloc+0xae> return 0; 8fe: 4501 li a0,0 900: bf45 j 8b0 <malloc+0x94>
; char *strdup_fastcall(const char * s) SECTION code_clib SECTION code_string PUBLIC _strdup_fastcall EXTERN asm_strdup defc _strdup_fastcall = asm_strdup
push ebp mov ebp, esp sub esp, 60 mov [esp-16], 3 mov [esp-4], 16 push 10 push 14 call someFuncThatTakesTwoArgs sub esp, 8 push 100
; A147601: First differences of A132355. ; 7,4,21,8,35,12,49,16,63,20,77,24,91,28,105,32,119,36,133,40,147,44,161,48,175,52,189,56,203,60,217,64,231,68,245,72,259,76,273,80,287,84,301,88,315,92,329,96,343,100,357 mov $3,$0 lpb $0,1 sub $0,1 add $1,5 lpe add $1,5 mov $0,$1 mod $0,2 mul $1,$0 add $1,2 mov $2,$3 mul $2,2 add $1,$2
; struct sp1_ss __CALLEE__ *sp1_CreateSpr_callee(void *drawf, uchar type, uchar height, int graphic, uchar plane) ; 03.2006 aralbrec, Sprite Pack v3.0 ; sinclair spectrum version PUBLIC sp1_CreateSpr_callee PUBLIC ASMDISP_SP1_CREATESPR_CALLEE EXTERN _sp1_struct_ss_prototype, _sp1_struct_cs_prototype EXTERN _u_malloc, _u_free .sp1_CreateSpr_callee pop ix pop bc pop hl pop de ld a,e pop de ld b,e pop de push ix .asmentry ; Create sprite of given height one column wide. Further columns are ; added with successive calls to SP1AddColSpr. ; ; enter : a = height in chars ; b = type: bit 7 = 1 occluding, bit 6 = 1 2 byte definition, bit 4 = 1 clear pixelbuff ; c = plane sprite occupies (0 = closest to viewer) ; de = address of draw function ; hl = graphic definition for column ; uses : all ; exit : no carry and hl=0 if memory allocation failed else hl = struct sp1_ss * and carry set .SP1CreateSpr push af ex af,af pop af ; a = a' = height exx ld hl,0 ; first try to get all the memory we need push hl ; push a 0 on stack to indicate end of allocated memory blocks ld b,a ; b = height .csalloc push bc ; save height counter ld hl,24 ; sizeof(struct sp1_cs) push hl call _u_malloc pop bc jp nc, fail pop bc push hl ; stack allocated block djnz csalloc ld hl,20 ; sizeof(struct sp1_ss) push hl call _u_malloc pop bc jp nc, fail push hl exx ex (sp),hl ; stack = graphic pointer push de ; save de = draw function push bc ; save b = type, c = plane ; have all necessary memory blocks on stack, hl = & struct sp1_ss ld de,_sp1_struct_ss_prototype ex de,hl ; hl = & struct sp1_ss prototype, de = & new struct sp1_ss ld ixl,e ld ixh,d ; ix = & struct sp1_ss ld bc,20 ; sizeof(struct sp1_ss) ldir ; copy prototype into new struct ; have copied prototype struct sp1_ss, now fill in the rest of the details ex af,af ; a = height ld (ix+3),a ; store height pop bc ; b = type, c = plane bit 6,b jr z, onebyte set 7,(ix+4) ; indicate 2-byte definition .onebyte ld a,b ; a = type and $90 or $40 ; a = type entry for struct sp1_cs pop de ; de = draw function pop hl ex (sp),hl ; stack = graphics ptr, hl = & first struct sp1_cs push de ; save draw function ld (ix+15),h ; store ptr to first struct sp1_cs in struct sp1_ss ld (ix+16),l ; done with struct sp1_ss, now do first struct sp1_cs ld de,_sp1_struct_cs_prototype ex de,hl ; hl = & struct sp1_cs prototype, de = & new struct sp1_cs ld iyl,e ld iyh,d ; iy = & struct sp1_cs push bc ; save c = plane ld bc,24 ; sizeof(struct sp1_cs) ldir ; copy prototype into new struct pop bc ; c = plane ; have copied prototype struct sp1_cs, now fill in the rest of the details ld (iy+4),c ; store plane ld (iy+5),a ; store type ld e,iyl ld d,iyh ld hl,10 add hl,de ex de,hl ; de = & struct sp1_cs.draw_code (& embedded code in struct sp1_cs) pop bc ; bc = draw function ld hl,-10 add hl,bc ; hl = embedded draw function code ld bc,10 ; length of draw code ldir ; copy draw code into struct sp1_cs ld a,ixl add a,8 ld (iy+8),a ; store & struct sp1_ss + 8 (& embedded code in struct sp1_ss) ld a,ixh adc a,0 ld (iy+9),a pop hl ; hl = graphics ptr ld (iy+11),l ; store graphics ptr ld (iy+12),h .loop ; ix = struct sp1_ss, iy = last struct sp1_cs added to sprite pop hl ; hl = & next struct sp1_cs to add ld a,h or l jr z, done push hl ld (iy+0),h ; store ptr to next struct sp1_cs ld (iy+1),l ld e,iyl ld d,iyh ex de,hl ; hl = last struct sp1_cs, de = new struct sp1_cs ld bc,24 ; sizeof(struct sp1_cs) ldir ; make copy of last one into new one ld e,(iy+11) ld d,(iy+12) ; de = graphics ptr from last struct sp1_cs pop iy ; iy = new struct sp1_cs ld (iy+0),c ; place 0 into struct sp1_cs.next_in_spr to indicate ld (iy+1),c ; this is currently last struct sp1_cs in sprite ld hl,8 ; offset to next character in sprite graphic def bit 7,(ix+4) jr z, onebyte2 ld l,16 ; if 2-byte def, offset is 16 bytes .onebyte2 add hl,de ld (iy+11),l ; store correct graphics ptr for this struct sp1_cs ld (iy+12),h jp loop .done set 5,(iy+5) ; indicate last struct sp1_cs added is in the last row of sprite ld a,ixl ld l,a ld a,ixh ld h,a scf ; indicate success ret .fail pop bc .faillp pop hl ; hl = allocated memory block ld a,h or l ret z ; if 0 done freeing, ret with nc for failure push hl call _u_free ; free the block pop hl jp faillp DEFC ASMDISP_SP1_CREATESPR_CALLEE = # asmentry - sp1_CreateSpr_callee
; ; jfdctfst.asm - fast integer FDCT (MMX) ; ; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB ; ; Based on ; x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 ; ; This file contains a fast, not so accurate integer implementation of ; the forward DCT (Discrete Cosine Transform). The following code is ; based directly on the IJG's original jfdctfst.c; see the jfdctfst.c ; for more details. ; ; [TAB8] %include "jsimdext.inc" %include "jdct.inc" ; -------------------------------------------------------------------------- %define CONST_BITS 8 ; 14 is also OK. %if CONST_BITS == 8 F_0_382 equ 98 ; FIX(0.382683433) F_0_541 equ 139 ; FIX(0.541196100) F_0_707 equ 181 ; FIX(0.707106781) F_1_306 equ 334 ; FIX(1.306562965) %else ; NASM cannot do compile-time arithmetic on floating-point constants. %define DESCALE(x,n) (((x)+(1<<((n)-1)))>>(n)) F_0_382 equ DESCALE( 410903207,30-CONST_BITS) ; FIX(0.382683433) F_0_541 equ DESCALE( 581104887,30-CONST_BITS) ; FIX(0.541196100) F_0_707 equ DESCALE( 759250124,30-CONST_BITS) ; FIX(0.707106781) F_1_306 equ DESCALE(1402911301,30-CONST_BITS) ; FIX(1.306562965) %endif ; -------------------------------------------------------------------------- SECTION SEG_CONST ; PRE_MULTIPLY_SCALE_BITS <= 2 (to avoid overflow) ; CONST_BITS + CONST_SHIFT + PRE_MULTIPLY_SCALE_BITS == 16 (for pmulhw) %define PRE_MULTIPLY_SCALE_BITS 2 %define CONST_SHIFT (16 - PRE_MULTIPLY_SCALE_BITS - CONST_BITS) alignz 16 global EXTN(jconst_fdct_ifast_mmx) PRIVATE EXTN(jconst_fdct_ifast_mmx): PW_F0707 times 4 dw F_0_707 << CONST_SHIFT PW_F0382 times 4 dw F_0_382 << CONST_SHIFT PW_F0541 times 4 dw F_0_541 << CONST_SHIFT PW_F1306 times 4 dw F_1_306 << CONST_SHIFT alignz 16 ; -------------------------------------------------------------------------- SECTION SEG_TEXT BITS 32 ; ; Perform the forward DCT on one block of samples. ; ; GLOBAL(void) ; jsimd_fdct_ifast_mmx (DCTELEM *data) ; %define data(b) (b)+8 ; DCTELEM *data %define original_ebp ebp+0 %define wk(i) ebp-(WK_NUM-(i))*SIZEOF_MMWORD ; mmword wk[WK_NUM] %define WK_NUM 2 align 16 global EXTN(jsimd_fdct_ifast_mmx) PRIVATE EXTN(jsimd_fdct_ifast_mmx): push ebp mov eax,esp ; eax = original ebp sub esp, byte 4 and esp, byte (-SIZEOF_MMWORD) ; align to 64 bits mov [esp],eax mov ebp,esp ; ebp = aligned ebp lea esp, [wk(0)] pushpic ebx ; push ecx ; need not be preserved ; push edx ; need not be preserved ; push esi ; unused ; push edi ; unused get_GOT ebx ; get GOT address ; ---- Pass 1: process rows. mov edx, POINTER [data(eax)] ; (DCTELEM *) mov ecx, DCTSIZE/4 alignx 16,7 .rowloop: movq mm0, MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)] movq mm2, MMWORD [MMBLOCK(2,1,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(3,1,edx,SIZEOF_DCTELEM)] ; mm0=(20 21 22 23), mm2=(24 25 26 27) ; mm1=(30 31 32 33), mm3=(34 35 36 37) movq mm4,mm0 ; transpose coefficients(phase 1) punpcklwd mm0,mm1 ; mm0=(20 30 21 31) punpckhwd mm4,mm1 ; mm4=(22 32 23 33) movq mm5,mm2 ; transpose coefficients(phase 1) punpcklwd mm2,mm3 ; mm2=(24 34 25 35) punpckhwd mm5,mm3 ; mm5=(26 36 27 37) movq mm6, MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)] movq mm7, MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(0,1,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(1,1,edx,SIZEOF_DCTELEM)] ; mm6=(00 01 02 03), mm1=(04 05 06 07) ; mm7=(10 11 12 13), mm3=(14 15 16 17) movq MMWORD [wk(0)], mm4 ; wk(0)=(22 32 23 33) movq MMWORD [wk(1)], mm2 ; wk(1)=(24 34 25 35) movq mm4,mm6 ; transpose coefficients(phase 1) punpcklwd mm6,mm7 ; mm6=(00 10 01 11) punpckhwd mm4,mm7 ; mm4=(02 12 03 13) movq mm2,mm1 ; transpose coefficients(phase 1) punpcklwd mm1,mm3 ; mm1=(04 14 05 15) punpckhwd mm2,mm3 ; mm2=(06 16 07 17) movq mm7,mm6 ; transpose coefficients(phase 2) punpckldq mm6,mm0 ; mm6=(00 10 20 30)=data0 punpckhdq mm7,mm0 ; mm7=(01 11 21 31)=data1 movq mm3,mm2 ; transpose coefficients(phase 2) punpckldq mm2,mm5 ; mm2=(06 16 26 36)=data6 punpckhdq mm3,mm5 ; mm3=(07 17 27 37)=data7 movq mm0,mm7 movq mm5,mm6 psubw mm7,mm2 ; mm7=data1-data6=tmp6 psubw mm6,mm3 ; mm6=data0-data7=tmp7 paddw mm0,mm2 ; mm0=data1+data6=tmp1 paddw mm5,mm3 ; mm5=data0+data7=tmp0 movq mm2, MMWORD [wk(0)] ; mm2=(22 32 23 33) movq mm3, MMWORD [wk(1)] ; mm3=(24 34 25 35) movq MMWORD [wk(0)], mm7 ; wk(0)=tmp6 movq MMWORD [wk(1)], mm6 ; wk(1)=tmp7 movq mm7,mm4 ; transpose coefficients(phase 2) punpckldq mm4,mm2 ; mm4=(02 12 22 32)=data2 punpckhdq mm7,mm2 ; mm7=(03 13 23 33)=data3 movq mm6,mm1 ; transpose coefficients(phase 2) punpckldq mm1,mm3 ; mm1=(04 14 24 34)=data4 punpckhdq mm6,mm3 ; mm6=(05 15 25 35)=data5 movq mm2,mm7 movq mm3,mm4 paddw mm7,mm1 ; mm7=data3+data4=tmp3 paddw mm4,mm6 ; mm4=data2+data5=tmp2 psubw mm2,mm1 ; mm2=data3-data4=tmp4 psubw mm3,mm6 ; mm3=data2-data5=tmp5 ; -- Even part movq mm1,mm5 movq mm6,mm0 psubw mm5,mm7 ; mm5=tmp13 psubw mm0,mm4 ; mm0=tmp12 paddw mm1,mm7 ; mm1=tmp10 paddw mm6,mm4 ; mm6=tmp11 paddw mm0,mm5 psllw mm0,PRE_MULTIPLY_SCALE_BITS pmulhw mm0,[GOTOFF(ebx,PW_F0707)] ; mm0=z1 movq mm7,mm1 movq mm4,mm5 psubw mm1,mm6 ; mm1=data4 psubw mm5,mm0 ; mm5=data6 paddw mm7,mm6 ; mm7=data0 paddw mm4,mm0 ; mm4=data2 movq MMWORD [MMBLOCK(0,1,edx,SIZEOF_DCTELEM)], mm1 movq MMWORD [MMBLOCK(2,1,edx,SIZEOF_DCTELEM)], mm5 movq MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)], mm7 movq MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)], mm4 ; -- Odd part movq mm6, MMWORD [wk(0)] ; mm6=tmp6 movq mm0, MMWORD [wk(1)] ; mm0=tmp7 paddw mm2,mm3 ; mm2=tmp10 paddw mm3,mm6 ; mm3=tmp11 paddw mm6,mm0 ; mm6=tmp12, mm0=tmp7 psllw mm2,PRE_MULTIPLY_SCALE_BITS psllw mm6,PRE_MULTIPLY_SCALE_BITS psllw mm3,PRE_MULTIPLY_SCALE_BITS pmulhw mm3,[GOTOFF(ebx,PW_F0707)] ; mm3=z3 movq mm1,mm2 ; mm1=tmp10 psubw mm2,mm6 pmulhw mm2,[GOTOFF(ebx,PW_F0382)] ; mm2=z5 pmulhw mm1,[GOTOFF(ebx,PW_F0541)] ; mm1=MULTIPLY(tmp10,FIX_0_54119610) pmulhw mm6,[GOTOFF(ebx,PW_F1306)] ; mm6=MULTIPLY(tmp12,FIX_1_30656296) paddw mm1,mm2 ; mm1=z2 paddw mm6,mm2 ; mm6=z4 movq mm5,mm0 psubw mm0,mm3 ; mm0=z13 paddw mm5,mm3 ; mm5=z11 movq mm7,mm0 movq mm4,mm5 psubw mm0,mm1 ; mm0=data3 psubw mm5,mm6 ; mm5=data7 paddw mm7,mm1 ; mm7=data5 paddw mm4,mm6 ; mm4=data1 movq MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)], mm0 movq MMWORD [MMBLOCK(3,1,edx,SIZEOF_DCTELEM)], mm5 movq MMWORD [MMBLOCK(1,1,edx,SIZEOF_DCTELEM)], mm7 movq MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)], mm4 add edx, byte 4*DCTSIZE*SIZEOF_DCTELEM dec ecx jnz near .rowloop ; ---- Pass 2: process columns. mov edx, POINTER [data(eax)] ; (DCTELEM *) mov ecx, DCTSIZE/4 alignx 16,7 .columnloop: movq mm0, MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)] movq mm2, MMWORD [MMBLOCK(6,0,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(7,0,edx,SIZEOF_DCTELEM)] ; mm0=(02 12 22 32), mm2=(42 52 62 72) ; mm1=(03 13 23 33), mm3=(43 53 63 73) movq mm4,mm0 ; transpose coefficients(phase 1) punpcklwd mm0,mm1 ; mm0=(02 03 12 13) punpckhwd mm4,mm1 ; mm4=(22 23 32 33) movq mm5,mm2 ; transpose coefficients(phase 1) punpcklwd mm2,mm3 ; mm2=(42 43 52 53) punpckhwd mm5,mm3 ; mm5=(62 63 72 73) movq mm6, MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)] movq mm7, MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(4,0,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(5,0,edx,SIZEOF_DCTELEM)] ; mm6=(00 10 20 30), mm1=(40 50 60 70) ; mm7=(01 11 21 31), mm3=(41 51 61 71) movq MMWORD [wk(0)], mm4 ; wk(0)=(22 23 32 33) movq MMWORD [wk(1)], mm2 ; wk(1)=(42 43 52 53) movq mm4,mm6 ; transpose coefficients(phase 1) punpcklwd mm6,mm7 ; mm6=(00 01 10 11) punpckhwd mm4,mm7 ; mm4=(20 21 30 31) movq mm2,mm1 ; transpose coefficients(phase 1) punpcklwd mm1,mm3 ; mm1=(40 41 50 51) punpckhwd mm2,mm3 ; mm2=(60 61 70 71) movq mm7,mm6 ; transpose coefficients(phase 2) punpckldq mm6,mm0 ; mm6=(00 01 02 03)=data0 punpckhdq mm7,mm0 ; mm7=(10 11 12 13)=data1 movq mm3,mm2 ; transpose coefficients(phase 2) punpckldq mm2,mm5 ; mm2=(60 61 62 63)=data6 punpckhdq mm3,mm5 ; mm3=(70 71 72 73)=data7 movq mm0,mm7 movq mm5,mm6 psubw mm7,mm2 ; mm7=data1-data6=tmp6 psubw mm6,mm3 ; mm6=data0-data7=tmp7 paddw mm0,mm2 ; mm0=data1+data6=tmp1 paddw mm5,mm3 ; mm5=data0+data7=tmp0 movq mm2, MMWORD [wk(0)] ; mm2=(22 23 32 33) movq mm3, MMWORD [wk(1)] ; mm3=(42 43 52 53) movq MMWORD [wk(0)], mm7 ; wk(0)=tmp6 movq MMWORD [wk(1)], mm6 ; wk(1)=tmp7 movq mm7,mm4 ; transpose coefficients(phase 2) punpckldq mm4,mm2 ; mm4=(20 21 22 23)=data2 punpckhdq mm7,mm2 ; mm7=(30 31 32 33)=data3 movq mm6,mm1 ; transpose coefficients(phase 2) punpckldq mm1,mm3 ; mm1=(40 41 42 43)=data4 punpckhdq mm6,mm3 ; mm6=(50 51 52 53)=data5 movq mm2,mm7 movq mm3,mm4 paddw mm7,mm1 ; mm7=data3+data4=tmp3 paddw mm4,mm6 ; mm4=data2+data5=tmp2 psubw mm2,mm1 ; mm2=data3-data4=tmp4 psubw mm3,mm6 ; mm3=data2-data5=tmp5 ; -- Even part movq mm1,mm5 movq mm6,mm0 psubw mm5,mm7 ; mm5=tmp13 psubw mm0,mm4 ; mm0=tmp12 paddw mm1,mm7 ; mm1=tmp10 paddw mm6,mm4 ; mm6=tmp11 paddw mm0,mm5 psllw mm0,PRE_MULTIPLY_SCALE_BITS pmulhw mm0,[GOTOFF(ebx,PW_F0707)] ; mm0=z1 movq mm7,mm1 movq mm4,mm5 psubw mm1,mm6 ; mm1=data4 psubw mm5,mm0 ; mm5=data6 paddw mm7,mm6 ; mm7=data0 paddw mm4,mm0 ; mm4=data2 movq MMWORD [MMBLOCK(4,0,edx,SIZEOF_DCTELEM)], mm1 movq MMWORD [MMBLOCK(6,0,edx,SIZEOF_DCTELEM)], mm5 movq MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)], mm7 movq MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)], mm4 ; -- Odd part movq mm6, MMWORD [wk(0)] ; mm6=tmp6 movq mm0, MMWORD [wk(1)] ; mm0=tmp7 paddw mm2,mm3 ; mm2=tmp10 paddw mm3,mm6 ; mm3=tmp11 paddw mm6,mm0 ; mm6=tmp12, mm0=tmp7 psllw mm2,PRE_MULTIPLY_SCALE_BITS psllw mm6,PRE_MULTIPLY_SCALE_BITS psllw mm3,PRE_MULTIPLY_SCALE_BITS pmulhw mm3,[GOTOFF(ebx,PW_F0707)] ; mm3=z3 movq mm1,mm2 ; mm1=tmp10 psubw mm2,mm6 pmulhw mm2,[GOTOFF(ebx,PW_F0382)] ; mm2=z5 pmulhw mm1,[GOTOFF(ebx,PW_F0541)] ; mm1=MULTIPLY(tmp10,FIX_0_54119610) pmulhw mm6,[GOTOFF(ebx,PW_F1306)] ; mm6=MULTIPLY(tmp12,FIX_1_30656296) paddw mm1,mm2 ; mm1=z2 paddw mm6,mm2 ; mm6=z4 movq mm5,mm0 psubw mm0,mm3 ; mm0=z13 paddw mm5,mm3 ; mm5=z11 movq mm7,mm0 movq mm4,mm5 psubw mm0,mm1 ; mm0=data3 psubw mm5,mm6 ; mm5=data7 paddw mm7,mm1 ; mm7=data5 paddw mm4,mm6 ; mm4=data1 movq MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)], mm0 movq MMWORD [MMBLOCK(7,0,edx,SIZEOF_DCTELEM)], mm5 movq MMWORD [MMBLOCK(5,0,edx,SIZEOF_DCTELEM)], mm7 movq MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)], mm4 add edx, byte 4*SIZEOF_DCTELEM dec ecx jnz near .columnloop emms ; empty MMX state ; pop edi ; unused ; pop esi ; unused ; pop edx ; need not be preserved ; pop ecx ; need not be preserved poppic ebx mov esp,ebp ; esp <- aligned ebp pop esp ; esp <- original ebp pop ebp ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 16
; A268292: a(n) is the total number of isolated 1's at the boundary between n-th and (n-1)-th iterations in the pattern of A267489. ; 0,0,0,0,0,0,0,1,3,5,7,9,11,14,18,22,26,30,34,39,45,51,57,63,69,76,84,92,100,108,116,125,135,145,155,165,175,186,198,210,222,234,246,259,273,287,301,315,329,344,360,376,392,408,424,441 lpb $0,1 trn $0,6 trn $1,1 add $1,$0 add $1,$0 lpe
/** * Copyright 2020 The Magma Authors. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <google/protobuf/util/time_util.h> #include <cassert> #include <grpcpp/impl/codegen/client_context.h> #include <grpcpp/impl/codegen/status.h> #include <cstring> #include <iostream> #include <memory> #include <string> #include <thread> #include <lte/protos/session_manager.grpc.pb.h> #include <lte/protos/session_manager.pb.h> #include <arpa/inet.h> #include <utility> #include "orc8r/gateway/c/common/service_registry/includes/ServiceRegistrySingleton.h" #include "lte/gateway/c/core/oai/lib/n11/SmfServiceClient.h" using grpc::Status; using magma::AsyncLocalResponse; using magma::ServiceRegistrySingleton; void handle_session_context_response( grpc::Status status, magma::lte::SmContextVoid response) { if (!status.ok()) { std::cout << "AsyncSetAmfSessionContext fails with code " << status.error_code() << ", msg: " << status.error_message() << std::endl; } } using namespace magma::lte; namespace magma5g { SetSMSessionContext create_sm_pdu_session( std::string& imsi, uint8_t* apn, uint32_t pdu_session_id, uint32_t pdu_session_type, uint32_t gnb_gtp_teid, uint8_t pti, uint8_t* gnb_gtp_teid_ip_addr, std::string& ip4, std::string& ip6, const ambr_t& state_ambr, uint32_t version) { magma::lte::SetSMSessionContext req; auto* req_common = req.mutable_common_context(); // Encode IMSI req_common->mutable_sid()->set_id("IMSI" + imsi); // Encode TYPE IMSI req_common->mutable_sid()->set_type( magma::lte::SubscriberID_IDType::SubscriberID_IDType_IMSI); // Encode APU, storing apn value req_common->set_apn((char*) apn); // Encode RAT TYPE req_common->set_rat_type(magma::lte::RATType::TGPP_NR); // Put in CREATING STATE req_common->set_sm_session_state(magma::lte::SMSessionFSMState::CREATING_0); // Create with Default Version req_common->set_sm_session_version(version); if (!ip4.empty()) { // Set the IPv4 PDU Address req_common->set_ue_ipv4(ip4); } if (!ip6.empty()) { // Set the IPv6 PDU Address req_common->set_ue_ipv6(ip6); } auto* req_rat_specific = req.mutable_rat_specific_context()->mutable_m5gsm_session_context(); // Set the Session ID req_rat_specific->set_pdu_session_id(pdu_session_id); // Set the Type of Request req_rat_specific->set_request_type(magma::lte::RequestType::INITIAL_REQUEST); // TEID of GNB req_rat_specific->mutable_gnode_endpoint()->set_teid(gnb_gtp_teid); // IP Address of GNB char ipv4_str[INET_ADDRSTRLEN] = {0}; inet_ntop(AF_INET, gnb_gtp_teid_ip_addr, ipv4_str, INET_ADDRSTRLEN); req_rat_specific->mutable_gnode_endpoint()->set_end_ipv4_addr(ipv4_str); // Set the PTI req_rat_specific->set_procedure_trans_identity((const char*) (&(pti))); // Set the default QoS values req_rat_specific->mutable_default_ambr()->set_max_bandwidth_ul( state_ambr.br_ul); req_rat_specific->mutable_default_ambr()->set_max_bandwidth_dl( state_ambr.br_dl); // For UT // state_ambr.br_unit = 1; req_rat_specific->mutable_default_ambr()->set_br_unit( static_cast<magma::lte::AggregatedMaximumBitrate::BitrateUnitsAMBR>( state_ambr.br_unit)); return (req); } int AsyncSmfServiceClient::amf_smf_create_pdu_session( char* imsi, uint8_t* apn, uint32_t pdu_session_id, uint32_t pdu_session_type, uint32_t gnb_gtp_teid, uint8_t pti, uint8_t* gnb_gtp_teid_ip_addr, char* ue_ipv4_addr, char* ue_ipv6_addr, const ambr_t& state_ambr, uint32_t version) { std::string ip4_str, ip6_str; if (ue_ipv4_addr) { ip4_str = ue_ipv4_addr; } if (ue_ipv6_addr) { ip6_str = ue_ipv6_addr; } auto imsi_str = std::string(imsi); magma::lte::SetSMSessionContext req = create_sm_pdu_session( imsi_str, apn, pdu_session_id, pdu_session_type, gnb_gtp_teid, pti, gnb_gtp_teid_ip_addr, ip4_str, ip6_str, state_ambr, version); AsyncSmfServiceClient::getInstance().set_smf_session(req); return 0; } bool AsyncSmfServiceClient::set_smf_session(SetSMSessionContext& request) { SetSMFSessionRPC( request, [](const Status& status, const SmContextVoid& response) { handle_session_context_response(status, response); }); return true; } void AsyncSmfServiceClient::SetSMFSessionRPC( SetSMSessionContext& request, const std::function<void(Status, SmContextVoid)>& callback) { auto localResp = new AsyncLocalResponse<SmContextVoid>( std::move(callback), RESPONSE_TIMEOUT); localResp->set_response_reader(std::move(stub_->AsyncSetAmfSessionContext( localResp->get_context(), request, &queue_))); } bool AsyncSmfServiceClient::set_smf_notification( SetSmNotificationContext& notify) { SetSMFNotificationRPC( notify, [](const Status& status, const SmContextVoid& response) { handle_session_context_response(status, response); }); return true; } void AsyncSmfServiceClient::SetSMFNotificationRPC( SetSmNotificationContext& notify, const std::function<void(Status, SmContextVoid)>& callback) { auto localResp = new AsyncLocalResponse<SmContextVoid>( std::move(callback), RESPONSE_TIMEOUT); localResp->set_response_reader(std::move(stub_->AsyncSetSmfNotification( localResp->get_context(), notify, &queue_))); } AsyncSmfServiceClient::AsyncSmfServiceClient() { auto channel = ServiceRegistrySingleton::Instance()->GetGrpcChannel( "sessiond", ServiceRegistrySingleton::LOCAL); stub_ = AmfPduSessionSmContext::NewStub(channel); std::thread resp_loop_thread([&]() { rpc_response_loop(); }); resp_loop_thread.detach(); } AsyncSmfServiceClient& AsyncSmfServiceClient::getInstance() { static AsyncSmfServiceClient instance; return instance; } bool AsyncSmfServiceClient::n11_update_location_req( const s6a_update_location_req_t* const ulr_p) { return s6a_update_location_req(ulr_p); } } // namespace magma5g
; $Id: bit_open.asm,v 1.4 2016-06-16 20:23:52 dom Exp $ ; ; TI calculator "Infrared port" 1 bit sound functions stub ; ; void bit_open(); ; ; Stefano Bodrato - 24/10/2001 ; SECTION code_clib PUBLIC bit_open PUBLIC _bit_open .bit_open ._bit_open IF FORti82 ld a,@11000000 ; Set W1 and R1 out (0),a ld a,@11010100 ENDIF IF FORti83 ld a,@11010000 ENDIF IF FORti85 ld a,@11000000 out (7),a ENDIF IF FORti86 ld a,@11000000 out (7),a ENDIF ret
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r8 push %r9 push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x2b28, %r8 nop nop nop and %rsi, %rsi mov $0x6162636465666768, %r10 movq %r10, (%r8) nop dec %r10 lea addresses_WT_ht+0x1b1f8, %r13 nop and %r9, %r9 movb (%r13), %cl nop nop nop add $27185, %r13 lea addresses_UC_ht+0x6338, %rsi lea addresses_WC_ht+0x4097, %rdi nop nop nop nop add $33055, %r10 mov $91, %rcx rep movsb cmp $24122, %rcx lea addresses_WT_ht+0x3ab8, %rsi lea addresses_UC_ht+0xb750, %rdi sub %rdx, %rdx mov $29, %rcx rep movsl nop nop nop xor %rdx, %rdx lea addresses_A_ht+0x88b8, %rcx clflush (%rcx) nop nop nop nop nop and $15064, %rdi mov $0x6162636465666768, %r8 movq %r8, (%rcx) nop nop nop sub %rdi, %rdi pop %rsi pop %rdx pop %rdi pop %rcx pop %r9 pop %r8 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r13 push %r15 push %r8 push %rcx push %rdi push %rsi // REPMOV lea addresses_PSE+0x16338, %rsi mov $0x28f2fb00000002f8, %rdi nop nop nop nop xor %r15, %r15 mov $0, %rcx rep movsw nop cmp $11808, %r15 // Faulty Load lea addresses_PSE+0x16338, %r13 clflush (%r13) nop nop xor %rcx, %rcx movb (%r13), %r8b lea oracles, %r15 and $0xff, %r8 shlq $12, %r8 mov (%r15,%r8,1), %r8 pop %rsi pop %rdi pop %rcx pop %r8 pop %r15 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': True, 'congruent': 0, 'type': 'addresses_PSE'}, 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_NC'}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 4}} {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_WC_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_UC_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 6}} {'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 */
; A319410: Twice A032741. ; Submitted by Jamie Morken(w2) ; 0,0,2,2,4,2,6,2,6,4,6,2,10,2,6,6,8,2,10,2,10,6,6,2,14,4,6,6,10,2,14,2,10,6,6,6,16,2,6,6,14,2,14,2,10,10,6,2,18,4,10,6,10,2,14,6,14,6,6,2,22,2,6,10,12,6,14,2,10,6,14,2,22,2,6,10,10,6,14,2,18,8,6,2,22,6,6,6,14,2,22,6,10,6,6,6,22,2,10,10 mov $2,$0 mul $2,2 lpb $0 mov $3,$2 dif $3,$0 sub $0,2 cmp $3,$2 add $4,$3 lpe lpb $2 mov $1,$2 mul $4,4 sub $1,$4 cmp $2,3 lpe div $1,4 mov $0,$1 mul $0,2
COPY START 0 .COPY FILE FROM INPUT TO OUTPUT FIRST STL RETADR .SAVE TETURN ADDRESS LDB #LENGTH .ESTABLISH BASE REGISTER BASE LENGTH CLOOP +JSUB RDREC .READ INPUT RECORD LDA LENGTH .TEST FOR EOF COMP #0 JEQ ENDFIL .EXIT IF EOF FOUND +JSUB WRREC .WRITE OUTPUT RECORD J CLOOP ENDFIL LDA =C'EOF' .INSERT END OF FILE MARKER STA BUFFER LDA #3 STA LENGTH +JSUB WRREC .WRITE EOF J @RETADR .RETURN TO CALLER LTORG RETADR RESW 1 LENGTH RESW 1 .LENGTH OF THE RECORD BUFFER RESB 4096 .4096-BYTE BUFFER AREA BUFEND EQU * MAXLEN EQU BUFFEND-BUFFER .MAXIMUM RECORD LENGTH . . SUBROUTINE TO READ RECORD INTO BUFFER . RDREC CLEAR X .CLEAR LOOP COUNTER CLEAR A .CLEAR A TO ZERO CLEAR S .CLEAR S TO ZERO +LDT #MAXLEN RLOOP TD INPUT .TEST INPUT DEVICE JEQ RLOOP .LOOP UNTIL READY RD INPUT .READ CHARACTER INTO REGISTER A COMPR A,S .TEST FOR END OF RECORD (X'00') JEQ EXIT .EXIT LOOP IF EOR STCH BUFFER,X .CTORE CHARACTER IN BUFFER TIXR T .LOOP UNLESS MAX LENGTH HAS BEEN REACHED JLT RLOOP EXIT STX LENGTH .SAVE RECORD LENGTH RSUB .RETURN TO CALLER INPUT BYTE X'F1' .CODE FOR INPUT DEVICE . . SUBROUTINE TO WRITE RECORD INTO BUFFER . WRREC CLEAR X .CLEAR LOOP COUNTER LDT LENGTH WLOOP TD =X'05' .TEST INPUT DEVICE JEQ WLOOP .LOOP UNTIL READY LDCH BUFFER,X .GET CHARACTER FROM BUFFER WD =X'05' .WRITE CHARACTER TIXR T .LOOP UNTIL ALL CHARACTERS HAVE BEEN WRITTEN JLT WLOOP RSUB .RETURN TO CALLER END FIRST
; A304659: a(n) = n*(n + 1)*(16*n - 1)/6. ; 0,5,31,94,210,395,665,1036,1524,2145,2915,3850,4966,6279,7805,9560,11560,13821,16359,19190,22330,25795,29601,33764,38300,43225,48555,54306,60494,67135,74245,81840,89936,98549,107695,117390,127650,138491,149929,161980,174660,187985,201971,216634,231990,248055,264845,282376,300664,319725,339575,360230,381706,404019,427185,451220,476140,501961,528699,556370,584990,614575,645141,676704,709280,742885,777535,813246,850034,887915,926905,967020,1008276,1050689,1094275,1139050,1185030,1232231,1280669 mov $1,$0 add $0,1 mul $1,16 bin $1,2 mul $0,$1 div $0,48
; A275794: One half of the y members of the positive proper solutions (x = x1(n), y = y1(n)) of the first class for the Pell equation x^2 - 2*y^2 = +7^2. ; 2,15,88,513,2990,17427,101572,592005,3450458,20110743,117214000,683173257,3981825542,23207779995,135264854428,788381346573,4595023225010,26781758003487,156095524795912,909791390771985,5302652819835998,30906125528244003,180134100349628020,1049898476569524117,6119256759067516682,35665642077835575975,207874595707945939168,1211581932169840059033,7061616997311094415030,41158120051696726431147,239887103312869264171852,1398164499825518858599965,8149099895640243887427938,47496434874015944465967663,276829509348455422908378040,1613480621216716592984300577,9404054217951844134997425422,54810844686494348217000251955,319461013901014245167004086308,1861955238719591122785024265893,10852270418416532491543141509050,63251667271779603826473824788407,368657733212261090467299807221392,2148694732001786938977325018539945,12523510658798460543396650304018278,72992369220788976321402576805569723,425430704665935397385018810529400060 mov $1,4 mov $2,9 lpb $0 sub $0,1 add $2,$1 add $1,$2 add $1,$2 add $2,$1 lpe div $1,2 mov $0,$1
dnl X86-64 mpn_lshift optimised for AMD K10. dnl Copyright 2012 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') ABI_SUPPORT(DOS64) ABI_SUPPORT(STD64) MULFUNC_PROLOGUE(mpn_lshift) include_mpn(`x86_64/fastsse/lshift-movdqu2.asm')
;;; ;;; This is Suggested Project 7.9.2.1 ;;; Basically do simple addition, subtraction, multiplication, modulo ;;; Pg. 136 for the problem ;;; Pg. 24 for Registers ;;; Pg. 48 for Data Types SECTION .data SUCCESS: equ 0 ; Default success value SYS_EXIT: equ 60 ; Default system exit value ;; Variables used by the project bNum1: db 10 bNum2: db 2 bNum3: db 3 bNum4: db 4 wNum1: dw 300 ;; Answers bAns1: db 0 ; bAns1 = bNum1 + bNum2 12 bAns2: db 0 ; bAns2 = bNum1 + bNum3 13 bAns3: db 0 ; bAns3 = bNum3 + bNum4 7 bAns6: db 0 ; bAns6 = bNum1 - bNum2 8 bAns7: db 0 ; bAns7 = bNum1 - bNum3 7 bAns8: db 0 ; bAns8 = bNum2 - bNum4 254 2^8 = 256 - 2 = 254 wAns11: dw 0 ; wAns11 = bNum1 * bNum3 30 wAns12: dw 0 ; wAns12 = bNum2 * bNum2 4 wAns13: dw 0 ; wAns13 = bNum2 * bNum4 8 bAns16: db 0 ; bAns16 = bNum1 / bNum2 5 bAns17: db 0 ; bAns17 = bNum3 / bNum4 0 bAns18: db 0 ; bAns18 = wNum1 / bNum4 75 bRem18: db 0 ; bRem18 = wNum1 % bNum4 0 SECTION .text ; Code Section global _start ; Standard start _start: ;; bAns1 = bNum1 + bNum2 mov al, byte [bNum1] add al, byte [bNum2] mov byte [bAns1], al ;; bAns2 = bNum1 + bNum3 mov al, byte [bNum1] add al, byte [bNum3] mov byte [bAns2], al ;; bAns3 = bNum3 + bNum4 mov al, byte [bNum3] add al, byte [bNum4] mov byte [bAns3], al ;; bAns6 = bNum1 - bNum2 mov al, byte [bNum1] sub al, byte [bNum2] mov byte [bAns6], al ;; bAns7 = bNum1 - bNum3 mov al, byte [bNum1] sub al, byte [bNum3] mov byte [bAns7], al ;; bAns8 = bNum2 - bNum4 mov al, byte [bNum2] sub al, byte [bNum4] mov byte [bAns8], al ;; wAns11 = bNum1 * bNum3 mov al, byte [bNum1] mul byte [bNum3] mov word [wAns11], ax ;; wAns12 = bNum2 * bNum2 mov al, byte [bNum2] mul al mov word [wAns12], ax ;; wAns13 = bNum2 * bNum4 mov al, byte [bNum2] mul byte [bNum4] mov word [wAns13], ax ;; bAns16 = bNum1 / bNum2 mov al, byte [bNum1] div byte [bNum2] mov byte [bAns16], al ;; bAns17 = bNum3 / bNum4 mov al, byte [bNum3] div byte [bNum4] mov byte [bAns17], al ;; bAns18 = wNum1 / bNum4 mov ax, word [wNum1] div byte [bNum4] mov byte [bAns18], al ;; bRem18 = wNum1 % bNum4 mov ax, word [wNum1] div byte [bNum4] mov byte [bRem18], ah ; Remember the remainder is stored in ah ; Done, terminate program last: mov rax, SYS_EXIT ; Call code for exit mov rdi, SUCCESS ; Exit with success syscall
; A098229: a(n)=6*c(n,1) where n runs through the 3-smooth numbers (see comment). ; Submitted by Jon Maiga ; 0,3,2,3,5,3,2,5,3,5,5,2,3,5,5,5,3,5,2,5,5,3,5,5,5,5,2,3,5,5,5,5,5,3,5,5,2,5,5,5,3,5,5,5,5,5,5,3,2,5,5,5,5,5,5,3,5,5,5,5,5,2,5,5,3,5,5,5,5,5,5,5,5,3,5,5,2,5,5,5,5,5,5,3,5,5,5,5,5,5,5,5,2,5,3,5,5,5,5,5 seq $0,33031 ; Squarefree kernels of 3-smooth numbers. mov $2,$0 add $$0,$0 mov $0,$2 sub $0,1
SECTION code_stdlib PUBLIC __dtoa_round __dtoa_round: ; HL = buffer_dst * ; IX = buffer * ; (IX-6) = flags, bit 7 = 'N', bit 4 = '#', bit 0 = precision==0 ; (IX-5) = iz (number of zeroes to insert before .) ; (IX-4) = fz (number of zeroes to insert after .) ; (IX-3) = tz (number of zeroes to append) ; (IX-2) = ignore ; (IX-1) = '0' marks start of buffer dec hl ; point at rounding digit ld a,(hl) cp '5' ret c ; if round down push hl loop_round: dec hl ld a,(hl) cp '.' jr z, loop_round ld (hl),'0' cp '9' jr z, loop_round inc a ld (hl),a pop hl ret
_foo: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "user.h" #include "fcntl.h" int main(int argc, char const *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 57 push %edi e: 56 push %esi f: 53 push %ebx 10: 51 push %ecx 11: 83 ec 28 sub $0x28,%esp 14: 8b 19 mov (%ecx),%ebx 16: 8b 79 04 mov 0x4(%ecx),%edi int k,n,id; double x = 0,z,d; if(argc <2) 19: 83 fb 01 cmp $0x1,%ebx 1c: 7f 67 jg 85 <main+0x85> if( n < 0 || n > 20 ) n = 2; if( argc < 3) d = 1.0; 1e: d9 e8 fld1 n=1; //default value 20: be 01 00 00 00 mov $0x1,%esi d = 1.0; 25: dd 5d d0 fstpl -0x30(%ebp) n=1; //default value 28: 31 db xor %ebx,%ebx 2a: eb 16 jmp 42 <main+0x42> 2c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi id = 0; for( k=0; k<n; k++){ id = fork(); if(id < 0) printf(1,"%d failed in fork!\n",getpid()); else if(id > 0){ //parent 30: 0f 84 8f 00 00 00 je c5 <main+0xc5> for( k=0; k<n; k++){ 36: 83 c3 01 add $0x1,%ebx // printf(1, "Parent %d created child %d\n",getpid(),id); wait(); 39: e8 2c 03 00 00 call 36a <wait> for( k=0; k<n; k++){ 3e: 39 f3 cmp %esi,%ebx 40: 7d 2e jge 70 <main+0x70> id = fork(); 42: e8 13 03 00 00 call 35a <fork> if(id < 0) 47: 85 c0 test %eax,%eax 49: 79 e5 jns 30 <main+0x30> printf(1,"%d failed in fork!\n",getpid()); 4b: e8 92 03 00 00 call 3e2 <getpid> 50: 83 ec 04 sub $0x4,%esp for( k=0; k<n; k++){ 53: 83 c3 01 add $0x1,%ebx printf(1,"%d failed in fork!\n",getpid()); 56: 50 push %eax 57: 68 28 08 00 00 push $0x828 5c: 6a 01 push $0x1 5e: e8 6d 04 00 00 call 4d0 <printf> 63: 83 c4 10 add $0x10,%esp for( k=0; k<n; k++){ 66: 39 f3 cmp %esi,%ebx 68: 7c d8 jl 42 <main+0x42> 6a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi sleep(100); break; } } int wtime,rtime; waitx(&wtime,&rtime); 70: 8d 45 e4 lea -0x1c(%ebp),%eax 73: 83 ec 08 sub $0x8,%esp 76: 50 push %eax 77: 8d 45 e0 lea -0x20(%ebp),%eax 7a: 50 push %eax 7b: e8 92 03 00 00 call 412 <waitx> // printf(1,"wtime = %d, rtime = %d\n",wtime,rtime); exit(); 80: e8 dd 02 00 00 call 362 <exit> n = atoi(argv[1]); //from command line 85: 83 ec 0c sub $0xc,%esp 88: ff 77 04 pushl 0x4(%edi) 8b: e8 60 02 00 00 call 2f0 <atoi> if( n < 0 || n > 20 ) 90: 83 c4 10 add $0x10,%esp 93: 83 f8 14 cmp $0x14,%eax n = atoi(argv[1]); //from command line 96: 89 c6 mov %eax,%esi if( n < 0 || n > 20 ) 98: 76 63 jbe fd <main+0xfd> if( argc < 3) 9a: 83 fb 02 cmp $0x2,%ebx 9d: 7e 4f jle ee <main+0xee> n = 2; 9f: be 02 00 00 00 mov $0x2,%esi d = atoi(argv[2]); a4: 83 ec 0c sub $0xc,%esp a7: ff 77 08 pushl 0x8(%edi) aa: e8 41 02 00 00 call 2f0 <atoi> af: 89 45 d0 mov %eax,-0x30(%ebp) b2: 83 c4 10 add $0x10,%esp b5: db 45 d0 fildl -0x30(%ebp) b8: dd 5d d0 fstpl -0x30(%ebp) for( k=0; k<n; k++){ bb: 85 f6 test %esi,%esi bd: 0f 85 65 ff ff ff jne 28 <main+0x28> c3: eb ab jmp 70 <main+0x70> for( z = 0; z < 8000000.0; z += d) c5: d9 ee fldz c7: 89 f6 mov %esi,%esi c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi d0: dc 45 d0 faddl -0x30(%ebp) d3: d9 05 3c 08 00 00 flds 0x83c d9: df e9 fucomip %st(1),%st db: 77 f3 ja d0 <main+0xd0> dd: dd d8 fstp %st(0) sleep(100); df: 83 ec 0c sub $0xc,%esp e2: 6a 64 push $0x64 e4: e8 09 03 00 00 call 3f2 <sleep> break; e9: 83 c4 10 add $0x10,%esp ec: eb 82 jmp 70 <main+0x70> d = 1.0; ee: d9 e8 fld1 n = 2; f0: be 02 00 00 00 mov $0x2,%esi d = 1.0; f5: dd 5d d0 fstpl -0x30(%ebp) f8: e9 2b ff ff ff jmp 28 <main+0x28> if( argc < 3) fd: 83 fb 02 cmp $0x2,%ebx 100: 75 a2 jne a4 <main+0xa4> d = 1.0; 102: d9 e8 fld1 104: dd 5d d0 fstpl -0x30(%ebp) 107: eb b2 jmp bb <main+0xbb> 109: 66 90 xchg %ax,%ax 10b: 66 90 xchg %ax,%ax 10d: 66 90 xchg %ax,%ax 10f: 90 nop 00000110 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 110: 55 push %ebp 111: 89 e5 mov %esp,%ebp 113: 53 push %ebx 114: 8b 45 08 mov 0x8(%ebp),%eax 117: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 11a: 89 c2 mov %eax,%edx 11c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 120: 83 c1 01 add $0x1,%ecx 123: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 127: 83 c2 01 add $0x1,%edx 12a: 84 db test %bl,%bl 12c: 88 5a ff mov %bl,-0x1(%edx) 12f: 75 ef jne 120 <strcpy+0x10> ; return os; } 131: 5b pop %ebx 132: 5d pop %ebp 133: c3 ret 134: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 13a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000140 <strcmp>: int strcmp(const char *p, const char *q) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 53 push %ebx 144: 8b 55 08 mov 0x8(%ebp),%edx 147: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 14a: 0f b6 02 movzbl (%edx),%eax 14d: 0f b6 19 movzbl (%ecx),%ebx 150: 84 c0 test %al,%al 152: 75 1c jne 170 <strcmp+0x30> 154: eb 2a jmp 180 <strcmp+0x40> 156: 8d 76 00 lea 0x0(%esi),%esi 159: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 160: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 163: 0f b6 02 movzbl (%edx),%eax p++, q++; 166: 83 c1 01 add $0x1,%ecx 169: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) 16c: 84 c0 test %al,%al 16e: 74 10 je 180 <strcmp+0x40> 170: 38 d8 cmp %bl,%al 172: 74 ec je 160 <strcmp+0x20> return (uchar)*p - (uchar)*q; 174: 29 d8 sub %ebx,%eax } 176: 5b pop %ebx 177: 5d pop %ebp 178: c3 ret 179: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 180: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 182: 29 d8 sub %ebx,%eax } 184: 5b pop %ebx 185: 5d pop %ebp 186: c3 ret 187: 89 f6 mov %esi,%esi 189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000190 <strlen>: uint strlen(const char *s) { 190: 55 push %ebp 191: 89 e5 mov %esp,%ebp 193: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 196: 80 39 00 cmpb $0x0,(%ecx) 199: 74 15 je 1b0 <strlen+0x20> 19b: 31 d2 xor %edx,%edx 19d: 8d 76 00 lea 0x0(%esi),%esi 1a0: 83 c2 01 add $0x1,%edx 1a3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 1a7: 89 d0 mov %edx,%eax 1a9: 75 f5 jne 1a0 <strlen+0x10> ; return n; } 1ab: 5d pop %ebp 1ac: c3 ret 1ad: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) 1b0: 31 c0 xor %eax,%eax } 1b2: 5d pop %ebp 1b3: c3 ret 1b4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 1ba: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000001c0 <memset>: void* memset(void *dst, int c, uint n) { 1c0: 55 push %ebp 1c1: 89 e5 mov %esp,%ebp 1c3: 57 push %edi 1c4: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 1c7: 8b 4d 10 mov 0x10(%ebp),%ecx 1ca: 8b 45 0c mov 0xc(%ebp),%eax 1cd: 89 d7 mov %edx,%edi 1cf: fc cld 1d0: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 1d2: 89 d0 mov %edx,%eax 1d4: 5f pop %edi 1d5: 5d pop %ebp 1d6: c3 ret 1d7: 89 f6 mov %esi,%esi 1d9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001e0 <strchr>: char* strchr(const char *s, char c) { 1e0: 55 push %ebp 1e1: 89 e5 mov %esp,%ebp 1e3: 53 push %ebx 1e4: 8b 45 08 mov 0x8(%ebp),%eax 1e7: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 1ea: 0f b6 10 movzbl (%eax),%edx 1ed: 84 d2 test %dl,%dl 1ef: 74 1d je 20e <strchr+0x2e> if(*s == c) 1f1: 38 d3 cmp %dl,%bl 1f3: 89 d9 mov %ebx,%ecx 1f5: 75 0d jne 204 <strchr+0x24> 1f7: eb 17 jmp 210 <strchr+0x30> 1f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 200: 38 ca cmp %cl,%dl 202: 74 0c je 210 <strchr+0x30> for(; *s; s++) 204: 83 c0 01 add $0x1,%eax 207: 0f b6 10 movzbl (%eax),%edx 20a: 84 d2 test %dl,%dl 20c: 75 f2 jne 200 <strchr+0x20> return (char*)s; return 0; 20e: 31 c0 xor %eax,%eax } 210: 5b pop %ebx 211: 5d pop %ebp 212: c3 ret 213: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 219: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000220 <gets>: char* gets(char *buf, int max) { 220: 55 push %ebp 221: 89 e5 mov %esp,%ebp 223: 57 push %edi 224: 56 push %esi 225: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 226: 31 f6 xor %esi,%esi 228: 89 f3 mov %esi,%ebx { 22a: 83 ec 1c sub $0x1c,%esp 22d: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 230: eb 2f jmp 261 <gets+0x41> 232: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 238: 8d 45 e7 lea -0x19(%ebp),%eax 23b: 83 ec 04 sub $0x4,%esp 23e: 6a 01 push $0x1 240: 50 push %eax 241: 6a 00 push $0x0 243: e8 32 01 00 00 call 37a <read> if(cc < 1) 248: 83 c4 10 add $0x10,%esp 24b: 85 c0 test %eax,%eax 24d: 7e 1c jle 26b <gets+0x4b> break; buf[i++] = c; 24f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 253: 83 c7 01 add $0x1,%edi 256: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 259: 3c 0a cmp $0xa,%al 25b: 74 23 je 280 <gets+0x60> 25d: 3c 0d cmp $0xd,%al 25f: 74 1f je 280 <gets+0x60> for(i=0; i+1 < max; ){ 261: 83 c3 01 add $0x1,%ebx 264: 3b 5d 0c cmp 0xc(%ebp),%ebx 267: 89 fe mov %edi,%esi 269: 7c cd jl 238 <gets+0x18> 26b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 26d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 270: c6 03 00 movb $0x0,(%ebx) } 273: 8d 65 f4 lea -0xc(%ebp),%esp 276: 5b pop %ebx 277: 5e pop %esi 278: 5f pop %edi 279: 5d pop %ebp 27a: c3 ret 27b: 90 nop 27c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 280: 8b 75 08 mov 0x8(%ebp),%esi 283: 8b 45 08 mov 0x8(%ebp),%eax 286: 01 de add %ebx,%esi 288: 89 f3 mov %esi,%ebx buf[i] = '\0'; 28a: c6 03 00 movb $0x0,(%ebx) } 28d: 8d 65 f4 lea -0xc(%ebp),%esp 290: 5b pop %ebx 291: 5e pop %esi 292: 5f pop %edi 293: 5d pop %ebp 294: c3 ret 295: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 299: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000002a0 <stat>: int stat(const char *n, struct stat *st) { 2a0: 55 push %ebp 2a1: 89 e5 mov %esp,%ebp 2a3: 56 push %esi 2a4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 2a5: 83 ec 08 sub $0x8,%esp 2a8: 6a 00 push $0x0 2aa: ff 75 08 pushl 0x8(%ebp) 2ad: e8 f0 00 00 00 call 3a2 <open> if(fd < 0) 2b2: 83 c4 10 add $0x10,%esp 2b5: 85 c0 test %eax,%eax 2b7: 78 27 js 2e0 <stat+0x40> return -1; r = fstat(fd, st); 2b9: 83 ec 08 sub $0x8,%esp 2bc: ff 75 0c pushl 0xc(%ebp) 2bf: 89 c3 mov %eax,%ebx 2c1: 50 push %eax 2c2: e8 f3 00 00 00 call 3ba <fstat> close(fd); 2c7: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 2ca: 89 c6 mov %eax,%esi close(fd); 2cc: e8 b9 00 00 00 call 38a <close> return r; 2d1: 83 c4 10 add $0x10,%esp } 2d4: 8d 65 f8 lea -0x8(%ebp),%esp 2d7: 89 f0 mov %esi,%eax 2d9: 5b pop %ebx 2da: 5e pop %esi 2db: 5d pop %ebp 2dc: c3 ret 2dd: 8d 76 00 lea 0x0(%esi),%esi return -1; 2e0: be ff ff ff ff mov $0xffffffff,%esi 2e5: eb ed jmp 2d4 <stat+0x34> 2e7: 89 f6 mov %esi,%esi 2e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000002f0 <atoi>: int atoi(const char *s) { 2f0: 55 push %ebp 2f1: 89 e5 mov %esp,%ebp 2f3: 53 push %ebx 2f4: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 2f7: 0f be 11 movsbl (%ecx),%edx 2fa: 8d 42 d0 lea -0x30(%edx),%eax 2fd: 3c 09 cmp $0x9,%al n = 0; 2ff: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 304: 77 1f ja 325 <atoi+0x35> 306: 8d 76 00 lea 0x0(%esi),%esi 309: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 310: 8d 04 80 lea (%eax,%eax,4),%eax 313: 83 c1 01 add $0x1,%ecx 316: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 31a: 0f be 11 movsbl (%ecx),%edx 31d: 8d 5a d0 lea -0x30(%edx),%ebx 320: 80 fb 09 cmp $0x9,%bl 323: 76 eb jbe 310 <atoi+0x20> return n; } 325: 5b pop %ebx 326: 5d pop %ebp 327: c3 ret 328: 90 nop 329: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000330 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 330: 55 push %ebp 331: 89 e5 mov %esp,%ebp 333: 56 push %esi 334: 53 push %ebx 335: 8b 5d 10 mov 0x10(%ebp),%ebx 338: 8b 45 08 mov 0x8(%ebp),%eax 33b: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 33e: 85 db test %ebx,%ebx 340: 7e 14 jle 356 <memmove+0x26> 342: 31 d2 xor %edx,%edx 344: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 348: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 34c: 88 0c 10 mov %cl,(%eax,%edx,1) 34f: 83 c2 01 add $0x1,%edx while(n-- > 0) 352: 39 d3 cmp %edx,%ebx 354: 75 f2 jne 348 <memmove+0x18> return vdst; } 356: 5b pop %ebx 357: 5e pop %esi 358: 5d pop %ebp 359: c3 ret 0000035a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 35a: b8 01 00 00 00 mov $0x1,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <exit>: SYSCALL(exit) 362: b8 02 00 00 00 mov $0x2,%eax 367: cd 40 int $0x40 369: c3 ret 0000036a <wait>: SYSCALL(wait) 36a: b8 03 00 00 00 mov $0x3,%eax 36f: cd 40 int $0x40 371: c3 ret 00000372 <pipe>: SYSCALL(pipe) 372: b8 04 00 00 00 mov $0x4,%eax 377: cd 40 int $0x40 379: c3 ret 0000037a <read>: SYSCALL(read) 37a: b8 05 00 00 00 mov $0x5,%eax 37f: cd 40 int $0x40 381: c3 ret 00000382 <write>: SYSCALL(write) 382: b8 10 00 00 00 mov $0x10,%eax 387: cd 40 int $0x40 389: c3 ret 0000038a <close>: SYSCALL(close) 38a: b8 15 00 00 00 mov $0x15,%eax 38f: cd 40 int $0x40 391: c3 ret 00000392 <kill>: SYSCALL(kill) 392: b8 06 00 00 00 mov $0x6,%eax 397: cd 40 int $0x40 399: c3 ret 0000039a <exec>: SYSCALL(exec) 39a: b8 07 00 00 00 mov $0x7,%eax 39f: cd 40 int $0x40 3a1: c3 ret 000003a2 <open>: SYSCALL(open) 3a2: b8 0f 00 00 00 mov $0xf,%eax 3a7: cd 40 int $0x40 3a9: c3 ret 000003aa <mknod>: SYSCALL(mknod) 3aa: b8 11 00 00 00 mov $0x11,%eax 3af: cd 40 int $0x40 3b1: c3 ret 000003b2 <unlink>: SYSCALL(unlink) 3b2: b8 12 00 00 00 mov $0x12,%eax 3b7: cd 40 int $0x40 3b9: c3 ret 000003ba <fstat>: SYSCALL(fstat) 3ba: b8 08 00 00 00 mov $0x8,%eax 3bf: cd 40 int $0x40 3c1: c3 ret 000003c2 <link>: SYSCALL(link) 3c2: b8 13 00 00 00 mov $0x13,%eax 3c7: cd 40 int $0x40 3c9: c3 ret 000003ca <mkdir>: SYSCALL(mkdir) 3ca: b8 14 00 00 00 mov $0x14,%eax 3cf: cd 40 int $0x40 3d1: c3 ret 000003d2 <chdir>: SYSCALL(chdir) 3d2: b8 09 00 00 00 mov $0x9,%eax 3d7: cd 40 int $0x40 3d9: c3 ret 000003da <dup>: SYSCALL(dup) 3da: b8 0a 00 00 00 mov $0xa,%eax 3df: cd 40 int $0x40 3e1: c3 ret 000003e2 <getpid>: SYSCALL(getpid) 3e2: b8 0b 00 00 00 mov $0xb,%eax 3e7: cd 40 int $0x40 3e9: c3 ret 000003ea <sbrk>: SYSCALL(sbrk) 3ea: b8 0c 00 00 00 mov $0xc,%eax 3ef: cd 40 int $0x40 3f1: c3 ret 000003f2 <sleep>: SYSCALL(sleep) 3f2: b8 0d 00 00 00 mov $0xd,%eax 3f7: cd 40 int $0x40 3f9: c3 ret 000003fa <uptime>: SYSCALL(uptime) 3fa: b8 0e 00 00 00 mov $0xe,%eax 3ff: cd 40 int $0x40 401: c3 ret 00000402 <cps>: SYSCALL(cps) 402: b8 16 00 00 00 mov $0x16,%eax 407: cd 40 int $0x40 409: c3 ret 0000040a <chpr>: SYSCALL(chpr) 40a: b8 17 00 00 00 mov $0x17,%eax 40f: cd 40 int $0x40 411: c3 ret 00000412 <waitx>: SYSCALL(waitx) 412: b8 18 00 00 00 mov $0x18,%eax 417: cd 40 int $0x40 419: c3 ret 0000041a <getpinfo>: SYSCALL(getpinfo) 41a: b8 19 00 00 00 mov $0x19,%eax 41f: cd 40 int $0x40 421: c3 ret 422: 66 90 xchg %ax,%ax 424: 66 90 xchg %ax,%ax 426: 66 90 xchg %ax,%ax 428: 66 90 xchg %ax,%ax 42a: 66 90 xchg %ax,%ax 42c: 66 90 xchg %ax,%ax 42e: 66 90 xchg %ax,%ax 00000430 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 430: 55 push %ebp 431: 89 e5 mov %esp,%ebp 433: 57 push %edi 434: 56 push %esi 435: 53 push %ebx 436: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 439: 85 d2 test %edx,%edx { 43b: 89 45 c0 mov %eax,-0x40(%ebp) neg = 1; x = -xx; 43e: 89 d0 mov %edx,%eax if(sgn && xx < 0){ 440: 79 76 jns 4b8 <printint+0x88> 442: f6 45 08 01 testb $0x1,0x8(%ebp) 446: 74 70 je 4b8 <printint+0x88> x = -xx; 448: f7 d8 neg %eax neg = 1; 44a: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) } else { x = xx; } i = 0; 451: 31 f6 xor %esi,%esi 453: 8d 5d d7 lea -0x29(%ebp),%ebx 456: eb 0a jmp 462 <printint+0x32> 458: 90 nop 459: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi do{ buf[i++] = digits[x % base]; 460: 89 fe mov %edi,%esi 462: 31 d2 xor %edx,%edx 464: 8d 7e 01 lea 0x1(%esi),%edi 467: f7 f1 div %ecx 469: 0f b6 92 48 08 00 00 movzbl 0x848(%edx),%edx }while((x /= base) != 0); 470: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 472: 88 14 3b mov %dl,(%ebx,%edi,1) }while((x /= base) != 0); 475: 75 e9 jne 460 <printint+0x30> if(neg) 477: 8b 45 c4 mov -0x3c(%ebp),%eax 47a: 85 c0 test %eax,%eax 47c: 74 08 je 486 <printint+0x56> buf[i++] = '-'; 47e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 483: 8d 7e 02 lea 0x2(%esi),%edi 486: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi 48a: 8b 7d c0 mov -0x40(%ebp),%edi 48d: 8d 76 00 lea 0x0(%esi),%esi 490: 0f b6 06 movzbl (%esi),%eax write(fd, &c, 1); 493: 83 ec 04 sub $0x4,%esp 496: 83 ee 01 sub $0x1,%esi 499: 6a 01 push $0x1 49b: 53 push %ebx 49c: 57 push %edi 49d: 88 45 d7 mov %al,-0x29(%ebp) 4a0: e8 dd fe ff ff call 382 <write> while(--i >= 0) 4a5: 83 c4 10 add $0x10,%esp 4a8: 39 de cmp %ebx,%esi 4aa: 75 e4 jne 490 <printint+0x60> putc(fd, buf[i]); } 4ac: 8d 65 f4 lea -0xc(%ebp),%esp 4af: 5b pop %ebx 4b0: 5e pop %esi 4b1: 5f pop %edi 4b2: 5d pop %ebp 4b3: c3 ret 4b4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 4b8: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 4bf: eb 90 jmp 451 <printint+0x21> 4c1: eb 0d jmp 4d0 <printf> 4c3: 90 nop 4c4: 90 nop 4c5: 90 nop 4c6: 90 nop 4c7: 90 nop 4c8: 90 nop 4c9: 90 nop 4ca: 90 nop 4cb: 90 nop 4cc: 90 nop 4cd: 90 nop 4ce: 90 nop 4cf: 90 nop 000004d0 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 4d0: 55 push %ebp 4d1: 89 e5 mov %esp,%ebp 4d3: 57 push %edi 4d4: 56 push %esi 4d5: 53 push %ebx 4d6: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4d9: 8b 75 0c mov 0xc(%ebp),%esi 4dc: 0f b6 1e movzbl (%esi),%ebx 4df: 84 db test %bl,%bl 4e1: 0f 84 b3 00 00 00 je 59a <printf+0xca> ap = (uint*)(void*)&fmt + 1; 4e7: 8d 45 10 lea 0x10(%ebp),%eax 4ea: 83 c6 01 add $0x1,%esi state = 0; 4ed: 31 ff xor %edi,%edi ap = (uint*)(void*)&fmt + 1; 4ef: 89 45 d4 mov %eax,-0x2c(%ebp) 4f2: eb 2f jmp 523 <printf+0x53> 4f4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 4f8: 83 f8 25 cmp $0x25,%eax 4fb: 0f 84 a7 00 00 00 je 5a8 <printf+0xd8> write(fd, &c, 1); 501: 8d 45 e2 lea -0x1e(%ebp),%eax 504: 83 ec 04 sub $0x4,%esp 507: 88 5d e2 mov %bl,-0x1e(%ebp) 50a: 6a 01 push $0x1 50c: 50 push %eax 50d: ff 75 08 pushl 0x8(%ebp) 510: e8 6d fe ff ff call 382 <write> 515: 83 c4 10 add $0x10,%esp 518: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 51b: 0f b6 5e ff movzbl -0x1(%esi),%ebx 51f: 84 db test %bl,%bl 521: 74 77 je 59a <printf+0xca> if(state == 0){ 523: 85 ff test %edi,%edi c = fmt[i] & 0xff; 525: 0f be cb movsbl %bl,%ecx 528: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 52b: 74 cb je 4f8 <printf+0x28> state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 52d: 83 ff 25 cmp $0x25,%edi 530: 75 e6 jne 518 <printf+0x48> if(c == 'd'){ 532: 83 f8 64 cmp $0x64,%eax 535: 0f 84 05 01 00 00 je 640 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 53b: 81 e1 f7 00 00 00 and $0xf7,%ecx 541: 83 f9 70 cmp $0x70,%ecx 544: 74 72 je 5b8 <printf+0xe8> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 546: 83 f8 73 cmp $0x73,%eax 549: 0f 84 99 00 00 00 je 5e8 <printf+0x118> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 54f: 83 f8 63 cmp $0x63,%eax 552: 0f 84 08 01 00 00 je 660 <printf+0x190> putc(fd, *ap); ap++; } else if(c == '%'){ 558: 83 f8 25 cmp $0x25,%eax 55b: 0f 84 ef 00 00 00 je 650 <printf+0x180> write(fd, &c, 1); 561: 8d 45 e7 lea -0x19(%ebp),%eax 564: 83 ec 04 sub $0x4,%esp 567: c6 45 e7 25 movb $0x25,-0x19(%ebp) 56b: 6a 01 push $0x1 56d: 50 push %eax 56e: ff 75 08 pushl 0x8(%ebp) 571: e8 0c fe ff ff call 382 <write> 576: 83 c4 0c add $0xc,%esp 579: 8d 45 e6 lea -0x1a(%ebp),%eax 57c: 88 5d e6 mov %bl,-0x1a(%ebp) 57f: 6a 01 push $0x1 581: 50 push %eax 582: ff 75 08 pushl 0x8(%ebp) 585: 83 c6 01 add $0x1,%esi } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 588: 31 ff xor %edi,%edi write(fd, &c, 1); 58a: e8 f3 fd ff ff call 382 <write> for(i = 0; fmt[i]; i++){ 58f: 0f b6 5e ff movzbl -0x1(%esi),%ebx write(fd, &c, 1); 593: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 596: 84 db test %bl,%bl 598: 75 89 jne 523 <printf+0x53> } } } 59a: 8d 65 f4 lea -0xc(%ebp),%esp 59d: 5b pop %ebx 59e: 5e pop %esi 59f: 5f pop %edi 5a0: 5d pop %ebp 5a1: c3 ret 5a2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi state = '%'; 5a8: bf 25 00 00 00 mov $0x25,%edi 5ad: e9 66 ff ff ff jmp 518 <printf+0x48> 5b2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); 5b8: 83 ec 0c sub $0xc,%esp 5bb: b9 10 00 00 00 mov $0x10,%ecx 5c0: 6a 00 push $0x0 5c2: 8b 7d d4 mov -0x2c(%ebp),%edi 5c5: 8b 45 08 mov 0x8(%ebp),%eax 5c8: 8b 17 mov (%edi),%edx 5ca: e8 61 fe ff ff call 430 <printint> ap++; 5cf: 89 f8 mov %edi,%eax 5d1: 83 c4 10 add $0x10,%esp state = 0; 5d4: 31 ff xor %edi,%edi ap++; 5d6: 83 c0 04 add $0x4,%eax 5d9: 89 45 d4 mov %eax,-0x2c(%ebp) 5dc: e9 37 ff ff ff jmp 518 <printf+0x48> 5e1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 5e8: 8b 45 d4 mov -0x2c(%ebp),%eax 5eb: 8b 08 mov (%eax),%ecx ap++; 5ed: 83 c0 04 add $0x4,%eax 5f0: 89 45 d4 mov %eax,-0x2c(%ebp) if(s == 0) 5f3: 85 c9 test %ecx,%ecx 5f5: 0f 84 8e 00 00 00 je 689 <printf+0x1b9> while(*s != 0){ 5fb: 0f b6 01 movzbl (%ecx),%eax state = 0; 5fe: 31 ff xor %edi,%edi s = (char*)*ap; 600: 89 cb mov %ecx,%ebx while(*s != 0){ 602: 84 c0 test %al,%al 604: 0f 84 0e ff ff ff je 518 <printf+0x48> 60a: 89 75 d0 mov %esi,-0x30(%ebp) 60d: 89 de mov %ebx,%esi 60f: 8b 5d 08 mov 0x8(%ebp),%ebx 612: 8d 7d e3 lea -0x1d(%ebp),%edi 615: 8d 76 00 lea 0x0(%esi),%esi write(fd, &c, 1); 618: 83 ec 04 sub $0x4,%esp s++; 61b: 83 c6 01 add $0x1,%esi 61e: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); 621: 6a 01 push $0x1 623: 57 push %edi 624: 53 push %ebx 625: e8 58 fd ff ff call 382 <write> while(*s != 0){ 62a: 0f b6 06 movzbl (%esi),%eax 62d: 83 c4 10 add $0x10,%esp 630: 84 c0 test %al,%al 632: 75 e4 jne 618 <printf+0x148> 634: 8b 75 d0 mov -0x30(%ebp),%esi state = 0; 637: 31 ff xor %edi,%edi 639: e9 da fe ff ff jmp 518 <printf+0x48> 63e: 66 90 xchg %ax,%ax printint(fd, *ap, 10, 1); 640: 83 ec 0c sub $0xc,%esp 643: b9 0a 00 00 00 mov $0xa,%ecx 648: 6a 01 push $0x1 64a: e9 73 ff ff ff jmp 5c2 <printf+0xf2> 64f: 90 nop write(fd, &c, 1); 650: 83 ec 04 sub $0x4,%esp 653: 88 5d e5 mov %bl,-0x1b(%ebp) 656: 8d 45 e5 lea -0x1b(%ebp),%eax 659: 6a 01 push $0x1 65b: e9 21 ff ff ff jmp 581 <printf+0xb1> putc(fd, *ap); 660: 8b 7d d4 mov -0x2c(%ebp),%edi write(fd, &c, 1); 663: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 666: 8b 07 mov (%edi),%eax write(fd, &c, 1); 668: 6a 01 push $0x1 ap++; 66a: 83 c7 04 add $0x4,%edi putc(fd, *ap); 66d: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); 670: 8d 45 e4 lea -0x1c(%ebp),%eax 673: 50 push %eax 674: ff 75 08 pushl 0x8(%ebp) 677: e8 06 fd ff ff call 382 <write> ap++; 67c: 89 7d d4 mov %edi,-0x2c(%ebp) 67f: 83 c4 10 add $0x10,%esp state = 0; 682: 31 ff xor %edi,%edi 684: e9 8f fe ff ff jmp 518 <printf+0x48> s = "(null)"; 689: bb 40 08 00 00 mov $0x840,%ebx while(*s != 0){ 68e: b8 28 00 00 00 mov $0x28,%eax 693: e9 72 ff ff ff jmp 60a <printf+0x13a> 698: 66 90 xchg %ax,%ax 69a: 66 90 xchg %ax,%ax 69c: 66 90 xchg %ax,%ax 69e: 66 90 xchg %ax,%ax 000006a0 <free>: static Header base; static Header *freep; void free(void *ap) { 6a0: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 6a1: a1 f8 0a 00 00 mov 0xaf8,%eax { 6a6: 89 e5 mov %esp,%ebp 6a8: 57 push %edi 6a9: 56 push %esi 6aa: 53 push %ebx 6ab: 8b 5d 08 mov 0x8(%ebp),%ebx bp = (Header*)ap - 1; 6ae: 8d 4b f8 lea -0x8(%ebx),%ecx 6b1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 6b8: 39 c8 cmp %ecx,%eax 6ba: 8b 10 mov (%eax),%edx 6bc: 73 32 jae 6f0 <free+0x50> 6be: 39 d1 cmp %edx,%ecx 6c0: 72 04 jb 6c6 <free+0x26> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 6c2: 39 d0 cmp %edx,%eax 6c4: 72 32 jb 6f8 <free+0x58> break; if(bp + bp->s.size == p->s.ptr){ 6c6: 8b 73 fc mov -0x4(%ebx),%esi 6c9: 8d 3c f1 lea (%ecx,%esi,8),%edi 6cc: 39 fa cmp %edi,%edx 6ce: 74 30 je 700 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 6d0: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 6d3: 8b 50 04 mov 0x4(%eax),%edx 6d6: 8d 34 d0 lea (%eax,%edx,8),%esi 6d9: 39 f1 cmp %esi,%ecx 6db: 74 3a je 717 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 6dd: 89 08 mov %ecx,(%eax) freep = p; 6df: a3 f8 0a 00 00 mov %eax,0xaf8 } 6e4: 5b pop %ebx 6e5: 5e pop %esi 6e6: 5f pop %edi 6e7: 5d pop %ebp 6e8: c3 ret 6e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 6f0: 39 d0 cmp %edx,%eax 6f2: 72 04 jb 6f8 <free+0x58> 6f4: 39 d1 cmp %edx,%ecx 6f6: 72 ce jb 6c6 <free+0x26> { 6f8: 89 d0 mov %edx,%eax 6fa: eb bc jmp 6b8 <free+0x18> 6fc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 700: 03 72 04 add 0x4(%edx),%esi 703: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 706: 8b 10 mov (%eax),%edx 708: 8b 12 mov (%edx),%edx 70a: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 70d: 8b 50 04 mov 0x4(%eax),%edx 710: 8d 34 d0 lea (%eax,%edx,8),%esi 713: 39 f1 cmp %esi,%ecx 715: 75 c6 jne 6dd <free+0x3d> p->s.size += bp->s.size; 717: 03 53 fc add -0x4(%ebx),%edx freep = p; 71a: a3 f8 0a 00 00 mov %eax,0xaf8 p->s.size += bp->s.size; 71f: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 722: 8b 53 f8 mov -0x8(%ebx),%edx 725: 89 10 mov %edx,(%eax) } 727: 5b pop %ebx 728: 5e pop %esi 729: 5f pop %edi 72a: 5d pop %ebp 72b: c3 ret 72c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000730 <malloc>: return freep; } void* malloc(uint nbytes) { 730: 55 push %ebp 731: 89 e5 mov %esp,%ebp 733: 57 push %edi 734: 56 push %esi 735: 53 push %ebx 736: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 739: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 73c: 8b 15 f8 0a 00 00 mov 0xaf8,%edx nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 742: 8d 78 07 lea 0x7(%eax),%edi 745: c1 ef 03 shr $0x3,%edi 748: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 74b: 85 d2 test %edx,%edx 74d: 0f 84 9d 00 00 00 je 7f0 <malloc+0xc0> 753: 8b 02 mov (%edx),%eax 755: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 758: 39 cf cmp %ecx,%edi 75a: 76 6c jbe 7c8 <malloc+0x98> 75c: 81 ff 00 10 00 00 cmp $0x1000,%edi 762: bb 00 10 00 00 mov $0x1000,%ebx 767: 0f 43 df cmovae %edi,%ebx p = sbrk(nu * sizeof(Header)); 76a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi 771: eb 0e jmp 781 <malloc+0x51> 773: 90 nop 774: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 778: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 77a: 8b 48 04 mov 0x4(%eax),%ecx 77d: 39 f9 cmp %edi,%ecx 77f: 73 47 jae 7c8 <malloc+0x98> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 781: 39 05 f8 0a 00 00 cmp %eax,0xaf8 787: 89 c2 mov %eax,%edx 789: 75 ed jne 778 <malloc+0x48> p = sbrk(nu * sizeof(Header)); 78b: 83 ec 0c sub $0xc,%esp 78e: 56 push %esi 78f: e8 56 fc ff ff call 3ea <sbrk> if(p == (char*)-1) 794: 83 c4 10 add $0x10,%esp 797: 83 f8 ff cmp $0xffffffff,%eax 79a: 74 1c je 7b8 <malloc+0x88> hp->s.size = nu; 79c: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 79f: 83 ec 0c sub $0xc,%esp 7a2: 83 c0 08 add $0x8,%eax 7a5: 50 push %eax 7a6: e8 f5 fe ff ff call 6a0 <free> return freep; 7ab: 8b 15 f8 0a 00 00 mov 0xaf8,%edx if((p = morecore(nunits)) == 0) 7b1: 83 c4 10 add $0x10,%esp 7b4: 85 d2 test %edx,%edx 7b6: 75 c0 jne 778 <malloc+0x48> return 0; } } 7b8: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 7bb: 31 c0 xor %eax,%eax } 7bd: 5b pop %ebx 7be: 5e pop %esi 7bf: 5f pop %edi 7c0: 5d pop %ebp 7c1: c3 ret 7c2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if(p->s.size == nunits) 7c8: 39 cf cmp %ecx,%edi 7ca: 74 54 je 820 <malloc+0xf0> p->s.size -= nunits; 7cc: 29 f9 sub %edi,%ecx 7ce: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 7d1: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 7d4: 89 78 04 mov %edi,0x4(%eax) freep = prevp; 7d7: 89 15 f8 0a 00 00 mov %edx,0xaf8 } 7dd: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 7e0: 83 c0 08 add $0x8,%eax } 7e3: 5b pop %ebx 7e4: 5e pop %esi 7e5: 5f pop %edi 7e6: 5d pop %ebp 7e7: c3 ret 7e8: 90 nop 7e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; 7f0: c7 05 f8 0a 00 00 fc movl $0xafc,0xaf8 7f7: 0a 00 00 7fa: c7 05 fc 0a 00 00 fc movl $0xafc,0xafc 801: 0a 00 00 base.s.size = 0; 804: b8 fc 0a 00 00 mov $0xafc,%eax 809: c7 05 00 0b 00 00 00 movl $0x0,0xb00 810: 00 00 00 813: e9 44 ff ff ff jmp 75c <malloc+0x2c> 818: 90 nop 819: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi prevp->s.ptr = p->s.ptr; 820: 8b 08 mov (%eax),%ecx 822: 89 0a mov %ecx,(%edx) 824: eb b1 jmp 7d7 <malloc+0xa7>
; A110660: Promic numbers repeated. ; 0,0,2,2,6,6,12,12,20,20,30,30,42,42,56,56,72,72,90,90,110,110,132,132,156,156,182,182,210,210,240,240,272,272,306,306,342,342,380,380,420,420,462,462,506,506,552,552,600,600,650,650,702,702,756,756,812,812,870,870,930,930,992,992,1056,1056,1122,1122,1190,1190,1260,1260,1332,1332,1406,1406,1482,1482,1560,1560,1640,1640,1722,1722,1806,1806,1892,1892,1980,1980,2070,2070,2162,2162,2256,2256,2352,2352,2450,2450,2550,2550,2652,2652,2756,2756,2862,2862,2970,2970,3080,3080,3192,3192,3306,3306,3422,3422,3540,3540,3660,3660,3782,3782,3906,3906,4032,4032,4160,4160,4290,4290,4422,4422,4556,4556,4692,4692,4830,4830,4970,4970,5112,5112,5256,5256,5402,5402,5550,5550,5700,5700,5852,5852,6006,6006,6162,6162,6320,6320,6480,6480,6642,6642,6806,6806,6972,6972,7140,7140,7310,7310,7482,7482,7656,7656,7832,7832,8010,8010,8190,8190,8372,8372,8556,8556,8742,8742,8930,8930,9120,9120,9312,9312,9506,9506,9702,9702,9900,9900,10100,10100,10302,10302,10506,10506,10712,10712,10920,10920,11130,11130,11342,11342,11556,11556,11772,11772,11990,11990,12210,12210,12432,12432,12656,12656,12882,12882,13110,13110,13340,13340,13572,13572,13806,13806,14042,14042,14280,14280,14520,14520,14762,14762,15006,15006,15252,15252,15500,15500 div $0,2 mov $1,$0 pow $0,2 add $1,$0