text
stringlengths
1
1.05M
; A045995: Rows of Fibonacci-Pascal triangle. ; 1,1,1,1,1,1,1,2,2,1,1,3,8,3,1,1,5,55,55,5,1,1,8,610,6765,610,8,1,1,13,10946,9227465,9227465,10946,13,1,1,21,317811,225851433717,190392490709135,225851433717,317811,21,1,1,34,14930352,160500643816367088,96151855463018422468774568,96151855463018422468774568,160500643816367088,14930352,34,1,1,55,1134903170,5358359254990966640871840 seq $0,7318 ; Pascal's triangle read by rows: C(n,k) = binomial(n,k) = n!/(k!*(n-k)!), 0 <= k <= n. seq $0,45 ; Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
[org 0x0100] jmp start trap_bool: DW 0 flag: db 0 oldISR: dd 0 strStk:db 'Stack' strFlg:db 'Flags' stkInd:db '+0+2+4+6' myName: db 'Hafiz Muhammad Hamza',' L12-4013 ','Copyrights 2013 HaZa','All Rights Reserved ' cmd: db 'CMD > ' strline: db '________________________________________________________________________________' m2DS1: db '0 1 2 3 4 5 6 7 8 9 A B C D E F' m1DS2: db 'DS:0000 DS:0008 DS:0010 DS:0018 DS:0020 DS:0028 DS:0030 DS:0038 DS:0040 DS:0048 ' m2DS2: db 'DS:0000 DS:0010 DS:0020 DS:0030 DS:0040 ' regNames: db 'CS IP BP SP AX BX CX DX SI DI DS ES SS FS ' flagBits:db'OF DF IF SF ZF AF PF CF ' clearScreen: mov ax , 0xB800 mov es , ax mov di , 0 mov ax , 0x0720 mov cx , 2000 rep stosw ret printNum: ;[BP+8]=y-coordinate [BP+6]=x-coordinate [BP+4]=number push bp mov bp , sp push ax push bx push cx push dx push di push es mov di , 80 mov ax , [bp+8] mul di mov di , ax add di , [bp+6] shl di , 1 add di , 8 mov ax , 0xB800 mov es , ax mov ax , [bp+4] mov bx , 16 mov cx , 4 nextDigit: mov dx , 0 div bx add dl , 0x30 cmp dl , 0x39 jbe noAlphabet add dl , 7 noAlphabet: mov dh , 0x0A mov [es:di] , dx sub di , 2 loop nextDigit pop es pop di pop dx pop cx pop bx pop ax pop bp ret 6 printStr: push bp mov bp , sp push ax push bx push cx push dx push si push di push es mov ax , 0xB800 mov es , ax mov di , 80 mov ax , [bp+10] mul di mov di , ax add di , [bp+8] shl di , 1 mov si , [bp+6] mov cx , [bp+4] mov ah , 0x07 nextChar: mov al , [si] mov [es:di] , ax add di , 2 inc si loop nextChar pop es pop di pop si pop dx pop cx pop bx pop ax pop bp ret 8 keyboardISR: push ax in al , 0x60 cmp al , 0x43 ;F9 jnz skip add byte [cs:flag] , al mov word [cs:trap_bool],0 skip: cmp al , 0x44 jnz KBquit add byte [cs:flag] , al mov word [cs:trap_bool],1 KBquit: pop ax jmp far [cs:oldISR] ISR3: mov word [cs:trap_bool],0 iret trapISR: push bp mov bp , sp push sp push ax push bx push cx push dx push si push di push ds push es push ss push fs sti ;waiting for keyboard interrupt push cs pop ds mov byte [flag] , 0 call clearScreen ;****************** PRINTING BOXES AND JUNK********************** push 0xB800 pop es mov ax , 0x077C mov di , 892 mov cx , 11 straightLine: stosw add di , 158 loop straightLine mov di , 2838 mov cx , 6 straightLine2: stosw add di , 158 loop straightLine2 push 4 push 0 push strline push 80 call printStr push 6 push 0 push strline push 46 call printStr push 16 push 0 push strline push 80 call printStr push 23 push 0 push strline push 80 call printStr mov di , 3000 mov cx , 20 mov si , myName mov ah , 0x8B prtName: lodsb stosw loop prtName mov di , 3160 mov cx , 20 mov ah , 0x0D prtRoll: lodsb stosw loop prtRoll mov di , 3480 mov cx , 20 mov ah , 0x70 prtCopyrights: lodsb stosw loop prtCopyrights mov di , 3640 mov cx , 20 mov ah , 0x70 prtReserved: lodsb stosw loop prtReserved mov di , 800 mov cx , 6 mov ah , 0x07 prtCMD: lodsb stosw loop prtCMD ;******************* PRINTING FLAGS NAMES *************** push 0 push 57 push strFlg push 5 call printStr ;to print "Flags" mov ax , 2 ;row mov bx , 57 ;column mov cx , 9 mov si , 3 ;lenght mov dx , flagBits printFLnames: push ax push bx push dx push si call printStr add dx , 3 add bx , 3 loop printFLnames ;******************* PRINTING FLAGS VALUES *************** push 0 push 63 mov dx , [bp+6] push dx call printNum ;prints whole of the flag register push 0xB800 pop es mov di , 596 mov dx , [bp+6] ;DX=Flag register shl dx , 4 mov cx , 3 mov ah , 0x0A Fl1: mov al , 0x30 shl dx , 1 jnc Fl1proceed mov al , 0x31 Fl1proceed: stosw add di , 4 loop Fl1 shl dx , 1 mov cx , 2 Fl3: mov al , 0x30 shl dx , 1 jnc Fl3proceed mov al , 0x31 Fl3proceed: stosw add di , 4 loop Fl3 mov cx , 3 Fl2: mov al , 0x30 shl dx , 2 jc Fl2proceed mov al , 0x31 Fl2proceed: stosw add di , 4 loop Fl2 ;******************* PRINTING REGISTERS NAMES *************** mov ax , 0 ;row mov bx , 0 ;column mov cx , 4 mov si , 40 ;lenght mov dx , regNames printNames: push ax push bx push dx push si call printStr add dx , 40 add ax , 1 loop printNames ;******************* PRINTING REGISTER VALUES *************** mov di , 0 mov si , 4 mov cx , 14 mov ax , 0 ;row mov bx , 2 ;column printValues: push ax push bx mov dx , [bp+si] push dx call printNum sub si , 2 add bx , 10 inc di cmp di , 4 jnz cntPrt mov di , 0 inc ax mov bx , 2 cntPrt: loop printValues ;******************** PRINTING STACK STRINGS ************** push 0 push 42 push strStk push 5 call printStr ;to print "Stack" mov ax , 0 ;row mov bx , 48 ;column mov cx , 4 mov si , 2 ;lenght mov dx , stkInd prtStk: push ax push bx push dx push si call printStr add dx , 2 inc ax loop prtStk ;******************* PRINTING STACK VALUES *************** mov ax , [bp-20] ;AX=SS mov es , ax mov di , [bp-2] mov cx , 4 mov ax , 0 ;row mov bx , 50 ;column printStackValues: push ax push bx mov dx , [es:di] push dx call printNum add di , 2 inc ax loop printStackValues ;******************* PRINTING m2DS NAMES *************** push 17 push 11 push m2DS1 push 45 call printStr push 0xB800 pop es mov word [es:2720] , 0x7032 mov ax , 18 ;row mov bx , 0 ;column mov cx , 5 mov si , 10 ;lenght mov dx , m2DS2 printm2DS2N: push ax push bx push dx push si call printStr add dx , 10 inc ax loop printm2DS2N ;******************* PRINTING m2DS VALUES *************** push cs pop ds mov si , 0 mov di , 0 mov cx , 40 mov ax , 18 ;row mov bx , 9 ;column printm2DSValues: push ax push bx mov dx , [ds:si] xchg dl , dh ;little endian order push dx call printNum add si , 2 add bx , 6 inc di cmp di , 8 jnz cntPrtm2DS mov di , 0 inc ax mov bx , 9 cntPrtm2DS: loop printm2DSValues ;******************* PRINTING m1DS NAMES *************** push 5 push 59 push m2DS1 push 21 call printStr push 0xB800 pop es mov word [es:896] , 0x7031 mov ax , 6 ;row mov bx , 48 ;column mov cx , 10 mov si , 9 ;lenght mov dx , m1DS2 printm1DS2N: push ax push bx push dx push si call printStr add dx , 9 inc ax loop printm1DS2N ;******************* PRINTING m1DS VALUES *************** push cs pop ds mov si , 0 mov di , 0 mov cx , 40 mov ax , 6 ;row mov bx , 57 ;column printm1DSValues: push ax push bx mov dx , [ds:si] xchg dl , dh ;little endian order push dx call printNum add si , 2 add bx , 6 inc di cmp di , 4 jnz cntPrtm1DS mov di , 0 inc ax mov bx , 57 cntPrtm1DS: loop printm1DSValues CMP WORD [CS:trap_bool],1 JE SKIP_WAIT keyWait: cmp byte[CS:flag] , 0 je keyWait SKIP_WAIT: pop fs pop ss pop es pop ds pop di pop si pop dx pop cx pop bx pop ax pop sp pop bp iret start: xor ax , ax mov es , ax ;point ES to IVT table mov ax , [es:9*4] mov [oldISR] , ax mov ax , [es:9*4+2] mov [oldISR+2] , ax mov word [es:1*4] , trapISR mov [es:1*4+2] , cs cli mov word [es:9*4] , keyboardISR mov [es:9*4+2] , cs mov word [es:3*4] , ISR3 mov [es:3*4+2] , cs sti mov dx,start add dx,15 mov cl,4 shr dx , cl mov ax,0x3100 int 21h
;RaTol Symbolinen konekieli: Harjoitus 2, tehtävä 3 ;Tero Kukka IY96A ;Tiedosto: summaa1.asm ;Luotu 25.2.1998 ;Aliohjelma _Summaa1 ;Yhteenlaskettavat luvut ovat rekistereissä BL ja DH. ;Aliohjelmien esittely: public _Summaa1 .model small ;muistimalli .stack 00h ;pinon koko .data ;muuttujalohko .code ;ohjelmakoodi alkaa _Summaa1 proc ;unsigned char _Summaa1(); mov ah, 0 ;varmistetaan summan (word) oikea tulos mov al, bl add al, dh ret ;return AX; _Summaa1 endp end
; A022379: Fibonacci sequence beginning 3, 9. ; 3,9,12,21,33,54,87,141,228,369,597,966,1563,2529,4092,6621,10713,17334,28047,45381,73428,118809,192237,311046,503283,814329,1317612,2131941,3449553,5581494,9031047,14612541,23643588,38256129,61899717,100155846,162055563,262211409 mov $1,3 mov $3,6 lpb $0,1 sub $0,1 mov $2,$1 add $1,$3 mov $3,$2 lpe
;=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-; ; ; Name: PixelAddr16 ; ; Function: Determine buffer address of pixel in 160x200 16-color mode ; ; Caller: al = y-coordinate (0-99) ; bl = x-coordinate (0-159) ; ; Returns: AH = bit mask ; BX = byte offset in buffer ; CL = number of bits to shift left ; ;=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-; ; ; From: ; Programmers's Guide To PC & PS/2: Video Systems ; by Richard Wilton ; ;=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-; ; ; Adapted to nasm and, PCjr's 160x200 16-color: riq ; ;=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-; ; 2 pixels per byte ; 160 / 2 = 80 bytes per horizontal line. (80 = 64 + 16) ; offset = y * 80 + x / 2 ; cl = (x & 1) ? 0 : 1 PixelAddr08: mov cl,bl ;save for later sub ah,ah sub bh,bh xchg ah,al ; AX := 256*y shr ax,1 ; AX := 128*Y add bx,ax ; BX := 128*y + x shr ax,1 ; AX := 64*Y shr ax,1 ; AX := 32*Y add bx,ax ; BX := 128*Y + 32*Y + X == 160*Y + X shr bx,1 ; BX : = 80*y + x /2 mov ah,0b0000_1111 ;mask and cl,1 ;x & 1 xor cl,1 ;invert bit shl cl,1 ; shl cl,1 ;cl = (x&1) * 4 ; shl ah,cl ;mask = 0xf0 if x&1, else 0x0f cmp bx,4096 ja .error ret .error: int 3 jmp .error
/* * Copyright (c) 2010, Michael Lehn * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3) Neither the name of the FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * 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. */ #ifndef FLENS_SCALARTYPES_SCALAR_TCC #define FLENS_SCALARTYPES_SCALAR_TCC 1 #include <flens/scalartypes/scalar.h> namespace flens { template <typename I> Scalar<I>::~Scalar() { } template <typename I> const typename Scalar<I>::Impl & Scalar<I>::impl() const { return static_cast<const Impl &>(*this); } template <typename I> typename Scalar<I>::Impl & Scalar<I>::impl() { return static_cast<Impl &>(*this); } } // namespace flens #endif // FLENS_SCALARTYPES_SCALAR_TCC
#include <iostream> #include <vector> #include "openglu.hpp" #include <GLFW/glfw3.h> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/string_cast.hpp> #include "imgui/imgui_impl_glfw.h" #include "imgui/imgui_impl_opengl3.h" bool firstMouse = true; bool escaped = false; double lastX = 0.0f; double lastY = 0.0f; oglu::Camera camera(45.0f, 16.f / 9.f, 0.01f, 100.0f); void framebuffer_size_callback(GLFWwindow* window, int width, int height) { oglu::SetViewport(0, 0, width, height); camera.aspectRatio = ((float)width / (float)height); } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (escaped) return; if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = (float)xpos - (float)lastX; float yoffset = (float)lastY - (float)ypos; lastX = xpos; lastY = ypos; float sensitivity = 0.1f; xoffset *= sensitivity; yoffset *= sensitivity; camera.Pan(-xoffset); camera.Tilt(yoffset); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) { escaped = !escaped; firstMouse = true; glfwSetInputMode(window, GLFW_CURSOR, escaped ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED); } } void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.Forward(0.1f); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.Sideways(-0.1f); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.Forward(-0.1f); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.Sideways(0.1f); if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) camera.Move(0.0f, 0.1f, 0.0f); if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) camera.Move(0.0f, -0.1f, 0.0f); } int main(int argc, char** argv) { // Setup GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); const GLFWvidmode* screen = glfwGetVideoMode(glfwGetPrimaryMonitor()); int windowHeight = screen->height / 5 * 4; int windowWidth = (int)(16.f / 9.f * windowHeight); // Create Window GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, "First Person Movement Test", NULL, NULL); if (window == nullptr) { std::cerr << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetKeyCallback(window, key_callback); // glad stuff oglu::LoadGLLoader((GLADloadproc)glfwGetProcAddress); oglu::SetViewport(0, 0, windowWidth, windowHeight); IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init(); ImGui::StyleColorsDark(); // Create vertices for square float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f }; oglu::VertexAttribute topology[] = { { 0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0 }, { 1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)) }, { 2, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(5 * sizeof(float)) } }; // Make a square oglu::VertexArray cubeDefault = oglu::MakeVertexArray(vertices, sizeof(vertices), nullptr, 0, topology, sizeof(topology)); oglu::SharedMaterial cubeMaterial(new oglu::Material); //cubeMaterial->AddProperty("ambient", oglu::Color::White); cubeMaterial->AddProperty("shininess", 32.f); cubeMaterial->AddProperty("diffuse", oglu::MakeTexture("assets/tiles_diffuse.jpg")); cubeMaterial->AddProperty("specular", oglu::MakeTexture("assets/tiles_bump.jpg")); oglu::Object cubes[10] = { oglu::Object(cubeDefault), oglu::Object(cubeDefault), oglu::Object(cubeDefault), oglu::Object(cubeDefault), oglu::Object(cubeDefault), oglu::Object(cubeDefault), oglu::Object(cubeDefault), oglu::Object(cubeDefault), oglu::Object(cubeDefault), oglu::Object(cubeDefault) }; cubes[0].SetPosition(0.0f, 0.0f, 0.0f); cubes[1].SetPosition(2.0f, 5.0f, -15.0f); cubes[2].SetPosition(-1.5f, -2.2f, -2.5f); cubes[3].SetPosition(-3.8f, -2.0f, -12.3f); cubes[4].SetPosition(2.4f, -0.4f, -3.5f); cubes[5].SetPosition(-1.7f, 3.0f, -7.5f); cubes[6].SetPosition(1.3f, -2.0f, -2.5f); cubes[7].SetPosition(1.5f, 2.0f, -2.5f); cubes[8].SetPosition(1.5f, 0.2f, -1.5f); cubes[9].SetPosition(-1.3f, 1.0f, -1.5f); cubes[0].SetRotation(45.0f, 30.0f, 1.0f); cubes[1].SetRotation(270.0f, 90.0f, 70.0f); cubes[2].SetRotation(-80.0f, -190.0f, 270.0f); cubes[3].SetRotation(100.0f, -200.0f, -120.3f); cubes[4].SetRotation(240.0f, -40.0f, -30.5f); cubes[5].SetRotation(-170.0f, 300.0f, -75.0f); cubes[6].SetRotation(130.0f, -20.0f, -250.0f); cubes[7].SetRotation(150.0f, 200.0f, -25.0f); cubes[8].SetRotation(150.0f, 20.0f, -150.0f); cubes[9].SetRotation(-130.0f, 10.0f, -150.0f); for (oglu::Object& cube : cubes) cube.material = cubeMaterial; oglu::Object lightSource(cubeDefault); lightSource.SetScale(glm::vec3(0.1f)); oglu::PointLight pointLight; pointLight.LinkPositionToTransformable(lightSource); oglu::SpotLight flashlight; flashlight.linear = 0.09f; flashlight.quadratic = 0.032f; // Create a shader oglu::Shader shader, lightSourceShader; try { shader = oglu::MakeShader("shaders/vertexShader.vert", "shaders/fragmentShader.frag"); lightSourceShader = oglu::MakeShader("shaders/lightSourceShader.vert", "shaders/lightSourceShader.frag"); } catch (const std::runtime_error& e) { std::cerr << e.what() << std::endl; return -1; } oglu::AmbientLight ambient; ambient.intensity = 0.1f; camera.Move(0.0f, 0.0f, 5.0f); // Window loop oglu::Enable(GL_DEPTH_TEST); float t = 0.0f; glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); oglu::Color bgColor = oglu::Color::Black; lightSource.SetPosition(1.0f, 1.0f, -1.0f); while (!glfwWindowShouldClose(window)) { processInput(window); oglu::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, bgColor); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); flashlight.SetPosition(camera.GetPosition()); flashlight.direction = camera.GetFront(); shader->Use(); shader->SetUniform("pointLight.ambient", "pointLight.ambientStrength", ambient); shader->SetUniform3fv("pointLight.position", 1, glm::value_ptr(lightSource.GetPosition())); shader->SetUniform("pointLight.diffuse", pointLight.diffusionColor, true); shader->SetUniform("pointLight.specular", pointLight.specularColor, true); shader->SetUniform("pointLight.constant", pointLight.constant); shader->SetUniform("pointLight.linear", pointLight.linear); shader->SetUniform("pointLight.quadratic", pointLight.quadratic); shader->SetUniform3fv("fl.position", 1, glm::value_ptr(camera.GetPosition())); shader->SetUniform3fv("fl.direction", 1, glm::value_ptr(flashlight.direction)); shader->SetUniform("fl.angle", glm::cos(glm::radians(flashlight.angle))); shader->SetUniform("fl.outerAngle", glm::cos(glm::radians(flashlight.outerAngle))); shader->SetUniform("fl.diffuse", flashlight.diffusionColor, true); shader->SetUniform("fl.specular", flashlight.specularColor, true); shader->SetUniform("fl.constant", flashlight.constant); shader->SetUniform("fl.linear", flashlight.linear); shader->SetUniform("fl.quadratic", flashlight.quadratic); shader->SetUniform3fv("viewPos", 1, glm::value_ptr(camera.GetPosition())); shader->SetUniformMatrix4fv("view", 1, GL_FALSE, glm::value_ptr(camera.GetMatrix())); shader->SetUniformMatrix4fv("projection", 1, GL_FALSE, glm::value_ptr(camera.GetProjection())); shader->SetUniformTexture("material.diffuse", cubeMaterial->GetPropertyValue<oglu::Texture>("diffuse"), 0); shader->SetUniformTexture("material.specular", cubeMaterial->GetPropertyValue<oglu::Texture>("specular"), 1); shader->SetUniform("material.shininess", cubeMaterial->GetPropertyValue<float>("shininess")); for (oglu::Object& cube : cubes) { shader->SetUniform("model", cube); shader->SetUniformMatrix3fv("normal", 1, GL_FALSE, glm::value_ptr(cube.GetNormalMatrix())); cube.Render(); } lightSourceShader->Use(); lightSourceShader->SetUniformMatrix4fv("model", 1, GL_FALSE, glm::value_ptr(lightSource.GetMatrix(true))); lightSourceShader->SetUniformMatrix4fv("view", 1, GL_FALSE, glm::value_ptr(camera.GetMatrix())); lightSourceShader->SetUniformMatrix4fv("projection", 1, GL_FALSE, glm::value_ptr(camera.GetProjection())); lightSourceShader->SetUniform("color", pointLight.diffusionColor, true); lightSource.Render(); ImGui::Begin("Controls"); ImGui::SetNextItemOpen(true, ImGuiCond_Once); if(ImGui::CollapsingHeader("Scene")); { ImGui::ColorEdit3("Background color", &bgColor.r); ImGui::SliderFloat("FOV", &camera.fov, 30.0f, 100.0f); ImGui::SliderFloat("zNear", &camera.zNear, 0.01, 1.0f); ImGui::SliderFloat("zFar", &camera.zFar, 2.0f, 100.0f); } ImGui::SetNextItemOpen(true, ImGuiCond_Once); if(ImGui::CollapsingHeader("Lighting")) { ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Ambient")) { ImGui::ColorEdit3("Color", &ambient.color.r); ImGui::SliderFloat("Intensity", &ambient.intensity, 0.0f, 1.0f); ImGui::TreePop(); ImGui::Separator(); } ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Point")) { ImGui::ColorEdit3("Diffusion", &pointLight.diffusionColor.r); ImGui::ColorEdit3("Specular", &pointLight.specularColor.r); ImGui::SliderFloat3("Position", pointLight.GetPositionPointer(), -5.0f, 5.0f); ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Attenuation")) { ImGui::SliderFloat("Constant", &pointLight.constant, 1.0f, 4.0f); ImGui::SliderFloat("Linear", &pointLight.linear, 0.0014f, 0.7f); ImGui::SliderFloat("Quadratic", &pointLight.quadratic, 0.00007f, 1.8f); ImGui::TreePop(); } ImGui::TreePop(); } ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Flashlight")) { ImGui::ColorEdit3("Diffusion", &flashlight.diffusionColor.r); ImGui::ColorEdit3("Specular", &flashlight.specularColor.r); ImGui::SliderFloat("Angle", &flashlight.angle, 1.0f, flashlight.outerAngle - 1.0f); ImGui::SliderFloat("Outer angle", &flashlight.outerAngle, flashlight.angle + 1.0f, 60.0f); ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Attenuation")) { ImGui::SliderFloat("Constant", &flashlight.constant, 1.0f, 4.0f); ImGui::SliderFloat("Linear", &flashlight.linear, 0.0014f, 0.7f); ImGui::SliderFloat("Quadratic", &flashlight.quadratic, 0.00007f, 1.8f); ImGui::TreePop(); } ImGui::TreePop(); } } ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::CollapsingHeader("Cube Material")) { ImGui::SliderFloat("Shininess", cubeMaterial->GetProperty<float>("shininess"), 1.0f, 256.0f); } ImGui::End(); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); glfwSwapBuffers(window); glfwPollEvents(); t += 0.05f; } ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwTerminate(); return 0; }
.text addi $t0, $zero, 3 # A = 3 addi $t1, $zero, 2 # B = 2 addi $t2, $zero, 1 # C = 1 slt $t3, $t0, $t1 beq $t3, $zero, elseif addi $t5, $zero, 3 j endif elseif: slt $t3, $t1, $t2 # B < C = C > B beq $t3, $zero, else # condition # code addi $t5, $zero, 1 # end code j endif else: # code addi $t5, $zero, 0 # end code endif: li $v0, 1 # service 1 is print integer add $a0, $t5, $zero # load desired value into argument register $a0, using pseudo-op syscall .data
; A074280: Duplicate of A000523. ; 0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5 add $0,1 lpb $0,$0 div $0,2 add $2,1 lpe mov $1,$2
; A094204: Duplicate of A078584. ; 1,2,2,2,6,6,2,6,2,4,6,6,4,4,4,4,2,2,6,6,2,2,2,12,2,6,10,6,2,4,10,4,4,6 mul $0,2 cal $0,100803 ; A100802(m) where A100802(m) > A100802(m-1). mov $1,$0 div $1,2 add $1,1
<% from pwnlib.shellcraft.powerpc.linux import syscall %> <%page args="clock_id, flags, req, rem"/> <%docstring> Invokes the syscall clock_nanosleep. See 'man 2 clock_nanosleep' for more information. Arguments: clock_id(clockid_t): clock_id flags(int): flags req(timespec): req rem(timespec): rem </%docstring> ${syscall('SYS_clock_nanosleep', clock_id, flags, req, rem)}
section .data msg : db 'Enter an alphabet :' l : equ $-msg ans1 : db 'Capslock is On',10 l1 : equ $-ans1 ans2 :db 'Capslock is Off',10 l2 : equ $-ans2 ans3 : db 'Error , pressed some other key ',10 l3 equ $-ans3 section .bss d1 : resb 1 section .text global _start: _start: mov eax, 4 mov ebx, 1 mov ecx, msg mov edx, l int 80h mov eax, 3 mov ebx, 0 mov ecx, d1 mov edx, 1 int 80h ;mov bl, 0 mov al, byte[d1] cmp al,'A'; setnc bl;setnc and setae <--> >= cmp al, 'Z'+1 setc bh;< and bl, bh;bl=bl&&bh cmp bl, 1 je if else: mov al, byte[d1] cmp al, 'a' setnc bl cmp al, 'z'+1 setc bh and bl, bh cmp bl, 1 je ending else1: mov eax, 4 mov ebx, 1 mov ecx, ans3 mov edx, l3 int 80h mov eax, 1 mov ebx, 0 int 80h if: mov eax, 4 mov ebx, 1 mov ecx, ans1 mov edx, l1 int 80h mov eax, 1 mov ebx, 0 int 80h ending: mov eax, 4 mov ebx, 1 mov ecx, ans2 mov edx, l2 int 80h mov eax, 1 mov ebx, 0 int 80h
; CRT0 for the Sharp X1 - ; ; Karl Von Dyson (for X1s.org) ; ; $Id: x1_crt0.asm,v 1.17 2016-07-20 05:45:02 stefano Exp $ ; IF !DEFINED_CRT_ORG_CODE defc CRT_ORG_CODE = 0x8000 ENDIF defc TAR__register_sp = 0xFDFF INCLUDE "crt/classic/crt_rules.inc" org CRT_ORG_CODE if (CRT_ORG_CODE < 32768) defs ZORG_TOO_LOW endif INCLUDE "crt/classic/crt_init_sp.asm" INCLUDE "crt/classic/crt_init_atexit.asm" call crt0_init_bss IF DEFINED_USING_amalloc ld hl,0 add hl,sp INCLUDE "crt/classic/crt_init_amalloc.asm" ENDIF ; re-activate IPL ld bc,$1D00 xor a out (c),a ld hl,$FE00 push hl EXTERN im2_Init call im2_Init pop hl EXTERN im2_EmptyISR ld hl,im2_EmptyISR ld b,128 isr_table_fill: ld ($FE00),hl inc hl inc hl djnz isr_table_fill ld hl,_kbd_isr ld ($FE52),hl im 2 ei call _wait_sub_cpu ld bc, $1900 ld a, $E4 ; Interrupt vector set out (c), a call _wait_sub_cpu ld bc, $1900 ld a, $52 ; out (c), a call _main cleanup: call crt0_exit push hl ; return code end: jr end cleanup_exit: ret _kbd_isr: push af push bc push hl call asm_x1_keyboard_handler pop hl pop bc pop af ei reti
db 0 ; species ID placeholder db 75, 100, 95, 110, 40, 70 ; hp atk def spd sat sdf db NORMAL, NORMAL ; type db 45 ; catch rate db 211 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F0 ; gender ratio db 100 ; unknown 1 db 20 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/tauros/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_SLOW ; growth rate dn EGG_GROUND, EGG_GROUND ; egg groups ; tm/hm learnset tmhm HEADBUTT, CURSE, TOXIC, ZAP_CANNON, ROCK_SMASH, SUNNY_DAY, SNORE, BLIZZARD, HYPER_BEAM, ICY_WIND, PROTECT, IRON_HEAD, THUNDER, EARTHQUAKE, RETURN, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, FIRE_BLAST, PURSUIT, REST, ATTRACT, SURF, STRENGTH, FLAMETHROWER, THUNDERBOLT, ICE_BEAM ; end
; A127595: a(n) = F(4n) - 2F(2n) where F(n) = Fibonacci numbers A000045. ; Submitted by Jamie Morken(s1) ; 0,1,15,128,945,6655,46080,317057,2176335,14925184,102320625,701373311,4807434240,32951037313,225850798095,1548007091840,10610205501105,72723448842367,498453982018560,3416454544730369,23416728143799375,160500643280538496,1100087776963284465,7540113801073722623,51680708845243269120,354224848154089377025,2427893228334072522255,16641027750448028519552,114059301025492267684785,781774079429804656743679,5358359254987870623360000,36726740705497673776823681,251728825683528267730708815 mov $3,1 lpb $0 sub $0,$3 mov $1,$4 add $2,1 add $2,$4 add $4,$2 lpe mov $0,$4 add $0,$1 mul $0,$2
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %r9 push %rbp push %rbx push %rcx push %rdi lea addresses_UC_ht+0x22e1, %rcx nop nop dec %rbp movb $0x61, (%rcx) nop nop nop nop nop xor %r15, %r15 lea addresses_normal_ht+0xe93e, %r11 nop and $3420, %rdi mov (%r11), %rbx nop nop nop xor $43631, %r9 lea addresses_WC_ht+0xbafe, %rbp nop nop xor %r11, %r11 movb $0x61, (%rbp) nop add %rbp, %rbp lea addresses_normal_ht+0x9bfa, %r15 nop nop nop nop sub %rdi, %rdi and $0xffffffffffffffc0, %r15 vmovaps (%r15), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $1, %xmm7, %rcx nop nop nop nop inc %r15 pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r14 push %r15 push %r8 push %rbp push %rdi // Store lea addresses_PSE+0x19a67, %r8 nop nop nop nop nop add %r14, %r14 movl $0x51525354, (%r8) nop nop add $23580, %r8 // Store mov $0xbfe, %r8 add %rdi, %rdi mov $0x5152535455565758, %rbp movq %rbp, %xmm1 movaps %xmm1, (%r8) nop nop nop nop inc %r15 // Faulty Load mov $0xbfe, %rbp sub $36406, %r13 vmovntdqa (%rbp), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $0, %xmm3, %r15 lea oracles, %r8 and $0xff, %r15 shlq $12, %r15 mov (%r8,%r15,1), %r15 pop %rdi pop %rbp pop %r8 pop %r15 pop %r14 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_P', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_P', 'AVXalign': True, 'size': 16}} [Faulty Load] {'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_P', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 1}} {'src': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 1}} {'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_normal_ht', 'AVXalign': True, 'size': 32}, 'OP': 'LOAD'} {'58': 18881, '80': 2688, '00': 260} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 80 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 80 58 58 80 58 80 58 58 58 58 58 58 58 58 58 58 58 80 80 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 80 58 58 80 58 80 58 58 58 58 80 58 80 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 80 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 80 80 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 80 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 80 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 80 58 58 58 58 80 58 58 58 80 58 80 00 58 58 80 80 58 80 80 58 80 58 80 58 58 58 58 80 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 80 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 80 80 58 58 80 58 80 58 58 58 80 58 58 58 58 58 58 58 58 80 58 58 58 80 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 80 58 00 80 58 58 80 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 80 58 80 58 80 58 58 58 58 58 80 58 00 58 58 58 58 58 58 58 80 58 80 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 80 58 58 58 58 58 58 80 58 58 58 58 58 58 58 80 58 58 58 58 80 58 58 58 58 58 58 80 58 58 58 80 58 58 58 58 58 58 58 58 80 58 58 58 58 58 80 58 58 58 58 80 80 80 58 58 58 58 80 58 58 58 80 58 80 58 58 58 58 58 58 58 80 80 58 58 80 58 58 58 58 80 58 58 58 80 58 80 58 58 00 80 58 58 58 58 58 58 80 80 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 80 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 80 58 80 58 58 58 80 58 58 58 58 58 58 58 58 80 58 58 80 58 58 80 58 58 58 58 58 58 58 58 58 58 80 58 58 80 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 80 58 58 58 58 00 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 80 58 58 58 58 80 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 80 58 80 58 58 58 58 58 58 58 58 58 80 58 58 58 58 80 80 58 58 58 58 58 58 58 58 58 58 58 */
; A061347: Period 3: repeat [1, 1, -2]. ; 1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2,1,1,-2 mod $0,3 pow $0,$0 mov $1,3 sub $1,$0 sub $1,1
#pragma once #include "myparser_ast_spec.hpp" namespace myparser { template <> class Pass<PASS_REPR>: public PassProto<PASS_REPR> { private: const bool optionV; const bool optionC; protected: std::ostream &out; size_t indent; virtual void putName(const std::string &) {} virtual void putIndex(const size_t) {} virtual void putText(const std::string &) {} virtual void putSpace(const std::string &) {} virtual void putKeyword(const std::string &) {} virtual void putError(const std::string &) {} virtual void putMainBegin() {} virtual void putMainEnd() {} virtual void putPlaceHolder() {} virtual void putBegin() {} virtual void putEnd() {} virtual void putLnBegin() {} virtual void putLnEnd() {} virtual void putLn(const bool) {} public: inline Pass( std::ostream &target, const bool verbose, const bool compact ): PassProto<PASS_REPR>(), optionV(verbose), optionC(compact), out(target), indent(0) {} // virtual ~Pass() {} // specialized nodes template <size_t I> void run(const NodeSpace<I> *node) { putMainBegin(); putName(node->getRuleName()); putBegin(); putSpace(node->getFullText()); putEnd(); putMainEnd(); } template <size_t I> void run(const NodeKeyword<I> *node) { putMainBegin(); putName(node->getRuleName()); putBegin(); putKeyword(node->getFullText()); putEnd(); putMainEnd(); } // common nodes template <size_t I> void run(const NodeListIndexed<I> *node) { putMainBegin(); putName(node->getRuleName()); putIndex(I); // getIndex() == I std::vector<Node<> *> children1; if (!optionV) { for (Node<> *child: node->getChildren()) { if (!child->empty()) { children1.push_back(child); } } } const std::vector<Node<> *> &children = optionV ? node->getChildren() : children1; if (optionC && children.size() == 1) { putBegin(); children[0]->runPass(this); putEnd(); } else { putPlaceHolder(); putLnBegin(); ++indent; bool first = true; for (const Node<> *child: children) { putLn(first); first = false; child->runPass(this); } --indent; putLnEnd(); } putMainEnd(); } template <class TX = void> // actually not a template void run(const NodeTextPure<> *node) { putMainBegin(); putName(node->getRuleName()); putBegin(); putText(node->getFullText()); putEnd(); putMainEnd(); } template <class E> void run(const NodeTextOrError<E> *node) { putMainBegin(); putName(node->getRuleName()); putBegin(); if (node->accepted()) { putText(node->getFullText()); } else { putError(E::getStr()); } putEnd(); putMainEnd(); } template <class E> void run(const NodeError<E> *node) { putMainBegin(); putName(node->getRuleName()); putBegin(); putError(E::getStr()); putEnd(); putMainEnd(); } }; template <class TX = void> // actually not a template class PassReprText: public Pass<PASS_REPR> { protected: virtual void putText(const std::string &text) { out << text; } virtual void putSpace(const std::string &text) { out << text; } virtual void putKeyword(const std::string &text) { out << text; } public: inline PassReprText( std::ostream &target ): Pass<PASS_REPR>(target, true, false) {} // virtual ~PassReprText() {} }; template <class TX = void> // actually not a template class PassReprSimple: public Pass<PASS_REPR> { protected: virtual void putText(const std::string &text) { out << style_string << style_underline << text << style_normal; } virtual void putSpace(const std::string &text) { out << style_space << style_underline << text << style_normal; } virtual void putKeyword(const std::string &text) { out << style_keyword << style_underline << text << style_normal; } virtual void putError(const std::string &error) { out << style_error << "ERROR: " << style_normal << error; } virtual void putPlaceHolder() { out << "=>"; } virtual void putLn(const bool) { out << '\n'; for (size_t i = 0; i < indent; ++i) { out << " "; } } public: inline PassReprSimple( std::ostream &target, const bool verbose = false, const bool compact = true ): Pass<PASS_REPR>(target, verbose, compact) {} // virtual ~PassReprSimple() {} }; template <class TX = void> // actually not a template class PassReprFull: public Pass<PASS_REPR> { protected: virtual void putName(const std::string &name) { out << name; } virtual void putIndex(const size_t index) { out << '['; out << style_data << index << style_normal; out << ']'; } virtual void putText(const std::string &text) { out << style_string << style_underline << text << style_normal; } virtual void putSpace(const std::string &text) { out << style_space << style_underline << text << style_normal; } virtual void putKeyword(const std::string &text) { out << style_keyword << style_underline << text << style_normal; } virtual void putError(const std::string &error) { out << style_error << "ERROR: " << style_normal << error; } virtual void putBegin() { out << style_space << " - " << style_normal; } virtual void putLn(const bool) { out << '\n'; for (size_t i = 0; i < indent; ++i) { out << " "; } } public: inline PassReprFull( std::ostream &target, const bool verbose = false, const bool compact = true ): Pass<PASS_REPR>(target, verbose, compact) {} // virtual ~PassReprFull() {} }; template <class TX = void> // actually not a template class PassReprJSON: public Pass<PASS_REPR> { protected: void putStrEscaped(const std::string &str) { for (const char c: str) { switch (c) { // case '\0': // never reach case '\b': out << "\\b"; break; case '\t': out << "\\t"; break; case '\n': out << "\\n"; break; case '\v': out << "\\v"; break; case '\f': out << "\\f"; break; case '\r': out << "\\r"; break; case '\"': out << "\\\""; break; case '\'': out << "\\\'"; break; case '\\': out << "\\\\"; break; case '\x7F': out << "\\x7F"; break; default: if ('\0' <= c && c < '\x10') { out << "\\x0" << ("0123456789ABCDEF"[c & 0xF]); } else if ('\x10' <= c && c < '\x20') { out << "\\x1" << ("0123456789ABCDEF"[c & 0xF]); } else { out << c; } break; } } } virtual void putName(const std::string &name) { putLn1(); out << "\"rulename\": \"" << name << "\","; } virtual void putIndex(const size_t index) { putLn1(); out << "\"ruleindex\": \"" << index << "\","; } virtual void putText(const std::string &text) { putLn1(); out << "\"text\": \""; putStrEscaped(text); out << "\","; } virtual void putSpace(const std::string &text) { putLn1(); out << "\"text\": \""; putStrEscaped(text); out << "\","; } virtual void putKeyword(const std::string &text) { putLn1(); out << "\"text\": \""; putStrEscaped(text); out << "\","; } virtual void putError(const std::string &error) { putLn1(); out << "\"error\": \""; putStrEscaped(error); out << "\","; } virtual void putMainBegin() { out << "{"; ++indent; // extra } virtual void putMainEnd() { --indent; // extra putLn1(); out << "}"; } virtual void putLnBegin() { putLn1(); out << "\"children\": ["; --indent; // extra } virtual void putLnEnd() { ++indent; // extra out << "],"; } virtual void putLn(const bool first) { if (!first) { out << ','; putLn1(); } } void putLn1() { out << '\n'; for (size_t i = 0; i < indent; ++i) { out << " "; } } public: inline PassReprJSON( std::ostream &target, const bool verbose = false ): Pass<PASS_REPR>(target, verbose, false) {} // virtual ~PassReprJSON() {} }; }
//===--- StringOptimization.cpp - Optimize string operations --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This pass performs several optimizations on String operations. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "string-optimization" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Analysis/ValueTracking.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SIL/SILGlobalVariable.h" #include "swift/SIL/SILBuilder.h" #include "swift/AST/SemanticAttrs.h" #include "swift/AST/ParameterList.h" #include "swift/AST/ASTMangler.h" #include "swift/Demangling/Demangle.h" #include "llvm/Support/Debug.h" using namespace swift; namespace { /// Optimizes String operations with constant operands. /// Specifically: /// * Replaces x.append(y) with x = y if x is empty. /// * Removes x.append("") /// * Replaces x.append(y) with x = x + y if x and y are constant strings. /// * Replaces _typeName(T.self) with a constant string if T is statically /// known. /// * Replaces String(literal).utf8CString with the string literal itself. /// /// This pass must run on high-level SIL, where semantic calls are still in /// place. /// /// The optimization is implemented in a simple way. Therfore it cannot handle /// complicated patterns, e.g. the dataflow analysis for the String.append self /// argument is only done within a single block. /// But this is totally sufficient to be able to constant propagate strings in /// string interpolations. /// /// If we want to make this optimization more powerful it's best done by using /// the ConstExprStepEvaluator (which is currently lacking a few features to be /// used for this optimization). class StringOptimization { struct StringInfo { /// The string StringRef str; /// Negative means: not constant int reservedCapacity = 0; StringInfo(StringRef str, int reservedCapacity = 0) : str(str), reservedCapacity(reservedCapacity) { } bool isConstant() const { return reservedCapacity >= 0; } bool isEmpty() const { return isConstant() && str.empty(); } static StringInfo unknown() { return StringInfo(StringRef(), -1); } }; /// The stdlib's String type. SILType stringType; /// The String initializer which takes an UTF8 string literal as argument. SILFunction *makeUTF8Func = nullptr; /// Caches the analysis result for an alloc_stack or an inout function /// argument, whether it is an "identifyable" object. /// See mayWriteToIdentifyableObject(). llvm::DenseMap<SILValue, bool> identifyableObjectsCache; public: bool run(SILFunction *F); private: bool optimizeBlock(SILBasicBlock &block); bool optimizeStringAppend(ApplyInst *appendCall, llvm::DenseMap<SILValue, SILValue> &storedStrings); bool optimizeStringConcat(ApplyInst *concatCall); bool optimizeTypeName(ApplyInst *typeNameCall); bool optimizeGetCString(ApplyInst *getCStringCall); static ApplyInst *isSemanticCall(SILInstruction *inst, StringRef attr, unsigned numArgs); StoreInst *isStringStoreToIdentifyableObject(SILInstruction *inst); static void invalidateModifiedObjects(SILInstruction *inst, llvm::DenseMap<SILValue, SILValue> &storedStrings); static StringInfo getStringInfo(SILValue value); static StringInfo getStringFromStaticLet(SILValue value); static Optional<int> getIntConstant(SILValue value); static void replaceAppendWith(ApplyInst *appendCall, SILValue newValue); static SILValue copyValue(SILValue value, SILInstruction *before); ApplyInst *createStringInit(StringRef str, SILInstruction *beforeInst); }; /// The main entry point of the optimization. bool StringOptimization::run(SILFunction *F) { NominalTypeDecl *stringDecl = F->getModule().getASTContext().getStringDecl(); if (!stringDecl) return false; stringType = SILType::getPrimitiveObjectType( stringDecl->getDeclaredInterfaceType()->getCanonicalType()); bool changed = false; for (SILBasicBlock &block : *F) { changed |= optimizeBlock(block); } return changed; } /// Run the optimization on a basic block. bool StringOptimization::optimizeBlock(SILBasicBlock &block) { bool changed = false; /// Maps identifyable objects (alloc_stack, inout parameters) to string values /// which are stored in those objects. llvm::DenseMap<SILValue, SILValue> storedStrings; for (auto iter = block.begin(); iter != block.end();) { SILInstruction *inst = &*iter++; if (StoreInst *store = isStringStoreToIdentifyableObject(inst)) { storedStrings[store->getDest()] = store->getSrc(); continue; } if (ApplyInst *append = isSemanticCall(inst, semantics::STRING_APPEND, 2)) { if (optimizeStringAppend(append, storedStrings)) { changed = true; continue; } } if (ApplyInst *append = isSemanticCall(inst, semantics::STRING_CONCAT, 3)) { if (optimizeStringConcat(append)) { changed = true; continue; } } if (ApplyInst *typeName = isSemanticCall(inst, semantics::TYPENAME, 2)) { if (optimizeTypeName(typeName)) { changed = true; continue; } } if (ApplyInst *getCString = isSemanticCall(inst, semantics::STRING_GET_UTF8_CSTRING, 1)) { if (optimizeGetCString(getCString)) { changed = true; continue; } } // Remove items from storedStrings if inst overwrites (or potentially // overwrites) a stored String in an identifyable object. invalidateModifiedObjects(inst, storedStrings); } return changed; } /// Optimize String.append in case anything is known about the parameters. bool StringOptimization::optimizeStringAppend(ApplyInst *appendCall, llvm::DenseMap<SILValue, SILValue> &storedStrings) { SILValue rhs = appendCall->getArgument(0); StringInfo rhsString = getStringInfo(rhs); // Remove lhs.append(rhs) if rhs is empty. if (rhsString.isEmpty()) { appendCall->eraseFromParent(); return true; } SILValue lhsAddr = appendCall->getArgument(1); StringInfo lhsString = getStringInfo(storedStrings[lhsAddr]); // The following two optimizations are a trade-off: Performance-wise it may be // benefitial to initialize an empty string with reserved capacity and then // append multiple other string components. // Removing the empty string (with the reserved capacity) might result in more // allocations. // So we just do this optimization up to a certain capacity limit (found by // experiment). if (lhsString.reservedCapacity > 50) return false; // Replace lhs.append(rhs) with 'lhs = rhs' if lhs is empty. if (lhsString.isEmpty()) { replaceAppendWith(appendCall, copyValue(rhs, appendCall)); storedStrings[lhsAddr] = rhs; return true; } // Replace lhs.append(rhs) with "lhs = lhs + rhs" if both lhs and rhs are // constant. if (lhsString.isConstant() && rhsString.isConstant()) { std::string concat = lhsString.str.str(); concat += rhsString.str; if (ApplyInst *stringInit = createStringInit(concat, appendCall)) { replaceAppendWith(appendCall, stringInit); storedStrings[lhsAddr] = stringInit; return true; } } return false; } /// Optimize String.+ in case anything is known about the parameters. bool StringOptimization::optimizeStringConcat(ApplyInst *concatCall) { SILValue lhs = concatCall->getArgument(0); SILValue rhs = concatCall->getArgument(1); StringInfo rhsString = getStringInfo(rhs); // Replace lhs + "" with lhs if (rhsString.isEmpty()) { lhs = copyValue(lhs, concatCall); concatCall->replaceAllUsesWith(lhs); concatCall->eraseFromParent(); return true; } // Replace "" + rhs with rhs StringInfo lhsString = getStringInfo(lhs); if (lhsString.isEmpty()) { rhs = copyValue(rhs, concatCall); concatCall->replaceAllUsesWith(rhs); concatCall->eraseFromParent(); return true; } // Replace lhs + rhs with "lhs + rhs" if both lhs and rhs are constant. if (lhsString.isConstant() && rhsString.isConstant()) { std::string concat = lhsString.str.str(); concat += rhsString.str; if (ApplyInst *stringInit = createStringInit(concat, concatCall)) { concatCall->replaceAllUsesWith(stringInit); concatCall->eraseFromParent(); return true; } } return false; } /// Checks if the demangling tree contains any node which prevents constant /// folding of the type name. static bool containsProblematicNode(Demangle::Node *node, bool qualified) { switch (node->getKind()) { case Demangle::Node::Kind::LocalDeclName: // The printing of contexts for local types is completely different // in the runtime. Don't constant fold if we need to print the context. if (qualified) return true; break; case Demangle::Node::Kind::Class: { // ObjC class names are not derived from the mangling but from the // ObjC runtime. We cannot constant fold this. Demangle::Node *context = node->getChild(0); if (context->getKind() == Demangle::Node::Kind::Module && context->getText() == "__C") { return true; } break; } default: break; } for (Demangle::Node *child : *node) { if (containsProblematicNode(child, qualified)) return true; } return false; } /// Try to replace a _typeName() call with a constant string if the type is /// statically known. bool StringOptimization::optimizeTypeName(ApplyInst *typeNameCall) { // Check, if the type is statically known. auto *anyType = dyn_cast<InitExistentialMetatypeInst>(typeNameCall->getArgument(0)); if (!anyType) return false; auto *metatypeInst = dyn_cast<MetatypeInst>(anyType->getOperand()); if (!metatypeInst) return false; auto metatype = metatypeInst->getType().getAs<MetatypeType>(); Type ty = metatype->getInstanceType(); if (ty->hasArchetype() || ty->hasDynamicSelfType()) return false; // Usually the "qualified" parameter of _typeName() is a constant boolean. Optional<int> isQualifiedOpt = getIntConstant(typeNameCall->getArgument(1)); if (!isQualifiedOpt) return false; bool isQualified = isQualifiedOpt.getValue(); // Create the constant type string by mangling + demangling. Mangle::ASTMangler mangler; std::string mangledTypeName = mangler.mangleTypeForTypeName(ty); Demangle::DemangleOptions options; options.PrintForTypeName = true; options.DisplayLocalNameContexts = false; options.QualifyEntities = isQualified; Demangle::Context ctx; Demangle::NodePointer root = ctx.demangleTypeAsNode(mangledTypeName); if (!root || containsProblematicNode(root, isQualified)) return false; std::string typeStr = nodeToString(root, options); if (typeStr.empty()) return false; ApplyInst *stringInit = createStringInit(typeStr, typeNameCall); if (!stringInit) return false; typeNameCall->replaceAllUsesWith(stringInit); typeNameCall->eraseFromParent(); return true; } /// Replaces a String initializer followed by String.utf8CString with a /// (UTF8 encoded) string literal. /// /// Note that string literals are always generated with a trailing 0-byte. bool StringOptimization::optimizeGetCString(ApplyInst *getCStringCall) { // Is this a String.utf8CString of a literal String? StringInfo stringInfo = getStringInfo(getCStringCall->getArgument(0)); if (!stringInfo.isConstant()) return false; StringLiteralInst *literal = nullptr; bool changed = false; SmallVector<SILInstruction *, 16> workList; workList.push_back(getCStringCall); /// String.utf8CString returns an array of Int8. Search for ref_tail_addr of /// the array buffer. while (!workList.empty()) { SILInstruction *inst = workList.pop_back_val(); // Look through string_extract which extract the buffer from the array. if (isa<StructExtractInst>(inst) || inst == getCStringCall) { for (Operand *use : cast<SingleValueInstruction>(inst)->getUses()) { workList.push_back(use->getUser()); } continue; } if (auto *rta = dyn_cast<RefTailAddrInst>(inst)) { // Replace the ref_tail_addr with a pointer_to_address of the string // literal. if (!literal) { // Build the literal if we don't have one, yet. SILBuilder builder(getCStringCall); literal = builder.createStringLiteral(getCStringCall->getLoc(), stringInfo.str, StringLiteralInst::Encoding::UTF8); } SILBuilder builder(rta); auto *strAddr = builder.createPointerToAddress(rta->getLoc(), literal, rta->getType(), /*isStrict*/ false); rta->replaceAllUsesWith(strAddr); changed = true; } } return changed; } /// Returns the apply instruction if \p inst is a call of a function which has /// a semantic attribute \p attr and exactly \p numArgs arguments. ApplyInst *StringOptimization::isSemanticCall(SILInstruction *inst, StringRef attr, unsigned numArgs) { auto *apply = dyn_cast<ApplyInst>(inst); if (!apply || apply->getNumArguments() != numArgs) return nullptr; SILFunction *callee = apply->getReferencedFunctionOrNull(); if (callee && callee->hasSemanticsAttr(attr)) return apply; return nullptr; } /// Returns true for all instructions which we can safely analyze as a potential /// write to an identifyable objects. /// /// If we see any other kind of object user, which may write to an object, or /// let the object address escape in some unexpected way (like address /// projections), we'll just ignore that object and will not treat it as /// "identifyable" object. static bool mayWriteToIdentifyableObject(SILInstruction *inst) { // For simplicity, only handle store and apply. This is sufficient for most // case, especially for string interpolation. return isa<StoreInst>(inst) || isa<ApplyInst>(inst); } /// Returns the store intstruction if \p inst is a store of a String to an /// identifyable object. StoreInst *StringOptimization:: isStringStoreToIdentifyableObject(SILInstruction *inst) { auto *store = dyn_cast<StoreInst>(inst); if (!store) return nullptr; if (store->getSrc()->getType() != stringType) return nullptr; SILValue destAddr = store->getDest(); // We only handle alloc_stack an indirect function arguments. For those we can // be sure that they are not aliased, just by checking all users. if (!isa<AllocStackInst>(destAddr) && !isExclusiveArgument(destAddr)) return nullptr; if (identifyableObjectsCache.count(destAddr) != 0) { return identifyableObjectsCache[destAddr] ? store : nullptr; } // Check if it's an "identifyable" object. This is the case if it only has // users which we are able to track in a simple way: stores and applies. for (Operand *use : destAddr->getUses()) { SILInstruction *user = use->getUser(); switch (user->getKind()) { // Those instructions do not write to destAddr nor let they destAddr // escape. case SILInstructionKind::DeallocStackInst: case SILInstructionKind::LoadInst: break; case SILInstructionKind::DebugValueInst: if (DebugValueInst::hasAddrVal(user)) break; LLVM_FALLTHROUGH; default: if (!mayWriteToIdentifyableObject(user)) { // We don't handle user. It is some instruction which may write to // destAddr or let destAddr "escape" (like an address projection). identifyableObjectsCache[destAddr] = false; return nullptr; } break; } } identifyableObjectsCache[destAddr] = true; return store; } /// Removes all objects from \p storedStrings which \p inst (potentially) /// modifies. void StringOptimization::invalidateModifiedObjects(SILInstruction *inst, llvm::DenseMap<SILValue, SILValue> &storedStrings) { // Ignore non-writing instructions, like "load", "dealloc_stack". // Note that identifyable objects (= keys in storedStrings) can only have // certain kind of instructions as users: all instruction which we handle in // isStringStoreToIdentifyableObject(). if (!mayWriteToIdentifyableObject(inst)) return; for (Operand &op : inst->getAllOperands()) { storedStrings.erase(op.get()); } } /// If \p value is a struct_extract, return its operand and field. static std::pair<SILValue, VarDecl *> skipStructExtract(SILValue value) { if (auto *sei = dyn_cast<StructExtractInst>(value)) return {sei->getOperand(), sei->getField()}; // Look through function calls, which do the struct_extract in the callee. // This specifically targets // String(stringInterpolation: DefaultStringInterpolation) // which is not inlined in the high level pipeline (due to the specified // effects). auto *apply = dyn_cast<ApplyInst>(value); if (!apply) return {value, nullptr}; SILFunction *callee = apply->getReferencedFunctionOrNull(); if (!callee || !callee->isDefinition()) return {value, nullptr}; // `String(stringInterpolation: DefaultStringInterpolation)` has only a single // basic block. Avoid the effort of searching all blocks for a `return`. auto *ret = dyn_cast<ReturnInst>(callee->getEntryBlock()->getTerminator()); if (!ret) return {value, nullptr}; auto *sei = dyn_cast<StructExtractInst>(ret->getOperand()); if (!sei) return {value, nullptr}; auto *arg = dyn_cast<SILFunctionArgument>(sei->getOperand()); if (!arg) return {value, nullptr}; value = apply->getArgument(arg->getIndex()); return {value, sei->getField()}; } /// Returns information about value if it's a constant string. StringOptimization::StringInfo StringOptimization::getStringInfo(SILValue value) { if (!value) return StringInfo::unknown(); // Look through struct_extract(struct(value)). // This specifically targets calls to // String(stringInterpolation: DefaultStringInterpolation) // which are not inlined in the high level pipeline. VarDecl *field = nullptr; std::tie(value, field) = skipStructExtract(value); if (field) { auto *si = dyn_cast<StructInst>(value); if (!si) return StringInfo::unknown(); value = si->getFieldValue(field); } auto *apply = dyn_cast<ApplyInst>(value); if (!apply) { return getStringFromStaticLet(value); } SILFunction *callee = apply->getReferencedFunctionOrNull(); if (!callee) return StringInfo::unknown(); if (callee->hasSemanticsAttr(semantics::STRING_INIT_EMPTY)) { // An empty string initializer. return StringInfo(""); } if (callee->hasSemanticsAttr(semantics::STRING_INIT_EMPTY_WITH_CAPACITY)) { // An empty string initializer with initial capacity. int reservedCapacity = std::numeric_limits<int>::max(); if (apply->getNumArguments() > 0) { if (Optional<int> capacity = getIntConstant(apply->getArgument(0))) reservedCapacity = capacity.getValue(); } return StringInfo("", reservedCapacity); } if (callee->hasSemanticsAttr(semantics::STRING_MAKE_UTF8)) { // A string literal initializer. SILValue stringVal = apply->getArgument(0); auto *stringLiteral = dyn_cast<StringLiteralInst>(stringVal); SILValue lengthVal = apply->getArgument(1); auto *intLiteral = dyn_cast<IntegerLiteralInst>(lengthVal); if (intLiteral && stringLiteral && // For simplicity, we only support UTF8 string literals. stringLiteral->getEncoding() == StringLiteralInst::Encoding::UTF8 && // This passed number of code units should always match the size of the // string in the string literal. Just to be on the safe side, check it. intLiteral->getValue() == stringLiteral->getValue().size()) { return StringInfo(stringLiteral->getValue()); } } return StringInfo::unknown(); } /// Return the string if \p value is a load from a global static let, which is /// initialized with a String constant. StringOptimization::StringInfo StringOptimization::getStringFromStaticLet(SILValue value) { // Match the pattern // %ptr_to_global = apply %addressor() // %global_addr = pointer_to_address %ptr_to_global // %value = load %global_addr auto *load = dyn_cast<LoadInst>(value); if (!load) return StringInfo::unknown(); auto *pta = dyn_cast<PointerToAddressInst>(load->getOperand()); if (!pta) return StringInfo::unknown(); auto *addressorCall = dyn_cast<ApplyInst>(pta->getOperand()); if (!addressorCall) return StringInfo::unknown(); SILFunction *addressorFunc = addressorCall->getReferencedFunctionOrNull(); if (!addressorFunc) return StringInfo::unknown(); // The addressor function has a builtin.once call to the initializer. BuiltinInst *onceCall = nullptr; SILFunction *initializer = findInitializer(addressorFunc, onceCall); if (!initializer) return StringInfo::unknown(); if (initializer->size() != 1) return StringInfo::unknown(); // Match the pattern // %addr = global_addr @staticStringLet // ... // %str = apply %stringInitializer(...) // store %str to %addr GlobalAddrInst *gAddr = nullptr; for (SILInstruction &inst : initializer->front()) { if (auto *ga = dyn_cast<GlobalAddrInst>(&inst)) { if (gAddr) return StringInfo::unknown(); gAddr = ga; } } if (!gAddr || !gAddr->getReferencedGlobal()->isLet()) return StringInfo::unknown(); Operand *gUse = gAddr->getSingleUse(); auto *store = dyn_cast<StoreInst>(gUse->getUser()); if (!store || store->getDest() != gAddr) return StringInfo::unknown(); SILValue initVal = store->getSrc(); // This check is probably not needed, but let's be on the safe side: // it prevents an infinite recursion if the initializer of the global is // itself a load of another global, and so on. if (isa<LoadInst>(initVal)) return StringInfo::unknown(); return getStringInfo(initVal); } /// Returns the constant integer value if \a value is an Int or Bool struct with /// an integer_literal as operand. Optional<int> StringOptimization::getIntConstant(SILValue value) { auto *boolOrIntStruct = dyn_cast<StructInst>(value); if (!boolOrIntStruct || boolOrIntStruct->getNumOperands() != 1) return None; auto *literal = dyn_cast<IntegerLiteralInst>(boolOrIntStruct->getOperand(0)); if (!literal || literal->getValue().getActiveBits() > 64) return None; return literal->getValue().getSExtValue(); } /// Replace a String.append() with a store of \p newValue to the destination. void StringOptimization::replaceAppendWith(ApplyInst *appendCall, SILValue newValue) { SILBuilder builder(appendCall); SILLocation loc = appendCall->getLoc(); SILValue destAddr = appendCall->getArgument(1); if (appendCall->getFunction()->hasOwnership()) { builder.createStore(loc, newValue, destAddr, StoreOwnershipQualifier::Assign); } else { builder.createDestroyAddr(loc, destAddr); builder.createStore(loc, newValue, destAddr, StoreOwnershipQualifier::Unqualified); } appendCall->eraseFromParent(); } /// Returns a copy of \p value. Depending if the function is in OSSA, insert /// either a copy_value or retain_value. SILValue StringOptimization::copyValue(SILValue value, SILInstruction *before) { SILBuilder builder(before); SILLocation loc = before->getLoc(); if (before->getFunction()->hasOwnership()) return builder.createCopyValue(loc, value); builder.createRetainValue(loc, value, builder.getDefaultAtomicity()); return value; } /// Creates a call to a string initializer. ApplyInst *StringOptimization::createStringInit(StringRef str, SILInstruction *beforeInst) { SILBuilder builder(beforeInst); SILLocation loc = beforeInst->getLoc(); SILModule &module = beforeInst->getFunction()->getModule(); ASTContext &ctxt = module.getASTContext(); if (!makeUTF8Func) { // Find the String initializer which takes a string_literal as argument. ConstructorDecl *makeUTF8Decl = ctxt.getMakeUTF8StringDecl(); if (!makeUTF8Decl) return nullptr; auto Mangled = SILDeclRef(makeUTF8Decl, SILDeclRef::Kind::Allocator).mangle(); makeUTF8Func = module.loadFunction(Mangled, SILModule::LinkingMode::LinkAll); if (!makeUTF8Func) return nullptr; } auto *literal = builder.createStringLiteral(loc, str, StringLiteralInst::Encoding::UTF8); auto *length = builder.createIntegerLiteral(loc, SILType::getBuiltinWordType(ctxt), literal->getCodeUnitCount()); auto *isAscii = builder.createIntegerLiteral(loc, SILType::getBuiltinIntegerType(1, ctxt), intmax_t(ctxt.isASCIIString(str))); SILType stringMetaType = SILType::getPrimitiveObjectType( CanType(MetatypeType::get(stringType.getASTType(), MetatypeRepresentation::Thin))); auto *metaTypeInst = builder.createMetatype(loc, stringMetaType); auto *functionRef = builder.createFunctionRefFor(loc, makeUTF8Func); return builder.createApply(loc, functionRef, SubstitutionMap(), { literal, length, isAscii, metaTypeInst }); } /// The StringOptimization function pass. class StringOptimizationPass : public SILFunctionTransform { public: void run() override { SILFunction *F = getFunction(); if (!F->shouldOptimize()) return; LLVM_DEBUG(llvm::dbgs() << "*** StringOptimization on function: " << F->getName() << " ***\n"); StringOptimization stringOptimization; bool changed = stringOptimization.run(F); if (changed) { invalidateAnalysis(SILAnalysis::InvalidationKind::CallsAndInstructions); } } }; } // end anonymous namespace SILTransform *swift::createStringOptimization() { return new StringOptimizationPass(); }
<% from pwnlib.shellcraft.i386.linux import syscall %> <%page args="mqdes, notification"/> <%docstring> Invokes the syscall mq_notify. See 'man 2 mq_notify' for more information. Arguments: mqdes(mqd_t): mqdes notification(sigevent): notification </%docstring> ${syscall('SYS_mq_notify', mqdes, notification)}
.size 8000 .data@0 01 .text@48 jp ff81 .data@9c 02 03 04 05 .text@100 jp lbegin .data@143 c0 .text@150 lbegin: ld hl, ff81 ld a, 0e ld(hl++), a ld a, 27 ld(hl++), a ld a, 3e ld(hl++), a ld a, 80 ld(hl++), a ld a, e0 ld(hl++), a ld a, 46 ld(hl++), a ld a, 0d ld(hl++), a ld a, 20 ld(hl++), a ld a, fd ld(hl++), a ld a, af ld(hl++), a ld a, ea ld(hl++), a ld a, 00 ld(hl++), a ld a, 80 ld(hl++), a xor a, a ld(hl++), a ld a, fa ld(hl++), a ld a, 9e ld(hl++), a ld a, fe ld(hl++), a ld a, 06 ld(hl++), a inc a ld(hl++), a ld a, 00 ld(hl++), a ld a, e0 ld(hl++), a ld a, 80 ld(hl++), a ld a, 0e ld(hl++), a ld a, 28 ld(hl++), a ld a, 0d ld(hl++), a ld a, 20 ld(hl++), a ld a, fd ld(hl++), a ld a, c3 ld(hl++), a xor a, a ld(hl++), a ld a, 70 ld(hl++), a ld b, 90 call lwaitly_b ld a, 01 ld(8000), a ld hl, 809c inc a ld(hl++), a inc a ld(hl++), a inc a ld(hl++), a inc a ld(hl++), a ld hl, fe00 ld c, a0 ld a, 06 lbegin_fill_oam: ld(hl++), a dec c jrnz lbegin_fill_oam ld a, 90 ldff(45), a ld a, 40 ldff(41), a xor a, a ldff(0f), a ld a, 02 ldff(ff), a ei nop halt .text@7000 lprint_ff80: ld b, 91 call lwaitly_b xor a, a ldff(40), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ldff a, (80) ld(9800), a ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r15 push %r8 push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0x94ed, %r15 nop nop nop nop nop inc %r8 movb $0x61, (%r15) nop inc %r8 lea addresses_A_ht+0x1b6e9, %rsi lea addresses_UC_ht+0x159ed, %rdi xor $3511, %r12 mov $100, %rcx rep movsq nop nop nop nop nop dec %r8 lea addresses_WT_ht+0x1ed, %r15 nop sub %r10, %r10 movb (%r15), %cl nop nop nop nop nop inc %r10 lea addresses_D_ht+0x1b6ed, %rsi nop nop nop and $42059, %r15 mov (%rsi), %edi nop nop nop nop sub %r10, %r10 lea addresses_A_ht+0xb26d, %r15 nop nop nop nop nop add %rdi, %rdi movw $0x6162, (%r15) nop nop nop nop nop xor $47519, %r8 lea addresses_WT_ht+0x685d, %rcx nop nop nop nop sub %r12, %r12 mov $0x6162636465666768, %r15 movq %r15, %xmm3 vmovups %ymm3, (%rcx) and $14805, %r8 lea addresses_D_ht+0x806d, %rsi lea addresses_UC_ht+0x103ed, %rdi nop nop and $31114, %rdx mov $47, %rcx rep movsl nop nop nop nop add %r10, %r10 lea addresses_WT_ht+0x4283, %rsi lea addresses_WC_ht+0x19849, %rdi nop nop nop nop xor $19369, %r15 mov $80, %rcx rep movsq xor %rdx, %rdx lea addresses_A_ht+0x1706d, %rsi lea addresses_WC_ht+0x1481d, %rdi nop nop nop cmp %r10, %r10 mov $4, %rcx rep movsb nop nop nop nop nop cmp $29901, %r8 lea addresses_UC_ht+0x13cb5, %rsi lea addresses_WT_ht+0xd681, %rdi clflush (%rdi) nop nop nop nop xor %r15, %r15 mov $83, %rcx rep movsq nop nop nop nop inc %rdx lea addresses_normal_ht+0x1a7ed, %rsi lea addresses_D_ht+0xf7fd, %rdi nop dec %r15 mov $94, %rcx rep movsq nop and %rsi, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %r8 pop %r15 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %rax push %rdi push %rsi // Store mov $0x2bba330000000f6d, %rdi nop add $47184, %rax movl $0x51525354, (%rdi) nop nop nop nop sub $9524, %r14 // Faulty Load lea addresses_WC+0x105ed, %rax nop nop nop xor %r10, %r10 movups (%rax), %xmm4 vpextrq $0, %xmm4, %r14 lea oracles, %rax and $0xff, %r14 shlq $12, %r14 mov (%rax,%r14,1), %r14 pop %rsi pop %rdi pop %rax pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 7}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 8}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 2}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 9}} {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 9}} {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 8}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': True, 'congruent': 7}} {'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 1}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_D_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 9}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 1}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 3}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 1}, 'dst': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 7}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 4}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A135416: a(n) = A036987(n)*(n+1)/2. ; 1,0,2,0,0,0,4,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 add $0,1 mov $2,$0 mov $3,1 lpb $2,1 lpb $0,1 trn $0,$3 mov $1,$3 mul $3,2 lpe sub $3,2 mov $2,$3 lpe
; A010009: a(0) = 1, a(n) = 19*n^2 + 2 for n>0. ; 1,21,78,173,306,477,686,933,1218,1541,1902,2301,2738,3213,3726,4277,4866,5493,6158,6861,7602,8381,9198,10053,10946,11877,12846,13853,14898,15981,17102,18261,19458,20693,21966,23277,24626,26013,27438,28901,30402,31941,33518,35133,36786,38477,40206,41973,43778,45621,47502,49421,51378,53373,55406,57477,59586,61733,63918,66141,68402,70701,73038,75413,77826,80277,82766,85293,87858,90461,93102,95781,98498,101253,104046,106877,109746,112653,115598,118581,121602,124661,127758,130893,134066,137277 pow $1,$0 gcd $1,2 mov $3,$0 mul $3,$0 mov $2,$3 mul $2,19 add $1,$2 mov $0,$1
; ; Old School Computer Architecture - SD Card driver ; Taken from the OSCA Bootcode by Phil Ruston 2011 ; ; Ported by Stefano Bodrato, 2012 ; ; Short delay to sync communications with card ; ; $Id: pause_4ms.asm,v 1.4 2012/09/26 14:15:25 stefano Exp $ ; XLIB pause_4ms INCLUDE "flos.def" pause_4ms: xor a jp kjt_timer_wait
#pragma once #include <vector> #include <fstream> #include <string> #include "Data/GLTexture.hpp" #include "External/picoPNG.h" #include "Debug.hpp" namespace Engine { extern bool ReadFileToBuffer(std::string filePath, std::vector<unsigned char> &buffer); extern GLTexture LoadPNGToGLTexture(std::string filePath, GLint sourceFormat, GLint format); } // end of Engine namespace
; A098600: a(n) = Fibonacci(n-1) + Fibonacci(n+1) - (-1)^n. ; 1,2,2,5,6,12,17,30,46,77,122,200,321,522,842,1365,2206,3572,5777,9350,15126,24477,39602,64080,103681,167762,271442,439205,710646,1149852,1860497,3010350,4870846,7881197,12752042,20633240,33385281,54018522,87403802,141422325,228826126,370248452,599074577,969323030,1568397606,2537720637,4106118242,6643838880,10749957121,17393796002,28143753122,45537549125,73681302246,119218851372,192900153617,312119004990,505019158606,817138163597,1322157322202,2139295485800,3461452808001,5600748293802,9062201101802,14662949395605,23725150497406,38388099893012,62113250390417,100501350283430,162614600673846,263115950957277,425730551631122,688846502588400,1114577054219521,1803423556807922,2918000611027442,4721424167835365,7639424778862806 cal $0,99926 ; Duplicate of A098600. mov $1,$0
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Wrapper classes for modeling an entire UAZBUS vehicle assembly // (including the vehicle itself, the powertrain, and the tires). // // ============================================================================= #include "chrono/ChConfig.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/wheeled_vehicle/driveline/ChShaftsDriveline4WD.h" #include "chrono_models/vehicle/kraz/Kraz.h" namespace chrono { namespace vehicle { namespace kraz { Kraz::Kraz() : m_system(nullptr), m_tractor(nullptr), m_trailer(nullptr), m_contactMethod(ChContactMethod::NSC), m_chassisCollisionType(CollisionType::NONE), m_fixed(false), m_tire_step_size(-1), m_initFwdVel(0), m_initPos(ChCoordsys<>(ChVector<>(0, 0, 1), QUNIT)), m_initOmega({0, 0, 0, 0}) {} Kraz::Kraz(ChSystem* system) : m_system(system), m_tractor(nullptr), m_trailer(nullptr), m_contactMethod(ChContactMethod::NSC), m_chassisCollisionType(CollisionType::NONE), m_fixed(false), m_tire_step_size(-1), m_initFwdVel(0), m_initPos(ChCoordsys<>(ChVector<>(0, 0, 1), QUNIT)), m_initOmega({0, 0, 0, 0}) {} Kraz::~Kraz() { delete m_tractor; delete m_trailer; } void Kraz::SetChassisVisualizationType(VisualizationType vis_tractor, VisualizationType vis_trailer) { m_tractor->SetChassisVisualizationType(vis_tractor); m_trailer->SetChassisVisualizationType(vis_trailer); } void Kraz::SetSuspensionVisualizationType(VisualizationType vis_tractor, VisualizationType vis_trailer) { m_tractor->SetSuspensionVisualizationType(vis_tractor); m_trailer->SetSuspensionVisualizationType(vis_trailer); } void Kraz::SetSteeringVisualizationType(VisualizationType vis) { m_tractor->SetSteeringVisualizationType(vis); } void Kraz::SetWheelVisualizationType(VisualizationType vis_tractor, VisualizationType vis_trailer) { m_tractor->SetWheelVisualizationType(vis_tractor); m_trailer->SetWheelVisualizationType(vis_trailer); } void Kraz::SetTireVisualizationType(VisualizationType vis_tractor, VisualizationType vis_trailer) { for (auto& axle : m_tractor->GetAxles()) { for (auto& wheel : axle->GetWheels()) { wheel->GetTire()->SetVisualizationType(vis_tractor); } for (auto& axle : m_trailer->GetAxles()) { for (auto& wheel : axle->GetWheels()) { wheel->GetTire()->SetVisualizationType(vis_trailer); } } } } void Kraz::Initialize() { // Create and initialize the tractor m_tractor = m_system ? new Kraz_tractor(m_system, m_fixed) : new Kraz_tractor(m_fixed, m_contactMethod); m_tractor->Initialize(m_initPos, m_initFwdVel); auto drvLine = std::static_pointer_cast<ChShaftsDriveline4WD>(m_tractor->GetDriveline()); drvLine->LockCentralDifferential(0, false); // Create and initialize the trailer m_trailer = new Kraz_trailer(m_system); m_trailer->Initialize(m_tractor->GetChassis()); // Create and initialize the powertrain system auto powertrain = chrono_types::make_shared<Kraz_tractor_Powertrain>("Powertrain"); m_tractor->InitializePowertrain(powertrain); // Create the tractor tires auto tire_FL = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_FL"); auto tire_FR = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_FR"); auto tire_RL1i = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_RL1i"); auto tire_RR1i = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_RR1i"); auto tire_RL1o = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_RL1o"); auto tire_RR1o = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_RR1o"); auto tire_RL2i = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_RL2i"); auto tire_RR2i = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_RR2i"); auto tire_RL2o = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_RL2o"); auto tire_RR2o = chrono_types::make_shared<Kraz_tractor_Tire>("TractorTire_RR2o"); m_tractor->InitializeTire(tire_FL, m_tractor->GetAxle(0)->m_wheels[0], VisualizationType::NONE); m_tractor->InitializeTire(tire_FR, m_tractor->GetAxle(0)->m_wheels[1], VisualizationType::NONE); m_tractor->InitializeTire(tire_RL1i, m_tractor->GetAxle(1)->m_wheels[0], VisualizationType::NONE); m_tractor->InitializeTire(tire_RR1i, m_tractor->GetAxle(1)->m_wheels[1], VisualizationType::NONE); m_tractor->InitializeTire(tire_RL1o, m_tractor->GetAxle(1)->m_wheels[2], VisualizationType::NONE); m_tractor->InitializeTire(tire_RR1o, m_tractor->GetAxle(1)->m_wheels[3], VisualizationType::NONE); m_tractor->InitializeTire(tire_RL2i, m_tractor->GetAxle(2)->m_wheels[0], VisualizationType::NONE); m_tractor->InitializeTire(tire_RR2i, m_tractor->GetAxle(2)->m_wheels[1], VisualizationType::NONE); m_tractor->InitializeTire(tire_RL2o, m_tractor->GetAxle(2)->m_wheels[2], VisualizationType::NONE); m_tractor->InitializeTire(tire_RR2o, m_tractor->GetAxle(2)->m_wheels[3], VisualizationType::NONE); // Create the trailer tires auto tr_tire_FL = chrono_types::make_shared<Kraz_trailer_Tire>("FL"); auto tr_tire_FR = chrono_types::make_shared<Kraz_trailer_Tire>("FR"); auto tr_tire_ML = chrono_types::make_shared<Kraz_trailer_Tire>("ML"); auto tr_tire_MR = chrono_types::make_shared<Kraz_trailer_Tire>("MR"); auto tr_tire_RL = chrono_types::make_shared<Kraz_trailer_Tire>("RL"); auto tr_tire_RR = chrono_types::make_shared<Kraz_trailer_Tire>("RR"); m_trailer->InitializeTire(tr_tire_FL, m_trailer->GetAxle(0)->m_wheels[0], VisualizationType::NONE); m_trailer->InitializeTire(tr_tire_FR, m_trailer->GetAxle(0)->m_wheels[1], VisualizationType::NONE); m_trailer->InitializeTire(tr_tire_ML, m_trailer->GetAxle(1)->m_wheels[0], VisualizationType::NONE); m_trailer->InitializeTire(tr_tire_MR, m_trailer->GetAxle(1)->m_wheels[1], VisualizationType::NONE); m_trailer->InitializeTire(tr_tire_RL, m_trailer->GetAxle(2)->m_wheels[0], VisualizationType::NONE); m_trailer->InitializeTire(tr_tire_RR, m_trailer->GetAxle(2)->m_wheels[1], VisualizationType::NONE); for (auto& axle : m_tractor->GetAxles()) { for (auto& wheel : axle->GetWheels()) { if (m_tire_step_size > 0) wheel->GetTire()->SetStepsize(m_tire_step_size); } } for (auto& axle : m_trailer->GetAxles()) { for (auto& wheel : axle->GetWheels()) { if (m_tire_step_size > 0) wheel->GetTire()->SetStepsize(m_tire_step_size); } } } void Kraz::Synchronize(double time, const ChDriver::Inputs& driver_inputs, const ChTerrain& terrain) { m_tractor->Synchronize(time, driver_inputs, terrain); m_trailer->Synchronize(time, driver_inputs.m_braking, terrain); } void Kraz::Advance(double step) { m_tractor->Advance(step); m_trailer->Advance(step); } } // end namespace kraz } // end namespace vehicle } // end namespace chrono
; A076389: Sum of squares of numbers that cannot be written as t*n + u*(n+1) for nonnegative integers t,u. ; 0,1,30,220,950,3045,8036,18480,38340,73425,131890,224796,366730,576485,877800,1300160,1879656,2659905,3693030,5040700,6775230,8980741,11754380,15207600,19467500,24678225,31002426,38622780,47743570 mov $2,$0 bin $0,2 mov $1,$2 mul $1,2 add $1,$0 add $0,$1 mul $0,2 mul $1,$0 add $1,$0 sub $0,2 mul $1,$0 div $1,24
; A165758: a(n) = (12-7*6^n)/5. ; 1,-6,-48,-300,-1812,-10884,-65316,-391908,-2351460,-14108772,-84652644,-507915876,-3047495268,-18284971620,-109709829732,-658258978404,-3949553870436,-23697323222628,-142183939335780,-853103636014692,-5118621816088164 mov $2,6 pow $2,$0 sub $1,$2 div $1,5 mul $1,7 add $1,1
//----------------------------------*-C++-*----------------------------------// /** * @file WGDiffusionLossOperator.hh * @brief WGDiffusionLossOperator class definition * @note Copyright(C) 2012-2013 Jeremy Roberts */ //---------------------------------------------------------------------------// #ifndef detran_WGDIFFUSIONLOSSOPERATOR_HH_ #define detran_WGDIFFUSIONLOSSOPERATOR_HH_ #include "material/Material.hh" #include "geometry/Mesh.hh" #include "utilities/InputDB.hh" #include "utilities/SP.hh" #include "callow/matrix/Matrix.hh" namespace detran { /** * @class WGDiffusionLossOperator.hh * @brief Loss operator for a one group diffusion equation. * * This operator can be used for group sweeping in multigroup * Krylov diffusion solvers. Additionally, it can be used * to precondition within-group transport solves. * * The one group diffusion equation is * \f[ * -\nabla D(\vec{r}) \nabla \phi(\vec{r}) * + \Sigma_r(\vec{r}) \phi(\vec{r}) = Q(\vec{r}) * \f] * where the loss operator is defined * \f[ * \mathbf{M}[\cdot] \equiv (-\nabla D(\vec{r}) \nabla * + \Sigma_r(\vec{r}))[\cdot]\, . * \f] * * A mesh-centered discretization is used. */ class WGDiffusionLossOperator: public callow::Matrix { public: //-------------------------------------------------------------------------// // TYPEDEFS //-------------------------------------------------------------------------// typedef callow::Matrix Base; typedef callow::MatrixBase::SP_matrix SP_matrix; typedef detran_utilities::SP<WGDiffusionLossOperator> SP_operator; typedef detran_utilities::InputDB::SP_input SP_input; typedef detran_material::Material::SP_material SP_material; typedef detran_geometry::Mesh::SP_mesh SP_mesh; typedef detran_geometry::Mesh Mesh; typedef detran_utilities::vec_int vec_int; typedef detran_utilities::vec_dbl vec_dbl; typedef detran_utilities::vec2_dbl vec2_dbl; typedef detran_utilities::size_t size_t; //-------------------------------------------------------------------------// // CONSTRUCTOR & DESTRUCTOR //-------------------------------------------------------------------------// /** * @brief Constructor * @param input Pointer to input parameters * @param material Pointer to materials * @param mesh Pointer to mesh * @param group Group of operator */ WGDiffusionLossOperator(SP_input input, SP_material material, SP_mesh mesh, size_t group); //---------------------------------------------------------------------------// // PUBLIC FUNCTIONS //---------------------------------------------------------------------------// /// Rebuild the matrix based on the present material definitions. void construct(); private: //---------------------------------------------------------------------------// // DATA //---------------------------------------------------------------------------// /// Input SP_input d_input; /// Material SP_material d_material; /// Mesh SP_mesh d_mesh; /// Group of this operator size_t d_group; /// Problem dimension size_t d_dimension; /// Boundary albedo vec_dbl d_albedo; //---------------------------------------------------------------------------// // IMPLEMENTATION //---------------------------------------------------------------------------// // All matrix operator need this. Here, we have the client call construct. void build(); }; } // end namespace detran #endif // detran_WGDIFFUSIONLOSSOPERATOR_HH_ //---------------------------------------------------------------------------// // end of file WGDiffusionLossOperator.hh //---------------------------------------------------------------------------//
%ifdef CONFIG { "RegData": { "MM0": ["0x6162414263644344", "0x0"], "MM1": ["0x6162414263644344", "0x0"], "MM2": ["0x6162636465666768", "0x0"] }, "MemoryRegions": { "0x100000000": "4096" } } %endif mov rdx, 0xe0000000 mov rax, 0x4142434445464748 mov [rdx + 8 * 0], rax mov rax, 0x5152535455565758 mov [rdx + 8 * 1], rax mov rax, 0x6162636465666768 mov [rdx + 8 * 2], rax mov rax, 0x7172737475767778 mov [rdx + 8 * 3], rax movq mm0, [rdx] punpckhwd mm0, [rdx + 8 * 2] movq mm1, [rdx] movq mm2, [rdx + 8 * 2] punpckhwd mm1, mm2 hlt
; A071122: a(n) = a(n-1) + sum of decimal digits of 2^n. ; 2,6,14,21,26,36,47,60,68,75,89,108,128,150,176,201,215,234,263,294,320,345,386,423,452,492,527,570,611,648,695,753,815,876,935,999,1055,1122,1193,1254,1304,1350,1406,1464,1526,1596,1664,1737,1802,1878,1958 mov $9,$0 mov $11,$0 add $11,1 lpb $11,1 clr $0,9 mov $0,$9 sub $11,1 sub $0,$11 mov $5,$0 mov $0,2 add $5,1 pow $0,$5 add $2,1 sub $0,$2 mov $5,6 lpb $0,1 mov $2,$0 div $0,10 mod $2,10 mov $7,$5 add $7,$2 mov $5,$7 lpe add $5,3 mov $1,$5 sub $1,8 add $10,$1 lpe mov $1,$10
; Z88 Small C+ Run Time Library ; Long functions ; PUBLIC l_long_neg ; deHL = -deHL .l_long_neg ld a,l cpl ld l,a ld a,h cpl ld h,a ld a,e cpl ld e,a ld a,d cpl ld d,a inc l ret nz inc h ret nz inc de ret ; call l_long_com ; inc hl ; ld a,h ; or l ; ret nz ; inc de ; ret
// // GenerateModelsFromLabels // Usage: GenerateModelsFromLabels InputVolume Startlabel Endlabel // where // InputVolume is a meta file containing a 3 volume of // discrete labels. // StartLabel is the first label to be processed // EndLabel is the last label to be processed // NOTE: There can be gaps in the labeling. If a label does // not exist in the volume, it will be skipped. // // #include <vtkGeometryFilter.h> #include <vtkImageAccumulate.h> #include <vtkMaskFields.h> #include <vtkMetaImageReader.h> #include <vtkNew.h> #include <vtkThreshold.h> #include <vtkVersion.h> #include <vtkWindowedSincPolyDataFilter.h> #include <vtkXMLPolyDataWriter.h> // vtkDiscreteFlyingEdges3D was introduced in VTK >= 8.2 #if VTK_MAJOR_VERSION >= 9 || (VTK_MAJOR_VERSION >= 8 && VTK_MINOR_VERSION >= 2) #define USE_FLYING_EDGES #else #undef USE_FLYING_EDGES #endif //#undef USE_FLYING_EDGES #ifdef USE_FLYING_EDGES #include <vtkDiscreteFlyingEdges3D.h> #else #include <vtkDiscreteMarchingCubes.h> #endif #include <sstream> #include <vtkImageData.h> #include <vtkPointData.h> #include <vtkUnstructuredGrid.h> int main(int argc, char* argv[]) { if (argc < 4) { std::cout << "Usage: " << argv[0] << " InputVolume StartLabel EndLabel e.g. Frog/frogtissue.mhd 1 29" << std::endl; return EXIT_FAILURE; } // Create all of the classes we will need vtkNew<vtkMetaImageReader> reader; vtkNew<vtkImageAccumulate> histogram; #ifdef USE_FLYING_EDGES vtkNew<vtkDiscreteFlyingEdges3D> discreteCubes; #else vtkNew<vtkDiscreteMarchingCubes> discreteCubes; #endif vtkNew<vtkWindowedSincPolyDataFilter> smoother; vtkNew<vtkThreshold> selector; vtkNew<vtkMaskFields> scalarsOff; vtkNew<vtkGeometryFilter> geometry; vtkNew<vtkXMLPolyDataWriter> writer; // Define all of the variables unsigned int startLabel = atoi(argv[2]); unsigned int endLabel = atoi(argv[3]); std::string filePrefix = "Label"; unsigned int smoothingIterations = 15; double passBand = 0.001; double featureAngle = 120.0; // Generate models from labels // 1) Read the meta file // 2) Generate a histogram of the labels // 3) Generate models from the labeled volume // 4) Smooth the models // 5) Output each model into a separate file reader->SetFileName(argv[1]); histogram->SetInputConnection(reader->GetOutputPort()); histogram->SetComponentExtent(0, endLabel, 0, 0, 0, 0); histogram->SetComponentOrigin(0, 0, 0); histogram->SetComponentSpacing(1, 1, 1); histogram->Update(); discreteCubes->SetInputConnection(reader->GetOutputPort()); discreteCubes->GenerateValues(endLabel - startLabel + 1, startLabel, endLabel); smoother->SetInputConnection(discreteCubes->GetOutputPort()); smoother->SetNumberOfIterations(smoothingIterations); smoother->BoundarySmoothingOff(); smoother->FeatureEdgeSmoothingOff(); smoother->SetFeatureAngle(featureAngle); smoother->SetPassBand(passBand); smoother->NonManifoldSmoothingOn(); smoother->NormalizeCoordinatesOn(); smoother->Update(); selector->SetInputConnection(smoother->GetOutputPort()); #ifdef USE_FLYING_EDGES selector->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); #else selector->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, vtkDataSetAttributes::SCALARS); #endif // Strip the scalars from the output scalarsOff->SetInputConnection(selector->GetOutputPort()); scalarsOff->CopyAttributeOff(vtkMaskFields::POINT_DATA, vtkDataSetAttributes::SCALARS); scalarsOff->CopyAttributeOff(vtkMaskFields::CELL_DATA, vtkDataSetAttributes::SCALARS); geometry->SetInputConnection(scalarsOff->GetOutputPort()); writer->SetInputConnection(geometry->GetOutputPort()); for (unsigned int i = startLabel; i <= endLabel; i++) { // see if the label exists, if not skip it double frequency = histogram->GetOutput()->GetPointData()->GetScalars()->GetTuple1(i); if (frequency == 0.0) { continue; } // select the cells for a given label selector->ThresholdBetween(i, i); // output the polydata std::stringstream ss; ss << filePrefix << i << ".vtp"; std::cout << argv[0] << " writing " << ss.str() << std::endl; writer->SetFileName(ss.str().c_str()); writer->Write(); } return EXIT_SUCCESS; }
; A085037: Smallest square divisible by the n-th triangular number (n(n+1)/2). ; 1,9,36,100,225,441,196,36,225,3025,4356,6084,8281,11025,3600,4624,2601,3249,36100,44100,53361,64009,19044,900,4225,13689,15876,164836,189225,216225,15376,17424,314721,354025,44100,49284,494209,549081,152100,168100,741321,815409,894916,108900,119025,1168561,318096,7056,1225,65025,1758276,1898884,227529,245025,592900,636804,2732409,2927521,3132900,3348900,3575881,423801,28224,270400,4601025,4888521,5189284,5503716,5832225,6175225,181476,191844,7295401,308025,324900,8561476,9018009,9492561,2496400,32400,136161,11580409,12152196,12744900,13359025,13995081,3663396,3833764,1782225,1863225,17522596,18301284,19105641,19936225,1299600,1354896,461041,53361,108900,1020100 seq $0,96 ; a(n) = n*(n+3)/2. seq $0,53143 ; Smallest square divisible by n.
scoreboard: ; db " " db "X: O: " db 0
; char* strset(char *s, int c) SECTION code_string PUBLIC _strset EXTERN asm_strset _strset: pop af pop hl pop de push de push hl push af jp asm_strset
; A121636: Number of 2-cell columns starting at level 0 in all of deco polyominoes of height n. A deco polyomino is a directed column-convex polyomino in which the height, measured along the diagonal, is attained only in the last column. ; Submitted by Jon Maiga ; 0,1,5,23,122,754,5364,43308,391824,3929616,43287840,519711840,6755460480,94527008640,1416783432960,22646604153600,384576130713600,6914404440115200,131217341055897600,2621176954176614400 mov $1,1 mov $2,1 mov $3,$0 lpb $3 mul $1,$0 cmp $0,1 add $1,$2 mul $2,$3 add $1,$2 sub $3,1 max $3,1 add $0,$3 lpe mul $1,$0 mov $0,$1
; A076453: a(n+2) = abs(a(n+1)) - a(n), a(0)=1, a(1)=0. ; Submitted by Jamie Morken(s3) ; 1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1,0,-1,1,2,1,-1,0,1,1 mov $1,1 mov $2,1 lpb $0 sub $0,1 mov $3,$2 mov $2,$1 pow $1,2 dif $1,2 sub $1,$3 lpe mov $0,$1
; $Id: bit_fx3_mwr.asm,v 1.3 2016-04-23 21:06:32 dom Exp $ ; ; 1 bit sound library - version for "memory write" I/O architectures ; sound effects module. ; Alternate sound library by Stefano Bodrato ; SECTION code_clib PUBLIC bit_fx3 PUBLIC _bit_fx3 INCLUDE "games/games.inc" EXTERN bit_open EXTERN bit_open_di EXTERN bit_close EXTERN bit_close_ei .bit_fx3 ._bit_fx3 pop bc pop de push de push bc ld a,e cp 8 ret nc add a,a ld e,a ld d,0 ld hl,table add hl,de ld a,(hl) inc hl ld h,(hl) ld l,a jp (hl) .table defw blirp2 ; effect #0 defw blirp defw coff ; effect #2 defw blurp defw descending defw ascending defw descending2 defw fx7 ; effect #7 .blirp call bit_open_di ld b,255 .expl push af ld a,sndbit_mask ld h,0 ld l,b and (hl) ld l,a pop af xor l ld (sndbit_port),a push bc .dly nop djnz dly pop bc push af ld a,sndbit_mask ld h,0 ld l,b and (hl) ld l,a pop af xor l ld (sndbit_port),a push bc push af ld a,255 sub b ld b,a pop af .dly2 nop djnz dly2 pop bc djnz expl call bit_close_ei ret .blirp2 call bit_open_di ld b,100 .blrp push af ld a,sndbit_mask ld h,0 ld l,b and (hl) ld l,a pop af xor l ld (sndbit_port),a push bc push af ld a,255 sub b ld b,a pop af .dlyb nop djnz dlyb pop bc xor sndbit_mask ld (sndbit_port),a push bc .dlya nop djnz dlya pop bc djnz blrp call bit_close_ei ret ; Steam engine .coff call bit_open_di ld hl,0 .coff2 push af ld a,sndbit_mask and (hl) ld b,a pop af xor b ld (sndbit_port),a ld b,(hl) .cdly djnz cdly inc hl bit 7,l jr z,coff2 call bit_close_ei ret .blurp call bit_open_di ld b,255 .blurp2 push af ld a,sndbit_mask ld h,0 ld l,b and (hl) ld l,a pop af xor l ld (sndbit_port),a push af ld a,(hl) .dblurp dec a jr nz,dblurp pop af djnz blurp2 call bit_close_ei ret ; descending buzzing noise .descending call bit_open_di ld hl,1000 .desc1 push hl ld b,16 .desc2 rl l rl h jr nc,desc3 xor sndbit_mask ld (sndbit_port),a .desc3 ld e,5 .desc4 dec e jr nz,desc4 djnz desc2 pop hl dec hl ld c,a ld a,h or l ld a,c jr nz,desc1 call bit_close_ei ret ; ascending buzzing noise .ascending call bit_open_di ld hl,1023 .hdesc1 push hl ld b,16 .hdesc2 rl l rl h jr nc,hdesc3 xor sndbit_mask ld (sndbit_port),a .hdesc3 djnz hdesc2 pop hl dec hl ld c,a ld a,h or l ld a,c jr nz,hdesc1 call bit_close_ei ret ; descending buzzing noise #2 .descending2 call bit_open_di ld hl,1023 .asc1 push hl ld b,16 .asc2 rl l rl h jr c,asc3 xor sndbit_mask ld (sndbit_port),a .asc3 djnz asc2 pop hl dec hl ld c,a ld a,h or l ld a,c jr nz,asc1 call bit_close_ei ret ; noise #7 .fx7 call bit_open_di ld hl,4000 .fx71 push hl push af ld a,sndbit_mask and l ld l,a pop af xor l ld (sndbit_port),a pop hl dec hl ld c,a ld a,h or l ld a,c jr nz,fx71 call bit_close_ei ret
COMMENT @---------------------------------------------------------------------- Copyright (c) GeoWorks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: Cards library FILE: hand.asm REVISION HISTORY: Name Date Description ---- ---- ----------- Jon 6/90 Initial Version DESCRIPTION: This file contains handlers for HandClass. RCS STAMP: $Id: hand.asm,v 1.1 97/04/04 17:44:24 newdeal Exp $ ------------------------------------------------------------------------------@ CardsClassStructures segment resource HandClass CardsClassStructures ends ;--------------------------------------------------- CardsCodeResource segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandDraw %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_VIS_DRAW handler for HandClass CALLED BY: PASS: bp = gstate CHANGES: RETURN: nothing DESTROYED: ax, bx, cx, dx, di PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandDraw method HandClass, MSG_VIS_DRAW ; ; ; First see whether or not we have any cards ; tst ds:[di].DI_nCards jz drawSelf ; ; If we DO have cards, we want to draw the top one ; push bp mov ax, MSG_VIS_DRAW call VisCallFirstChild pop bp ;restore gstate mov di,bp ;di <- gstate mov si, PCT_NULL ;clear clip rect jmp endHandDraw drawSelf: ; ; If we have no cards, we draw our marker ; mov ax, MSG_DECK_DRAW_MARKER call ObjCallInstanceNoLock endHandDraw: ret HandDraw endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandStartSelect %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_META_START_SELECT handler for HandClass Informs the game object that the hand has been selected. CALLED BY: PASS: nothing CHANGES: RETURN: nothing DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandSelect method HandClass, MSG_META_START_SELECT, MSG_META_START_MOVE_COPY mov ax, MSG_GAME_HAND_SELECTED call VisCallParent mov ax, mask MRF_PROCESSED ret HandSelect endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandPushCard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_DECK_PUSH_CARD handler for HandClass Adds card into first position of hand's child tree CALLED BY: PASS: ^lcx:dx = OD of card to push CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: sets card to full size turns it face down adds it KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandPushCard method HandClass, MSG_DECK_PUSH_CARD ; ; Add the card to the hand's composite ; mov ax, MSG_DECK_ADD_CARD_FIRST call ObjCallInstanceNoLock ; ; Make sure it is full sized ; mov bx, cx mov si, dx mov ax, MSG_CARD_MAXIMIZE mov di, mask MF_FIXUP_DS call ObjMessage ; ; Make sure it is face down ; mov ax, MSG_CARD_TURN_FACE_DOWN mov di, mask MF_FIXUP_DS call ObjMessage ret HandPushCard endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandPtr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_META_PTR handler for HandClass There should be no action taken when the hand receives a MSG_META_PTR, so we must subclass the method with a "null" handler. CALLED BY: PASS: nothing CHANGES: nothing RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: nothing KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandPtr method HandClass, MSG_META_PTR mov ax, mask MRF_PROCESSED ret HandPtr endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandEndSelect %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_META_END_SELECT handler for HandClass There should be no action taken when the hand receives a MSG_META_END_SELECT, so we must subclass the method with a "null" handler. CALLED BY: PASS: nothing CHANGES: nothing RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: nothing KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandEndSelect method HandClass, MSG_META_END_SELECT mov ax, mask MRF_PROCESSED ret HandEndSelect endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandMakeFullHand %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_HAND_MAKE_FULL_HAND handler for HandClass Creates and adds a full set of 52 cards to the hand's composite. CALLED BY: PlayingTableInitialize PASS: nothing CHANGES: instantiates a full deck of cards and adds them as children RETURN: nothing DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: cycles through each rank and suit, instantiating cards and pushing them on as children KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandMakeFullHand method HandClass, MSG_HAND_MAKE_FULL_HAND mov dh, CR_ACE ;dh <- initial rank clr dl startLoop: push si ;save hand offset push dx ;save card rank & suit ; ; Instantiate a new card ; mov di, segment CardClass mov es, di mov di, offset CardClass mov bx, ds:[LMBH_handle] call ObjInstantiate ; ; Set up some attributes for our new baby ; pop dx ;dx <- card rank & suit push dx mov cl, offset CA_RANK shl dh, cl mov cl, offset CA_SUIT shl dl, cl ORNF dl, dh clr dh ;dx is now in the ;format of CardAttrs mov bp, dx ;bp <- card attrs ; ; Set the cards attributes ; mov ax, MSG_CARD_SET_ATTRIBUTES call ObjCallInstanceNoLock pop bp ;restore card rank&suit mov cx, ds:[LMBH_handle] pop dx ;restore hand offset xchg dx, si ;dx <- card offset, ;si <- hand offset push bp ;save card rank & suit mov ax, MSG_DECK_PUSH_CARD call ObjCallInstanceNoLock pop dx ;restore card rank&suit cmp dh, CR_KING ;is it a king? je incrementSuit ;if so, time for a ;new suit inc dh ;otherwise, inc rank jmp startLoop incrementSuit: cmp dl, CS_SPADES ;is it a spade? je endLoop ;if so, we're done inc dl ;otherwise inc rank mov dh, CR_ACE ;start over with ace jmp startLoop endLoop: ret HandMakeFullHand endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandShuffle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_HAND_SHUFFLE handler for HandClass Shuffles the hand's cards CALLED BY: PASS: nothing CHANGES: RETURN: nothing DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: for (i = 0; i <= number of children; i++){ j = random number between 0 and # of children swap attributes of card i and card j } KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandShuffle method HandClass, MSG_HAND_SHUFFLE mov dx, ds:[di].DI_nCards dec dx ;dx <- # of last card clr bp ;bp <- # of first child startLoop: cmp bp, dx ;done yet? jg endLoop push dx ;save # of children push bp ;save index mov ax, MSG_GAME_RANDOM call VisCallParent pop cx ;cx <- index push cx mov ax, MSG_HAND_EXCHANGE_CHILDREN ;swap attributes of call ObjCallInstanceNoLock ;card cx and card dx pop bp ;restore index inc bp ;inc index pop dx ;restore # of children jmp startLoop endLoop: ret HandShuffle endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandExchangeChildren %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_HAND_EXCHANGE_CHILDREN handler for HandClass CALLED BY: HandShuffle PASS: cx, dx = children to swap attributes CHANGES: card A gets card B's attributes, and card B gets card A's attributes RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: find card B get card B's attributes find card A get card A's attributes set card A's attributes set card B's attributes KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandExchangeChildren method HandClass, MSG_HAND_EXCHANGE_CHILDREN push cx ;save #A clr cx ;cx:dx = #B mov ax, MSG_VIS_FIND_CHILD call ObjCallInstanceNoLock pop di ;get #A off stack push cx,dx ;save OD of B push di ;put #A back on stack CallObjectCXDX MSG_CARD_GET_ATTRIBUTES, MF_CALL ;get B's attributes pop dx ;restore #A push bp ;save B's attrs clr cx ;cx:dx = #A mov ax, MSG_VIS_FIND_CHILD call ObjCallInstanceNoLock push cx,dx ;save OD of A CallObjectCXDX MSG_CARD_GET_ATTRIBUTES, MF_CALL ;bp <- A's attrs pop cx,dx ;restore OD of A pop ax ;restore B's attrs push bp ;save A's attrs mov bp, ax ;bp <- B's attrs CallObjectCXDX MSG_CARD_SET_ATTRIBUTES, MF_FIXUP_DS ;A <- B's attrs pop bp ;restore A's attrs pop cx,dx ;restore B's OD CallObjectCXDX MSG_CARD_SET_ATTRIBUTES, MF_FIXUP_DS ;B <- A's attrs ret HandExchangeChildren endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandGetRidOfCards %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_DECK_GET_RID_OF_CARDS handler for HandClass This method is basically here so that decks can give all their cards to the hand object; since the hand already has its own cards, there is nothing to do. CALLED BY: PASS: nothing CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandGetRidOfCards method HandClass, MSG_DECK_GET_RID_OF_CARDS ret HandGetRidOfCards endm CardsCodeResource ends
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r14 push %r9 push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0x9247, %rsi lea addresses_A_ht+0x74bf, %rdi clflush (%rsi) sub %r14, %r14 mov $53, %rcx rep movsl nop dec %r13 lea addresses_UC_ht+0x122bf, %r11 nop nop nop inc %r9 movups (%r11), %xmm3 vpextrq $1, %xmm3, %rdi nop cmp %r13, %r13 lea addresses_UC_ht+0x182cf, %rsi lea addresses_WT_ht+0x118cb, %rdi nop nop nop nop cmp %rdx, %rdx mov $111, %rcx rep movsq nop nop nop xor %rsi, %rsi lea addresses_normal_ht+0x76bf, %rcx clflush (%rcx) nop nop add $676, %rdi movups (%rcx), %xmm5 vpextrq $0, %xmm5, %r9 xor $14335, %r11 pop %rsi pop %rdx pop %rdi pop %rcx pop %r9 pop %r14 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r14 push %r15 push %rbp push %rcx push %rsi // Load lea addresses_A+0x1653f, %rbp inc %r15 vmovups (%rbp), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $0, %xmm7, %r11 // Exception!!! nop nop mov (0), %rbp nop and %rbp, %rbp // Store lea addresses_D+0xd6bf, %rcx nop nop nop inc %r14 mov $0x5152535455565758, %rsi movq %rsi, %xmm4 movups %xmm4, (%rcx) nop nop nop nop nop cmp $38440, %rbp // Faulty Load lea addresses_D+0xd6bf, %rbp nop nop nop nop nop cmp %r13, %r13 mov (%rbp), %r11d lea oracles, %r13 and $0xff, %r11 shlq $12, %r11 mov (%r13,%r11,1), %r11 pop %rsi pop %rcx pop %rbp pop %r15 pop %r14 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'same': True, 'size': 32, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A', 'same': False, 'size': 32, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_D', 'same': True, 'size': 4, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 16, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 16, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'58': 21829} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
############################################################################## # Program : MindReader Programmer: Chaoran Li, Jiaer JIang, Xue Cheng, Pengfei Tong # Due Date: 12/05/19 Last Modified:11/08/19 # Course: CS3340 Section:501 ############################################################################# # Description: # # Topic: # The topic for the team project this semester is the Mind Reader game. # For a feel of the game visit # https://www.mathsisfun.com/games/mind-reader.html # # Minimum requirements for the program: # The game is for a human player and your program is the 'mind reader'. Your program must display the # cards, get input from the player then correctly display the number that the player has in mind. # At the end of a game, the program will ask the player if he/she wants to play another game and then # repeat or end the program. # The 'cards' MUST be generated and displayed once at a time during a game, i.e. NOT pre-calculated # and stored in memory. The order of displayed cards MUST be random. # The player input (keystrokes) should be minimum # The ASCII based display is the minimum requirement. Creative ways to display the game (e.g. colors) # will earn the team extra credits. # If the player gives an invalid input, an error message is displayed to explain why the input was not valid. # # Extra credits will be given for: # Graphic/color display # Extra features of the programs (e.g. background music, sounds or music to indicate invalid input, # pleasant display etc...) implemented and documented. # Any other notable creativity that the team has shown. # You must document these extra credit features in your report and explain well to unlock these extra # credits. # # Design: # Print: Two loop to traverse to print # Calculate: Get higher unit first. Return 0 if out of range. # # Log: # version 1.0 10/04/19 Design the interaction flow # version 1.1 10/05/19 Print card and calculate result # version 1.2 10/09/19 If think about number out of 1~63, return 0 # version 1.3 11/08/19 Imply shuffle function # version 1.4 12/02/19 Add functions about Bitmaps # version 1.5 12/02/19 Final improvement about music and flow path. # ############################################################################# # Register: # global # $v0 for I/O # $a0 for I/O # $a1 for I/O # $s0 'y' # $s1 'n' # $s2 max digit # $s3 line feed every x numbers # $s4 random factor: a random number to decide current digit for card is 0 or 1 # #s5 card length # $t0 digit left, show result when $t0 is 0 # $t1 result # $t2 input, 1 for y and 0 for n # $t3 current digit # $t4 valid random sequence (last digit) # $t8 tmp1 # $t9 tmp2 # # Truth table: current digit(card) answer value result of xor final binary expansion add to result # 0 0(n) 0 1 1 # 0 1(y) 1 0 0 # 1 0(n) 1 0 0 # 1 1(y) 0 1 1 # if (xor = 0) add to result # ############################################################################# .data sequence: .space 24 # digit sequence card: .space 128 # at most # messages start: .asciiz "\nThink of a number between 1 and 63. Six cards will be displayed and you would tell\nme whether your number is in the card. Once you finish all six cards, I can read your\nmind. Start now?" hint: .asciiz "\n(input 'y' or 'n'):\n" question: .asciiz "\nDo you find your number here?" unvalid: .asciiz "\nThe only valid answer is 'y' or 'n' (lower case). So input correctly.\n" answer: .asciiz "\nYour number is " again: .asciiz ". Awesome right?\nDo you wanna another try?" overflow: .asciiz "\nYou are so cute! I think your number is not in 1 and 63" end: .asciiz "\nGame over. GLHF!" pictStart: .asciiz "Resource/P01.png" pictStart2: .asciiz "Resource/P02.png" pictCard1: .asciiz "Resource/P03.png" pictCard2: .asciiz "Resource/P04.png" pictCard3: .asciiz "Resource/P05.png" pictCard4: .asciiz "Resource/P06.png" pictCard5: .asciiz "Resource/P07.png" pictCard6: .asciiz "Resource/P08.png" pictAnsw: .asciiz "Resource/P09.png" pictOverf: .asciiz "Resource/P10.png" pictEnd: .asciiz "Resource/P11.png" musicStt: .asciiz "Resource/MusicStart.txt" musicEnd: .asciiz "Resource/MusicEnd.txt" buff: .asciiz " " numOfNotesBuff: .ascii " "#right now it has lenght of 3 b/c thats how many characters in the syscall in readNumNotes has. numOfNotes:.word 0 ############################################################################# .text .globl main # init main: li $s0, 0x79 # save character 'y' li $s1, 0x6e # save character 'n' li $s2, 6 # 6 digits binary for 0 ~ 63 li $s3, 8 # feed back every 8 numbers when print card li $s5, 1 # set card length sllv $s5, $s5, $s2 # << 6 srl $s5, $s5, 1 # half of 2^6 # init sequence ( a shuffled sequence to ask question) li $t8, 1 # start with 000001 move $t9, $s2 # index = max digit sll $t9, $t9, 2 # index -> address initSeq: beq $t9, $zero, restart # break addi $t9, $t9, -4 # address -= 4 sw $t8, sequence($t9) # save to sequence[index] sll $t8, $t8, 1 # <<1 j initSeq restart: li $a1, 64 # random range [0, 64) li $v0, 42 syscall move $s4, $a0 # random factor: a random 6-bit 0/1 sequence addi $sp, $sp, -8 # save $s0-s1 sw $s0, 0($sp) sw $s1, 4($sp) la $s0, sequence move $s1, $s2 jal shuffle # shuffle sequence (length = 6 (* 4)) lw $s0, 0($sp) lw $s1, 4($sp) addi $sp, $sp, 8 # restore addi $sp, $sp, -4 sw $ra, 0($sp) jal drawStart lw $ra, 0($sp) addi $sp, $sp, 4 li $v0, 4 # print message start la $a0, start # load address syscall li $v0, 4 # print message hint la $a0, hint syscall jal input # get an input beq $t2, $zero, exit # input, 1 for y and 0 for n li $t1, 0 # set result to 0 move $t0, $s2 # digits left # main loop: print card and ask question loop: beq $t0, $zero, show # if 0 digit left, show reslut. Get highter digit first for similicity sll $t8, $t0, 2 addi $t8, $t8, -4 # index -> address lw $t3, sequence($t8) # current digit = sequence[index] move $t4, $s4 srl $s4, $s4, 1 # random sequence >> andi $t4, $t4, 1 # get valid random sequence (lasr digit) # card background addi $sp, $sp, -12 # save variable sw $t0, 0($sp) sw $t1, 4($sp) sw $t2, 8($sp) beq $t0, 1, card6 beq $t0, 2, card5 beq $t0, 3, card4 beq $t0, 4, card3 beq $t0, 5, card2 card1: la $t0, pictCard1 j cardEntr card2: la $t0, pictCard2 j cardEntr card3: la $t0, pictCard3 j cardEntr card4: la $t0, pictCard4 j cardEntr card5: la $t0, pictCard5 j cardEntr card6: la $t0, pictCard6 cardEntr: li $t1, 0 li $t2, 0 jal makeDot lw $t0, 0($sp) lw $t1, 4($sp) lw $t2, 8($sp) addi $sp, $sp, 12 # restore variable # write card addi $sp, $sp, -8 # save $s0-s1 sw $s0, 0($sp) sw $s1, 4($sp) move $s0, $t3 move $s1, $t4 jal wCard # write card lw $s0, 0($sp) lw $s1, 4($sp) addi $sp, $sp, 8 # restore # shuffle card addi $sp, $sp, -8 # save $s0-s1 sw $s0, 0($sp) sw $s1, 4($sp) # $s2 is same and const in Callee la $s0, card move $s1, $s5 # length -> address jal shuffle # shuffle card (length = 2^6/2 (* 4) = 2^7) lw $s0, 0($sp) lw $s1, 4($sp) addi $sp, $sp, 8 # restore # print card addi $sp, $sp, -12 # save $s0-s2 sw $s0, 0($sp) sw $s1, 4($sp) sw $s2, 8($sp) la $s0, card move $s1, $s5 # length move $s2, $s3 # feed back value jal pCard # print card lw $s0, 0($sp) lw $s1, 4($sp) lw $s2, 8($sp) addi $sp, $sp, 12 # restore li $v0, 4 # print question la $a0, question syscall li $v0, 4 # print hint la $a0, hint syscall # get result from input jal input # get an input xor $t2, $t2, $t4 # xor bne $t2, $zero, skipAdd # != 0 skip add add $t1, $t1, $t3 # result += input skipAdd: addi $t0, $t0, -1 # digit left-- j loop show: beq $t1, $zero, overF # if answer is 0, overflow addi $sp, $sp, -4 sw $ra, 0($sp) jal drawAnsw lw $ra, 0($sp) addi $sp, $sp, 4 li $v0, 4 # print answer la $a0, answer syscall li $v0, 1 # print result addi $a0, $t1, 0 # set $a0 to result syscall addi $sp, $sp, -8 sw $ra, 0($sp) sw $t5, 4($sp) move $t5, $t1 jal bitMNum2 lw $ra, 0($sp) lw $t5, 4($sp) addi $sp, $sp, 8 doAgain: li $v0, 4 # print again la $a0, again syscall li $v0, 4 # print hint la $a0, hint syscall jal input beq $t2, $zero, exit j restart overF: li $v0, 4 # print overflow la $a0, overflow syscall addi $sp, $sp, -4 sw $ra, 0($sp) jal drawOverf lw $ra, 0($sp) addi $sp, $sp, 4 j doAgain input: li $v0, 12 # input a character syscall # check input validity beq $v0, $s0, branchY # input is y beq $v0, $s1, branchN # input is n li $v0, 4 # print unvalid la $a0, unvalid syscall addi $sp, $sp, -4 sw $ra, 0($sp) jal wrongTone lw $ra, 0($sp) addi $sp, $sp, 4 j input branchY: li $t2, 1 # set $t2 to 1 if input is y addi $sp, $sp, -4 sw $ra, 0($sp) jal yesTone lw $ra, 0($sp) addi $sp, $sp, 4 jr $ra branchN: li $t2, 0 # set $t2 to 0 if input is n addi $sp, $sp, -4 sw $ra, 0($sp) jal noTone lw $ra, 0($sp) addi $sp, $sp, 4 jr $ra # write card # $s0 current digit (Caller) # $s1 valid random expansion (Caller) # $s2 max digit (same as Caller) # $t0 digit # $t1 upper count # $t2 lower count # $t3 upper end # $t4 lower end # $t5 shamt # $t6 number # $t7 address in card # $t8 card length # $t9 tmp wCard: addi $sp, $sp, -40 # save $t0-$t9 sw $t0, 0($sp) sw $t1, 4($sp) sw $t2, 8($sp) sw $t3, 12($sp) sw $t4, 16($sp) sw $t5, 20($sp) sw $t6, 24($sp) sw $t7, 28($sp) sw $t8, 32($sp) sw $t9, 36($sp) li $t0, 0 # get digit move $t9, $s0 digitL: beq $t9, $zero, digitE addi $t0, $t0, 1 # digit++ srl $t9, $t9, 1 # $t8 >> 1 j digitL digitE: li $t1, 0 # upper count li $t2, 0 # lower count li $t3, 1 # set upper end sub $t5, $s2, $t0 # << max digit - current digit sllv $t3, $t3, $t5 li $t4, 1 # set lower end addi $t5, $t0, -1 # set shamt for splice number sllv $t4, $t4, $t5 # set upper end la $t7, card # get memory address li $t8, 1 # set card length sllv $t8, $t8, $s2 # << 6 srl $t8, $t8, 1 # half of 2^6 # traverse upperL: beq $t1, $t3, upperE # if equal end upper loop lowerL: beq $t2, $t4, lowerE # if equal end lower loop and start a upper loop # print number move $t6, $t1 # number == upper * upper unit + 1 + lower sll $t6, $t6, 1 # << 1 add $t6, $t6, $s1 # + valid binary expansion sllv $t6, $t6, $t5 # << until 6 digit add $t6, $t6, $t2 sw $t6, 0($t7) # save in card addi $t7, $t7, 4 # addr += 4 addi $t2, $t2, 1 # lower count++ j lowerL lowerE: addi $t1, $t1, 1 # upper count++ li $t2, 0 # set lower count to 0 j upperL upperE: lw $t0, 0($sp) lw $t1, 4($sp) lw $t2, 8($sp) lw $t3, 12($sp) lw $t4, 16($sp) lw $t5, 20($sp) lw $t6, 24($sp) lw $t7, 28($sp) lw $t8, 32($sp) lw $t9, 36($sp) addi $sp, $sp, 40 #restore jr $ra # shuffle # $s0 start address (Caller) # $s1 length(Caller) # $t0 break condition # $t1 target address # $t8 tmp1 # $t9 tmp2 shuffle: addi $sp, $sp, -16 # save $t0-t3 sw $t0, 0($sp) sw $t1, 4($sp) sw $t8, 8($sp) sw $t9, 12($sp) shuffleL: slt $t0, $zero, $s1 # 0 < length? 1: 0 beq $t0, $zero, shuffleE # break condition move $a1, $s1 # [0, length) li $v0, 42 syscall sll $a0, $a0, 2 # * 4 add $t1, $s0, $a0 # target address lw $t8, 0($s0) # swap lw $t9, 0($t1) sw $t9, 0($s0) sw $t8, 0($t1) addi $s0, $s0, 4 # addr += 4 addi $s1, $s1, -1 # length-- j shuffleL shuffleE: lw $t0, 0($sp) lw $t1, 4($sp) lw $t8, 8($sp) lw $t9, 12($sp) addi $sp, $sp, 16 # restore jr $ra # print card # $s0 start address (Caller) # $s1 length (Caller) # $s2 feed back value # $t0 index # $t1 address # $t2 feed back index # $t3 number pCard: addi $sp, $sp, -16 # save $t0-t3 sw $t0, 0($sp) sw $t1, 4($sp) sw $t2, 8($sp) sw $t3, 12($sp) li $t0, 0 move $t1, $s0 li $t2, 0 printL: beq $t0, $s1, printE lw $t3, 0($t1) # get number from card beq $t3, $zero, afterPrint # do not print 0 beq $t2, $zero, feedBack li $v0, 11 # print \t li $a0, 0x09 syscall j printNum feedBack: li $v0, 11 # print \n li $a0, 0x0a syscall printNum: move $a0, $t3 li $v0, 1 # print number syscall addi $t2, $t2, 1 # feed back index++ bne $t2, $s2, afterPrint li $t2, 0 # reset feed back index afterPrint: addi $t0, $t0, 1 # index++ addi $t1, $t1, 4 # address+=4 j printL printE: lw $t0, 0($sp) lw $t1, 4($sp) lw $t2, 8($sp) lw $t3, 12($sp) addi $sp, $sp, 16 # restore # bitmap functions addi $sp, $sp, -4 # save for bitmap print number sw $ra, 0($sp) jal bitMNum # print num in bitmap lw $ra, 0($sp) addi $sp, $sp, 4 # restore jr $ra ############################################################################### # Bitmap functions # Bitmap print number by yuer # Bitmap print picuture by pengfei ############################################################################### # Bitmap print number (yuer) bitMNum: addi $sp, $sp, -92 # save variables sw $ra, 0($sp) sw $a0, 4($sp) sw $a1, 8($sp) sw $a2, 12($sp) sw $a3, 16($sp) sw $s0, 20($sp) sw $s1, 24($sp) sw $s2, 28($sp) sw $s3, 32($sp) sw $s4, 36($sp) sw $s5, 40($sp) sw $s6, 44($sp) sw $s7, 48($sp) sw $t0, 52($sp) sw $t1, 56($sp) sw $t2, 60($sp) sw $t3, 64($sp) sw $t4, 68($sp) sw $t5, 72($sp) sw $t6, 76($sp) sw $t7, 80($sp) sw $t8, 84($sp) sw $t9, 88($sp) #x from 10 - 370, y from 100 - 200, cube 45 x 25, word 8 x 16 li $s0, 10 #x position of the head li $s1, 100 #y position of the head li $t7, 200 li $t8, 370 li $s7, 10 la $t5, card # point to card li $t4, 32 # count: print at most 32 numbers outer: li $a2, 0xFFFFFFFF #loads the color white into the register $a2 li $s0, 10 inner: move $s3, $s0 move $s4, $s1 zeroJp: lw $s2, 0($t5) # load print number addi $t5, $t5, 4 # address ++4 addi $t4, $t4, -1 # count-- beq $s2, $zero, zeroJp # read again if zero #li $s2, 88 # where you will need to load print number into $s2 div $s2, $s7 mfhi $s6 mflo $s5 add $a0, $s5, $zero jal read addi $s0, $s3, 12 move $s1, $s4 add $a0, $s6, $zero jal read move $s0, $s3 move $s1, $s4 # exit condition for not print zero beq $t4, $zero, exitBPN addi $s0, $s0, 45 blt $s0, $t8, inner addi $s1, $s1, 25 blt $s1, $t7, outer # exit for bitmapPN exitBPN: lw $ra, 0($sp) lw $a0, 4($sp) lw $a1, 8($sp) lw $a2, 12($sp) lw $a3, 16($sp) lw $s0, 20($sp) lw $s1, 24($sp) lw $s2, 28($sp) lw $s3, 32($sp) lw $s4, 36($sp) lw $s5, 40($sp) lw $s6, 44($sp) lw $s7, 48($sp) lw $t0, 52($sp) lw $t1, 56($sp) lw $t2, 60($sp) lw $t3, 64($sp) lw $t4, 68($sp) lw $t5, 72($sp) lw $t6, 76($sp) lw $t7, 80($sp) lw $t8, 84($sp) lw $t9, 88($sp) addi $sp, $sp, 92 # restore variables jr $ra # $t5 answer # Bitmap print number for answer(yuer) bitMNum2: addi $sp, $sp, -92 # save variables sw $ra, 0($sp) sw $a0, 4($sp) sw $a1, 8($sp) sw $a2, 12($sp) sw $a3, 16($sp) sw $s0, 20($sp) sw $s1, 24($sp) sw $s2, 28($sp) sw $s3, 32($sp) sw $s4, 36($sp) sw $s5, 40($sp) sw $s6, 44($sp) sw $s7, 48($sp) sw $t0, 52($sp) sw $t1, 56($sp) sw $t2, 60($sp) sw $t3, 64($sp) sw $t4, 68($sp) sw $t5, 72($sp) sw $t6, 76($sp) sw $t7, 80($sp) sw $t8, 84($sp) sw $t9, 88($sp) #x from 10 - 370, y from 100 - 200, cube 45 x 25, word 8 x 16 li $a2, 0xFFFFFFFF li $s0, 190 li $s1, 150 li $s2, 10 move $s3, $s0 move $s4, $s1 div $t5, $s2 mfhi $s6 mflo $s5 add $a0, $s5, $zero jal read addi $s0, $s3, 12 move $s1, $s4 add $a0, $s6, $zero jal read move $s0, $s3 move $s1, $s4 # exit for bitmapPN exitBPN2: lw $ra, 0($sp) lw $a0, 4($sp) lw $a1, 8($sp) lw $a2, 12($sp) lw $a3, 16($sp) lw $s0, 20($sp) lw $s1, 24($sp) lw $s2, 28($sp) lw $s3, 32($sp) lw $s4, 36($sp) lw $s5, 40($sp) lw $s6, 44($sp) lw $s7, 48($sp) lw $t0, 52($sp) lw $t1, 56($sp) lw $t2, 60($sp) lw $t3, 64($sp) lw $t4, 68($sp) lw $t5, 72($sp) lw $t6, 76($sp) lw $t7, 80($sp) lw $t8, 84($sp) lw $t9, 88($sp) addi $sp, $sp, 92 # restore variables jr $ra read: addi $sp, $sp, -4 sw $ra, ($sp) move $s2, $a0 beq $s2, 0, draw0 beq $s2, 1, draw1 beq $s2, 2, draw2 beq $s2, 3, draw3 beq $s2, 4, draw4 beq $s2, 5, draw5 beq $s2, 6, draw6 beq $s2, 7, draw7 beq $s2, 8, draw8 beq $s2, 9, draw9 readE: lw $ra, ($sp) # beq is not jal addi $sp, $sp, 4 jr $ra draw0: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $t6, $s1, 8 jal col addi $s0, $s0, -8 addi $s1, $s1, -16 addi $t6, $s1, 8 jal col addi $t6, $s1, 8 jal col addi $t6, $s0, 8 jal row lw $ra, ($sp) addi $sp, $sp, 4 j readE draw1: addi $sp, $sp, -4 sw $ra, ($sp) addi $s0, $s0, 8 addi $t6, $s1, 8 jal col addi $t6, $s1, 8 jal col lw $ra, ($sp) addi $sp, $sp, 4 j readE draw2: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $t6, $s0, 0 addi $s0, $s0, -8 jal row addi $s0, $s0, -8 addi $t6, $s1, 8 jal col addi $t6, $s0, 8 jal row lw $ra, ($sp) addi $sp, $sp, 4 j readE draw3: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $t6, $s1, 8 jal col addi $t6, $s0, 0 addi $s0, $s0, -8 jal row addi $s0, $s0, -8 addi $s1, $s1, -8 jal row lw $ra, ($sp) addi $sp, $sp, 4 j readE draw4: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s1, 8 jal col addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $s1, $s1, -16 addi $t6, $s1, 8 jal col lw $ra, ($sp) addi $sp, $sp, 4 j readE draw5: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s1, 8 jal col addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $t6, $s0, 0 addi $s0, $s0, -8 jal row addi $s0, $s0, -8 addi $s1, $s1, -16 addi $t6, $s0, 8 jal row lw $ra, ($sp) addi $sp, $sp, 4 j readE draw6: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s1, 8 jal col addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $t6, $s0, 0 addi $s0, $s0, -8 jal row addi $s0, $s0, -8 addi $s1, $s1, -16 addi $t6, $s0, 8 jal row addi $s0, $s0, -8 addi $s1, $s1, 8 addi $t6, $s1, 8 jal col lw $ra, ($sp) addi $sp, $sp, 4 j readE draw7: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $t6, $s1, 8 jal col lw $ra, ($sp) addi $sp, $sp, 4 j readE draw8: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $t6, $s1, 8 jal col addi $s0, $s0, -8 addi $s1, $s1, -16 addi $t6, $s1, 8 jal col addi $t6, $s1, 8 jal col addi $t6, $s0, 8 jal row addi $t6, $s0, 0 addi $s0, $s0, -8 addi $s1, $s1, -8 jal row lw $ra, ($sp) addi $sp, $sp, 4 j readE draw9: addi $sp, $sp, -4 sw $ra, ($sp) addi $t6, $s0, 8 jal row addi $t6, $s1, 8 jal col addi $t6, $s1, 8 jal col addi $s0, $s0, -8 addi $s1, $s1, -16 addi $t6, $s1, 8 jal col addi $t6, $s0, 8 jal row addi $t6, $s0, 0 addi $s0, $s0, -8 addi $s1, $s1, 8 jal row lw $ra, ($sp) addi $sp, $sp, 4 j readE row: ble $s0, $t6, DrawRow addi $s0, $s0, -1 jr $ra col: ble $s1, $t6, DrawCol addi $s1, $s1, -1 jr $ra DrawRow: li $t3, 0x10000100 #t3 = first Pixel of the screen sll $t0, $s1, 9 #y = y * 512 addu $t0, $t0, $s0 # (xy) t0 = x + y sll $t0, $t0, 2 # (xy) t0 = xy * 4 addu $t0, $t3, $t0 # adds xy to the first pixel ( t3 ) sw $a2, ($t0) # put the color ($a2) in $t0 addi $s0, $s0, 1 #adds 1 to the X of the head j row DrawCol: li $t3, 0x10000100 #t3 = first Pixel of the screen sll $t0, $s1, 9 #y = y * 512 addu $t0, $t0, $s0 # (xy) t0 = x + y sll $t0, $t0, 2 # (xy) t0 = xy * 4 addu $t0, $t3, $t0 # adds xy to the first pixel ( t3 ) sw $a2, ($t0) # put the color ($a2) in $t0 addi $s1, $s1, 1 #adds 1 to the X of the head j col # Bitmap print pircture (pengfei) drawStart: addi $sp, $sp, -8 # save variable sw $ra, 0($sp) sw $t0, 4($sp) la $t0, pictStart jal makeDot addi $sp, $sp, -8 sw $ra, 0($sp) sw $s0, 4($sp) la $s0, musicStt # mucic jal musicTime lw $ra, 0($sp) lw $s0, 4($sp) addi $sp, $sp, 8 la $t0, pictStart2 jal makeDot lw $ra, 0($sp) lw $t0, 4($sp) addi $sp, $sp, 8 # restore variable jr $ra drawAnsw: addi $sp, $sp, -8 # save variable sw $ra, 0($sp) sw $t0, 4($sp) jal yesTone jal noTone la $t0, pictAnsw jal makeDot lw $ra, 0($sp) lw $t0, 4($sp) addi $sp, $sp, 8 # restore variable jr $ra drawOverf: addi $sp, $sp, -8 # save variable sw $ra, 0($sp) sw $t0, 4($sp) jal yesTone jal noTone la $t0, pictOverf jal makeDot lw $ra, 0($sp) lw $t0, 4($sp) addi $sp, $sp, 8 # restore variable jr $ra drawEnd: addi $sp, $sp, -8 # save variable sw $ra, 0($sp) sw $t0, 4($sp) la $t0, pictEnd jal makeDot addi $sp, $sp, -8 sw $ra, 0($sp) sw $s0, 4($sp) la $s0, musicEnd # mucic jal musicTime lw $ra, 0($sp) lw $s0, 4($sp) addi $sp, $sp, 8 lw $ra, 0($sp) lw $t0, 4($sp) addi $sp, $sp, 8 # restore variable jr $ra # $t0 dir # $t1 x-offset # $t2 y-offset # make dot? makeDot: addi $sp, $sp, -16 # save variable sw $ra, 0($sp) sw $a0, 4($sp) sw $a1, 8($sp) sw $a2, 12($sp) move $a0, $t0 # dir li $v0, 60 syscall li $a0, 0 # x li $a1, 0 # y li $v0, 61 syscall li $a0, 0 li $a1, 256 li $a2, 0 # $v0 = base+$a0*4+$a1*512*4 sll $a0,$a0,2 sll $a1,$a1,11 addi $v0, $a0, 0x10010000 add $v0, $v0, $a1 sw $v1, 0($v0) # make dot lw $ra, 0($sp) lw $a0, 4($sp) lw $a1, 8($sp) lw $a2, 12($sp) addi $sp, $sp, 16 # restore variable jr $ra ############################################################################### # Music function # Sound effect by pengfei ############################################################################### yesTone: li $a0, 83 #$a0 stores the pitch of the tone li $a1, 250 #$a1 stores the length of the tone li $a2, 112 #$a2 stores the instrument of the tone li $a3, 100 #$a3 stores the volumn of the tone li $v0, 33 #system call code for MIDI out synchronous syscall #play the first half of the tone jr $ra noTone: li $a0, 79 #$a0 stores the pitch of the tone li $a1, 250 #$a1 stores the length of the tone li $a2, 112 #$a2 stores the insrument of the tone li $a3, 100 #$a3 stores the volumn of the tone li $v0, 33 #system call code for MIDI out synchronous syscall #play the second half of the tone jr $ra wrongTone: li $a0, 50 #$a0 stores the pitch of the tone li $a1, 1500 #$a1 stores the length of the tone li $a2, 32 #$a2 stores the insrument of the tone li $a3, 127 #$a3 stores the volumn of the tone li $v0, 31 #system call code for MIDI out syscall #play the tone jr $ra # $s0 save the music file dir musicTime: addi $sp, $sp, -52 #save sw $ra, 0($sp) sw $a0, 4($sp) sw $a1, 8($sp) sw $a2, 12($sp) sw $a3, 16($sp) sw $t0, 20($sp) sw $t1, 24($sp) sw $t2, 28($sp) sw $t3, 32($sp) sw $t4, 36($sp) sw $t5, 40($sp) sw $t6, 44($sp) sw $t7, 48($sp) openFile: li $v0, 13 move $a0, $s0 #file name li $a1, 0 #0 for read li $a2,0 syscall move $t7,$v0 readNumNotes: #gets number of notes li $v0, 14 #syscall 14 read from file move $a0,$t7 #the file description la $a1, numOfNotesBuff #the buffer li $a2,3 #number of chars to read syscall move $t7,$a0 la $t4,numOfNotesBuff #convert the buffer's chars to int li $t0, 0 la $t1,numOfNotes #get the ascii value x() lb $t2,0($t4) li $t3,10 sub $t2,$t2,48 mult $t2,$t3 mflo $t2 add $t0,$t0,$t2 #get the ascii value ()x lb $t2,1($t4) li $t3,1 sub $t2,$t2,48 mult $t2,$t3 mflo $t2 add $t0,$t0,$t2 sw $t0,($t1) playNotes: li $t5,0 la $t2, numOfNotes lw $t4,($t2) playContinue: #get the note li $v0, 14 #syscall 14 read from file move $a0,$t7 #the file description la $a1, buff #the buffer li $a2,1 #number of chars to read syscall move $t7,$a0 #figures out which note is going to be played la $t2,buff lb $t0,($t2) li $t1,61 beq $t0,68,noteD beq $t0,69,noteE beq $t0,70,noteF beq $t0,71,noteG beq $t0,65,noteA beq $t0,66,noteB beq $t0,67,noteC #else play C# b noteSetUpDone noteD: add $t1,$t1,1 b noteSetUpDone noteE: add $t1,$t1,3 b noteSetUpDone noteF: add $t1,$t1,4 b noteSetUpDone noteG: add $t1,$t1,6 b noteSetUpDone noteA: add $t1,$t1,8 b noteSetUpDone noteB: add $t1,$t1,10 b noteSetUpDone noteC: add $t1,$t1,11 b noteSetUpDone noteSetUpDone: #play the sound move $a0,$t1 #pitch li $a1,100 #time li $a2,37 #32#31#29#instumanets li $a3,1000 #volume li $v0,33 #syscall to beep with pause syscall #increment counter add $t5,$t5,1 #checks that the counter is less than the number of notes bne $t5,$t4, notDone j closeFile notDone: b playContinue closeFile: li $v0, 16 move $a0,$t7 syscall lw $ra, 0($sp) lw $a0, 4($sp) lw $a1, 8($sp) lw $a2, 12($sp) lw $a3, 16($sp) lw $t0, 20($sp) lw $t1, 24($sp) lw $t2, 28($sp) lw $t3, 32($sp) lw $t4, 36($sp) lw $t5, 40($sp) lw $t6, 44($sp) lw $t7, 48($sp) addi $sp, $sp, 52 # restore jr $ra ############################################################################### # exit exit: addi $sp, $sp, -4 sw $ra, 0($sp) jal drawEnd lw $ra, 0($sp) addi $sp, $sp, 4 li $v0, 4 # print end la $a0, end syscall li $v0, 10 syscall
; A034721: a(n) = (10*n^3 - 9*n^2 + 2*n)/3 + 1. ; 1,2,17,66,169,346,617,1002,1521,2194,3041,4082,5337,6826,8569,10586,12897,15522,18481,21794,25481,29562,34057,38986,44369,50226,56577,63442,70841,78794,87321,96442,106177,116546,127569,139266,151657,164762,178601,193194,208561,224722,241697,259506,278169,297706,318137,339482,361761,384994,409201,434402,460617,487866,516169,545546,576017,607602,640321,674194,709241,745482,782937,821626,861569,902786,945297,989122,1034281,1080794,1128681,1177962,1228657,1280786,1334369,1389426,1445977,1504042,1563641,1624794,1687521,1751842,1817777,1885346,1954569,2025466,2098057,2172362,2248401,2326194,2405761,2487122,2570297,2655306,2742169,2830906,2921537,3014082,3108561,3204994 sub $0,1 mul $0,10 mov $1,$0 add $0,8 bin $0,3 sub $0,$1 div $0,50 add $0,1
; void *w_vector_size(w_vector_t *v) SECTION code_adt_w_vector PUBLIC w_vector_size defc w_vector_size = asm_w_vector_size INCLUDE "adt/w_vector/z80/asm_w_vector_size.asm"
; A260918: Number of squares of all sizes in polyominoes obtained by union of two pyramidal figures (A092498) with intersection equals A002623. ; 0,1,5,15,33,60,100,154,224,313,423,555,713,898,1112,1358,1638,1953,2307,2701,3137,3618,4146,4722,5350,6031,6767,7561,8415,9330,10310,11356,12470,13655,14913,16245,17655,19144,20714,22368,24108,25935,27853,29863,31967,34168,36468,38868,41372,43981,46697,49523,52461,55512,58680,61966,65372,68901,72555,76335,80245,84286,88460,92770,97218,101805,106535,111409,116429,121598,126918,132390,138018,143803,149747,155853,162123,168558,175162,181936,188882,196003,203301,210777,218435,226276,234302,242516,250920,259515,268305,277291,286475,295860,305448,315240,325240,335449,345869,356503,367353,378420,389708,401218,412952,424913,437103,449523,462177,475066,488192,501558,515166,529017,543115,557461,572057,586906,602010,617370,632990,648871,665015,681425,698103,715050,732270,749764,767534,785583,803913,822525,841423,860608,880082,899848,919908,940263,960917,981871,1003127,1024688,1046556,1068732,1091220,1114021,1137137,1160571,1184325,1208400,1232800,1257526,1282580,1307965,1333683,1359735,1386125,1412854,1439924,1467338,1495098,1523205,1551663,1580473,1609637,1639158,1669038,1699278,1729882,1760851,1792187,1823893,1855971,1888422,1921250,1954456,1988042,2022011,2056365,2091105,2126235,2161756,2197670,2233980,2270688,2307795,2345305,2383219,2421539,2460268,2499408,2538960,2578928,2619313,2660117,2701343,2742993,2785068,2827572,2870506,2913872,2957673,3001911,3046587,3091705,3137266,3183272,3229726,3276630,3323985,3371795,3420061,3468785,3517970,3567618,3617730,3668310,3719359,3770879,3822873,3875343,3928290,3981718,4035628,4090022,4144903,4200273,4256133,4312487,4369336,4426682,4484528,4542876,4601727,4661085,4720951,4781327,4842216,4903620,4965540,5027980,5090941,5154425,5218435,5282973,5348040,5413640,5479774,5546444,5613653 mov $12,$0 mov $14,$0 lpb $14 clr $0,12 mov $0,$12 sub $14,1 sub $0,$14 mov $9,$0 mov $11,$0 lpb $11 mov $0,$9 sub $11,1 sub $0,$11 mov $3,$0 div $3,3 mov $4,$3 mov $8,$0 div $8,2 add $8,$3 add $8,$0 add $4,$8 add $10,$4 lpe add $13,$10 lpe mov $1,$13
; A021805: Decimal expansion of 1/801. ; Submitted by Jon Maiga ; 0,0,1,2,4,8,4,3,9,4,5,0,6,8,6,6,4,1,6,9,7,8,7,7,6,5,2,9,3,3,8,3,2,7,0,9,1,1,3,6,0,7,9,9,0,0,1,2,4,8,4,3,9,4,5,0,6,8,6,6,4,1,6,9,7,8,7,7,6,5,2,9,3,3,8,3,2,7,0,9,1,1,3,6,0,7,9,9,0,0,1,2,4,8,4,3,9,4,5 seq $0,42 ; Unary representation of natural numbers. div $0,89 mod $0,10
; A004970: a(n) = ceiling(n*phi^15), where phi is the golden ratio, A001622. ; 0,1365,2729,4093,5457,6821,8185,9549,10913,12277,13641,15005,16369,17733,19097,20461,21825,23189,24553,25917,27281,28645,30009,31373,32737,34101,35465,36829,38193 mov $1,$0 trn $1,1 mov $2,$0 sub $0,$1 lpb $2 add $0,1364 sub $2,1 lpe
; A169642: a(n) = A005408(n) * A022998(n). ; 0,3,20,21,72,55,156,105,272,171,420,253,600,351,812,465,1056,595,1332,741,1640,903,1980,1081,2352,1275,2756,1485,3192,1711,3660,1953,4160,2211,4692,2485,5256,2775,5852,3081,6480,3403,7140,3741,7832,4095,8556,4465,9312,4851,10100,5253,10920,5671,11772,6105,12656,6555,13572,7021,14520,7503,15500,8001,16512,8515,17556,9045,18632,9591,19740,10153,20880,10731,22052,11325,23256,11935,24492,12561,25760,13203,27060,13861,28392,14535,29756,15225,31152,15931,32580,16653,34040,17391,35532,18145,37056,18915,38612,19701 mov $1,$0 mul $0,2 gcd $1,2 mov $2,$0 mul $2,$1 mul $0,$2 add $0,$2 div $0,2
; ; jdcolor.asm - colorspace conversion (SSE2) ; ; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB ; Copyright (C) 2009, D. R. Commander. ; ; Based on the x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 ; ; [TAB8] %include "jsimdext.inc" ; -------------------------------------------------------------------------- %define SCALEBITS 16 F_0_344 equ 22554 ; FIX(0.34414) F_0_714 equ 46802 ; FIX(0.71414) F_1_402 equ 91881 ; FIX(1.40200) F_1_772 equ 116130 ; FIX(1.77200) F_0_402 equ (F_1_402 - 65536) ; FIX(1.40200) - FIX(1) F_0_285 equ ( 65536 - F_0_714) ; FIX(1) - FIX(0.71414) F_0_228 equ (131072 - F_1_772) ; FIX(2) - FIX(1.77200) ; -------------------------------------------------------------------------- SECTION SEG_CONST alignz 16 global EXTN(jconst_ycc_rgb_convert_sse2) PRIVATE EXTN(jconst_ycc_rgb_convert_sse2): PW_F0402 times 8 dw F_0_402 PW_MF0228 times 8 dw -F_0_228 PW_MF0344_F0285 times 4 dw -F_0_344, F_0_285 PW_ONE times 8 dw 1 PD_ONEHALF times 4 dd 1 << (SCALEBITS-1) alignz 16 ; -------------------------------------------------------------------------- SECTION SEG_TEXT BITS 32 %include "jdcolext-sse2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_RGB_RED %define RGB_GREEN EXT_RGB_GREEN %define RGB_BLUE EXT_RGB_BLUE %define RGB_PIXELSIZE EXT_RGB_PIXELSIZE %define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extrgb_convert_sse2 %include "jdcolext-sse2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_RGBX_RED %define RGB_GREEN EXT_RGBX_GREEN %define RGB_BLUE EXT_RGBX_BLUE %define RGB_PIXELSIZE EXT_RGBX_PIXELSIZE %define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extrgbx_convert_sse2 %include "jdcolext-sse2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_BGR_RED %define RGB_GREEN EXT_BGR_GREEN %define RGB_BLUE EXT_BGR_BLUE %define RGB_PIXELSIZE EXT_BGR_PIXELSIZE %define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extbgr_convert_sse2 %include "jdcolext-sse2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_BGRX_RED %define RGB_GREEN EXT_BGRX_GREEN %define RGB_BLUE EXT_BGRX_BLUE %define RGB_PIXELSIZE EXT_BGRX_PIXELSIZE %define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extbgrx_convert_sse2 %include "jdcolext-sse2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_XBGR_RED %define RGB_GREEN EXT_XBGR_GREEN %define RGB_BLUE EXT_XBGR_BLUE %define RGB_PIXELSIZE EXT_XBGR_PIXELSIZE %define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extxbgr_convert_sse2 %include "jdcolext-sse2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_XRGB_RED %define RGB_GREEN EXT_XRGB_GREEN %define RGB_BLUE EXT_XRGB_BLUE %define RGB_PIXELSIZE EXT_XRGB_PIXELSIZE %define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extxrgb_convert_sse2 %include "jdcolext-sse2.asm"
;=============================================================================== ; Copyright 2015-2019 Intel Corporation ; All Rights Reserved. ; ; If this software was obtained under the Intel Simplified Software License, ; the following terms apply: ; ; The source code, information and material ("Material") contained herein is ; owned by Intel Corporation or its suppliers or licensors, and title to such ; Material remains with Intel Corporation or its suppliers or licensors. The ; Material contains proprietary information of Intel or its suppliers and ; licensors. The Material is protected by worldwide copyright laws and treaty ; provisions. No part of the Material may be used, copied, reproduced, ; modified, published, uploaded, posted, transmitted, distributed or disclosed ; in any way without Intel's prior express written permission. No license under ; any patent, copyright or other intellectual property rights in the Material ; is granted to or conferred upon you, either expressly, by implication, ; inducement, estoppel or otherwise. Any license under such intellectual ; property rights must be express and approved by Intel in writing. ; ; Unless otherwise agreed by Intel in writing, you may not remove or alter this ; notice or any other notice embedded in Materials by Intel or Intel's ; suppliers or licensors in any way. ; ; ; If this software was obtained under the Apache License, Version 2.0 (the ; "License"), the following terms apply: ; ; You may not use this file except in compliance with the License. You may ; obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ; ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, WITHOUT ; WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; ; See the License for the specific language governing permissions and ; limitations under the License. ;=============================================================================== ; ; ; Purpose: Cryptography Primitive. ; Rijndael-128 (AES) cipher functions. ; (It's the special free from Sbox/tables implementation) ; ; Content: ; SafeDecrypt_RIJ128() ; ; History: ; ; Notes. ; The implementation is based on ; isomorphism between native GF(2^8) and composite GF((2^4)^2). ; ; include asmdefs.inc include ia_32e.inc include ia_32e_regs.inc include pcpvariant.inc IF (_AES_NI_ENABLING_ EQ _FEATURE_OFF_) OR (_AES_NI_ENABLING_ EQ _FEATURE_TICKTOCK_) IF (_IPP32E GE _IPP32E_U8) IFDEF xxIPP_PIC LD_ADDR MACRO reg:REQ, addr:REQ LOCAL LABEL call LABEL LABEL: pop reg sub reg, LABEL-addr ENDM ELSE LD_ADDR MACRO reg:REQ, addr:REQ lea reg, addr ENDM ENDIF PTRANSFORM MACRO dst,src, memTransLO, memTransHI, tmp, srcLO movdqa dst, oword ptr memTransLO ;; LO transformation movdqa tmp, oword ptr memTransHI ;; HI transformation movdqa srcLO, src ;; split src: psrlw src, 4 ;; pand srcLO, xmm7 ;; low 4 bits -> srcLO pand src, xmm7 ;; upper 4 bits -> src pshufb dst, srcLO ;; transformation pshufb tmp, src pxor dst, tmp ENDM PLOOKUP_MEM MACRO dst, src, Table movdqa dst, OWORD PTR Table pshufb dst,src ENDM PREDUCE_MOD15 MACRO dst, src movdqa dst, src pcmpgtb src, xmm7 psubb dst, src ENDM PINVERSE_GF16_INV MACRO xmmB,xmmC, xmmP,xmmQ,xmmD,xmmT PLOOKUP_MEM xmmT, xmmC, GF16_logTbl ;; xmmT = index_of(c) pxor xmmC, xmmB PLOOKUP_MEM xmmQ, xmmC, GF16_logTbl ;; xmmQ = index_of(b xor c) PLOOKUP_MEM xmmD, xmmB, GF16_sqr1 ;; xmmD = sqr(b)*beta^14 PLOOKUP_MEM xmmP, xmmB, GF16_logTbl ;; xmmP = index_of(b) paddb xmmT, xmmQ ;; xmmT = index_of(c) + index_of(b xor c) PREDUCE_MOD15 xmmC, xmmT ;; PLOOKUP_MEM xmmT, xmmC, GF16_expTbl ;; c*(b xor c) pxor xmmD, xmmT ;; xmmD = delta = (c*(b xor c)) xor (sqr(b)*beta^14) PLOOKUP_MEM xmmT, xmmD, GF16_invLog ;; xmmT = index_of( inv(delta) ) paddb xmmQ, xmmT ;; xmmQ = index_of((b xor c) * inv(delta)) paddb xmmP, xmmT ;; xmmP = index_of(b * inv(delta)) PREDUCE_MOD15 xmmT, xmmQ PLOOKUP_MEM xmmC, xmmT, GF16_expTbl PREDUCE_MOD15 xmmT, xmmP PLOOKUP_MEM xmmB, xmmT, GF16_expTbl ENDM IPPCODE SEGMENT 'CODE' ALIGN (IPP_ALIGN_FACTOR) ALIGN IPP_ALIGN_FACTOR DECODE_DATA: ;; (forward) native GF(2^8) to composite GF((2^4)^2) transformation : {0x01,0x2E,0x49,0x43,0x35,0xD0,0x3D,0xE9} TransFwdLO \ DB 000h ;; 000h ;; 0 DB 001h ;; 001h ;; 1 DB 02Eh ;; 02Eh ;; 2 DB 02Fh ;; 02Eh XOR 001h ;; 3 DB 049h ;; 049h ;; 4 DB 048h ;; 049h XOR 001h ;; 5 DB 067h ;; 049h XOR 02Eh ;; 6 DB 066h ;; 049h XOR 02Eh XOR 001h ;; 7 DB 043h ;; 043h ;; 8 DB 042h ;; 043h XOR 001h ;; 9 DB 06Dh ;; 043h XOR 02Eh ;; a DB 06Ch ;; 043h XOR 02Eh XOR 001h ;; b DB 00Ah ;; 043h XOR 049h ;; c DB 00Bh ;; 043h XOR 049h XOR 001h ;; d DB 024h ;; 043h XOR 049h XOR 02Eh ;; e DB 025h ;; 043h XOR 049h XOR 02Eh XOR 001h ;; f TransFwdHI \ DB 000h ;; 000h ;; 0 DB 035h ;; 035h ;; 1 DB 0D0h ;; 0D0h ;; 2 DB 0E5h ;; 0D0h XOR 035h ;; 3 DB 03Dh ;; 03Dh ;; 4 DB 008h ;; 03Dh XOR 035h ;; 5 DB 0EDh ;; 03Dh XOR 0D0h ;; 6 DB 0D8h ;; 03Dh XOR 0D0h XOR 035h ;; 7 DB 0E9h ;; 0E9h ;; 8 DB 0DCh ;; 0E9h XOR 035h ;; 9 DB 039h ;; 0E9h XOR 0D0h ;; a DB 00Ch ;; 0E9h XOR 0D0h XOR 035h ;; b DB 0D4h ;; 0E9h XOR 03Dh ;; c DB 0E1h ;; 0E9h XOR 03Dh XOR 035h ;; d DB 004h ;; 0E9h XOR 03Dh XOR 0D0h ;; e DB 031h ;; 0E9h XOR 03Dh XOR 0D0h XOR 035h ;; f ;; (inverse) composite GF((2^4)^2) to native GF(2^8) transformation : {0x01,0x5C,0xE0,0x50,0x1F,0xEE,0x55,0x6A} TransInvLO \ DB 000h ;; 000h ;; 0 DB 001h ;; 001h ;; 1 DB 05Ch ;; 05Ch ;; 2 DB 05Dh ;; 05Ch XOR 001h ;; 3 DB 0E0h ;; 0E0h ;; 4 DB 0E1h ;; 0E0h XOR 001h ;; 5 DB 0BCh ;; 0E0h XOR 05Ch ;; 6 DB 0BDh ;; 0E0h XOR 05Ch XOR 001h ;; 7 DB 050h ;; 050h ;; 8 DB 051h ;; 050h XOR 001h ;; 9 DB 00Ch ;; 050h XOR 05Ch ;; a DB 00Dh ;; 050h XOR 05Ch XOR 001h ;; b DB 0B0h ;; 050h XOR 0E0h ;; c DB 0B1h ;; 050h XOR 0E0h XOR 001h ;; d DB 0ECh ;; 050h XOR 0E0h XOR 05Ch ;; e DB 0EDh ;; 050h XOR 0E0h XOR 05Ch XOR 001h ;; f TransInvHI \ DB 000h ;; 000h ;; 0 DB 01Fh ;; 01Fh ;; 1 DB 0EEh ;; 0EEh ;; 2 DB 0F1h ;; 0EEh XOR 01Fh ;; 3 DB 055h ;; 055h ;; 4 DB 04Ah ;; 055h XOR 01Fh ;; 5 DB 0BBh ;; 055h XOR 0EEh ;; 6 DB 0A4h ;; 055h XOR 0EEh XOR 01Fh ;; 7 DB 06Ah ;; 06Ah ;; 8 DB 075h ;; 06Ah XOR 01Fh ;; 9 DB 084h ;; 06Ah XOR 0EEh ;; a DB 09Bh ;; 06Ah XOR 0EEh XOR 01Fh ;; b DB 03Fh ;; 06Ah XOR 055h ;; c DB 020h ;; 06Ah XOR 055h XOR 01Fh ;; d DB 0D1h ;; 06Ah XOR 055h XOR 0EEh ;; e DB 0CEh ;; 06Ah XOR 055h XOR 0EEh XOR 01Fh ;; f GF16_csize DB 00Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh,0Fh ;; GF16 elements: ;; 0 1 2 3 4 5 6 7 8 9 A B C D E F GF16_logTbl \ DB 0C0h,00h,01h,04h,02h,08h,05h,0Ah,03h,0Eh,09h,07h,06h,0Dh,0Bh,0Ch GF16_expTbl \ DB 001h,02h,04h,08h,03h,06h,0Ch,0Bh,05h,0Ah,07h,0Eh,0Fh,0Dh,09h,01h GF16_sqr1 \ DB 000h,09h,02h,0Bh,08h,01h,0Ah,03h,06h,0Fh,04h,0Dh,0Eh,07h,0Ch,05h ;; sqr(GF16_element) * beta^14 GF16_invLog \ DB 0C0h,00h,0Eh,0Bh,0Dh,07h,0Ah,05h,0Ch,01h,06h,08h,09h,02h,04h,03h ;; affine transformation matrix (inverse cipher) : {0x50,0x36,0x15,0x82,0x01,0x34,0x40,0x3E} InvAffineLO \ DB 000h ;; 000h ;; 0 DB 050h ;; 050h ;; 1 DB 036h ;; 036h ;; 2 DB 066h ;; 036h XOR 050h ;; 3 DB 015h ;; 015h ;; 4 DB 045h ;; 015h XOR 050h ;; 5 DB 023h ;; 015h XOR 036h ;; 6 DB 073h ;; 015h XOR 036h XOR 050h ;; 7 DB 082h ;; 082h ;; 8 DB 0D2h ;; 082h XOR 050h ;; 9 DB 0B4h ;; 082h XOR 036h ;; a DB 0E4h ;; 082h XOR 036h XOR 050h ;; b DB 097h ;; 082h XOR 015h ;; c DB 0C7h ;; 082h XOR 015h XOR 050h ;; d DB 0A1h ;; 082h XOR 015h XOR 036h ;; e DB 0F1h ;; 082h XOR 015h XOR 036h XOR 050h ;; f InvAffineHI \ DB 000h ;; 000h ;; 0 DB 001h ;; 001h ;; 1 DB 034h ;; 034h ;; 2 DB 035h ;; 034h XOR 001h ;; 3 DB 040h ;; 040h ;; 4 DB 041h ;; 040h XOR 001h ;; 5 DB 074h ;; 040h XOR 034h ;; 6 DB 075h ;; 040h XOR 034h XOR 001h ;; 7 DB 03Eh ;; 03Eh ;; 8 DB 03Fh ;; 03Eh XOR 001h ;; 9 DB 00Ah ;; 03Eh XOR 034h ;; a DB 00Bh ;; 03Eh XOR 034h XOR 001h ;; b DB 07Eh ;; 03Eh XOR 040h ;; c DB 07Fh ;; 03Eh XOR 040h XOR 001h ;; d DB 04Ah ;; 03Eh XOR 040h XOR 034h ;; e DB 04Bh ;; 03Eh XOR 040h XOR 034h XOR 001h ;; f ;; affine transformation constant (inverse cipher) InvAffineCnt \ DQ 04848484848484848h,04848484848484848h ;; shift rows transformation (inverse cipher) InvShiftRows \ DB 0,13,10,7,4,1,14,11,8,5,2,15,12,9,6,3 ;; mix columns transformation (inverse cipher) GF16mul_4_2x \ DB 000h,024h,048h,06Ch,083h,0A7h,0CBh,0EFh,036h,012h,07Eh,05Ah,0B5h,091h,0FDh,0D9h ;; *(4+2x) GF16mul_1_6x \ DB 000h,061h,0C2h,0A3h,0B4h,0D5h,076h,017h,058h,039h,09Ah,0FBh,0ECh,08Dh,02Eh,04Fh ;; *(1+6x) GF16mul_C_6x \ DB 000h,06Ch,0CBh,0A7h,0B5h,0D9h,07Eh,012h,05Ah,036h,091h,0FDh,0EFh,083h,024h,048h ;; *(C+6x) GF16mul_3_Ax \ DB 000h,0A3h,076h,0D5h,0ECh,04Fh,09Ah,039h,0FBh,058h,08Dh,02Eh,017h,0B4h,061h,0C2h ;; *(3+Ax) GF16mul_B_0x \ DB 000h,00Bh,005h,00Eh,00Ah,001h,00Fh,004h,007h,00Ch,002h,009h,00Dh,006h,008h,003h ;; *(B+0x) GF16mul_0_Bx \ DB 000h,0B0h,050h,0E0h,0A0h,010h,0F0h,040h,070h,0C0h,020h,090h,0D0h,060h,080h,030h ;; *(0+Bx) GF16mul_2_4x \ DB 000h,042h,084h,0C6h,038h,07Ah,0BCh,0FEh,063h,021h,0E7h,0A5h,05Bh,019h,0DFh,09Dh ;; *(2+4x) GF16mul_2_6x \ DB 000h,062h,0C4h,0A6h,0B8h,0DAh,07Ch,01Eh,053h,031h,097h,0F5h,0EBh,089h,02Fh,04Dh ;; *(2+6x) ColumnROR \ DB 1,2,3,0,5,6,7,4,9,10,11,8,13,14,15,12 ALIGN IPP_ALIGN_FACTOR ;************************************************************* ;* void SafeDecrypt_RIJ128(const Ipp8u* pInpBlk, ;* Ipp8u* pOutBlk, ;* int nr, ;* const Ipp8u* pKeys, ;* const void* Tables) ;************************************************************* ;; ;; Lib = U8 ;; IPPASM SafeDecrypt_RIJ128 PROC PUBLIC FRAME USES_GPR rsi, rdi USES_XMM xmm6,xmm7 LOCAL_FRAME = 0 COMP_ABI 5 ;; rdi: pInpBlk: PTR DWORD, ; input block address ;; rsi: pOutBlk: PTR DWORD, ; output block address ;; rdx: nr: DWORD, ; number of rounds ;; rcx: pKey: PTR DWORD ; key material address RSIZE = sizeof dword ; size of row SC = 4 ; columns in STATE SSIZE = RSIZE*SC ; size of state lea rax,[rdx*4] lea rcx,[rcx+rax*4] ; AES-128-keys movdqu xmm0, oword ptr[rdi] ; input block movdqa xmm7, oword ptr GF16_csize ;; convert input into the composite GF((2^4)^2) PTRANSFORM xmm2, xmm0, TransFwdLO,TransFwdHI, xmm1, xmm3 ;; initial whitening pxor xmm2, oword ptr[rcx] sub rcx, SSIZE ;; (nr-1) regular rounds sub rdx,1 decode_round: ;; InvSubByte() Transformation: ;; affine transformation PTRANSFORM xmm0, xmm2, InvAffineLO,InvAffineHI, xmm1, xmm3 pxor xmm0, oword ptr InvAffineCnt ; H(c), c=0x05 ;; split input by low and upper parts movdqa xmm1, xmm0 pand xmm0, xmm7 ; low parts (4 bits) psrlw xmm1, 4 pand xmm1, xmm7 ; upper parts (4 bits) ;; compute multiplicative inverse PINVERSE_GF16_INV xmm1,xmm0, xmm3,xmm2,xmm4,xmm5 ;; InvShiftRows() Transformation: pshufb xmm0, oword ptr InvShiftRows pshufb xmm1, oword ptr InvShiftRows ;; InvMixColumn() Transformation: PLOOKUP_MEM xmm2, xmm0, GF16mul_4_2x ; mul H(0xE) = 0x24 pshufb xmm0, oword ptr ColumnROR PLOOKUP_MEM xmm3, xmm1, GF16mul_1_6x pshufb xmm1, oword ptr ColumnROR pxor xmm2, xmm3 PLOOKUP_MEM xmm3, xmm0, GF16mul_C_6x ; mul H(0xB) = 0x6C pshufb xmm0, oword ptr ColumnROR pxor xmm2, xmm3 PLOOKUP_MEM xmm3, xmm1, GF16mul_3_Ax pshufb xmm1, oword ptr ColumnROR pxor xmm2, xmm3 PLOOKUP_MEM xmm3, xmm0, GF16mul_B_0x ; mul H(0xD) = 0x0B pshufb xmm0, oword ptr ColumnROR pxor xmm2, xmm3 PLOOKUP_MEM xmm3, xmm1, GF16mul_0_Bx pshufb xmm1, oword ptr ColumnROR pxor xmm2, xmm3 PLOOKUP_MEM xmm3, xmm0, GF16mul_2_4x ; mul H(0x9) = 0x42 pxor xmm2, xmm3 PLOOKUP_MEM xmm3, xmm1, GF16mul_2_6x pxor xmm2, xmm3 ;; AddRoundKey() Transformation: pxor xmm2, oword ptr[rcx] sub rcx, SSIZE sub rdx,1 jg decode_round ;; ;; the last one is irregular ;; ;; InvSubByte() Transformation ;; affine transformation PTRANSFORM xmm0, xmm2, InvAffineLO,InvAffineHI, xmm1, xmm3 pxor xmm0, oword ptr InvAffineCnt ; H(c), c=0x05 ;; split input by low and upper parts movdqa xmm1, xmm0 pand xmm0, xmm7 ; low parts (4 bits) psrlw xmm1, 4 pand xmm1, xmm7 ; upper parts (4 bits) ;; compute multiplicative inverse PINVERSE_GF16_INV xmm1,xmm0, xmm3,xmm2,xmm4,xmm5 ;; InvShiftRows() Transformation: psllw xmm1, 4 por xmm1, xmm0 pshufb xmm1, oword ptr InvShiftRows ;; AddRoundKey() Transformation: pxor xmm1, oword ptr[rcx] ;; convert output into the native GF(2^8) PTRANSFORM xmm0,xmm1, TransInvLO,TransInvHI, xmm2, xmm3 movdqu oword ptr[rsi], xmm0 REST_XMM REST_GPR ret IPPASM SafeDecrypt_RIJ128 ENDP ENDIF ENDIF ;; _AES_NI_ENABLING_ END
<% from pwnlib.shellcraft.arm.linux import syscall %> <%page args="level"/> <%docstring> Invokes the syscall iopl. See 'man 2 iopl' for more information. Arguments: level(int): level </%docstring> ${syscall('SYS_iopl', level)}
#include "renderer.hpp" #include "camera.hpp" #include "gl/shaderUtils.hpp" #include "light/light.hpp" #include "material/material.hpp" #include "model.hpp" #include "renderTarget.hpp" #include "renderEffects/auraCompositing.hpp" #include <GL/glew.h> #include <iostream> constexpr GLuint GL_MAJOR = 3; constexpr GLuint GL_MINOR = 3; Renderer::Renderer(int width, int height, std::unique_ptr<Camera>&& camera) : width(width), height(height), camera(std::move(camera)) { std::cout << "Initializing SDL...\n"; if (!initializeSDL()) { std::cout << "Failed to initialize SDL\n"; return; } std::cout << "Initializing GL...\n"; if (!initializeGL()) { std::cout << "Failed to initialize GL\n"; return; } initializeScreenObject(); auraTarget = std::make_unique<RenderTarget>(width, height, true); sceneTarget = std::make_unique<RenderTarget>(width, height, false); auraEffect = std::make_unique<AuraCompositingEffect>(width, height); auraEffect->initialize(); std::cout << "Ready\n"; } Renderer::~Renderer() { SDL_DestroyWindow(window); window = nullptr; SDL_Quit(); } bool Renderer::initializeSDL() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cout << "SDL could not be initialized\n"; } else { SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); window = SDL_CreateWindow("Model Viewer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); if (window == nullptr) { std::cout << "Window could not be created!\n"; } else { screen = SDL_GetWindowSurface(window); } } return true; } bool Renderer::initializeGL() { SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, GL_MAJOR); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, GL_MINOR); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GLContext context = SDL_GL_CreateContext(window); if (context == nullptr) { std::cout << "Error creating openGL context: " << SDL_GetError() << "\n"; return false; } glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { std::cout << "Error initializing GLEW\n"; return false; } if (SDL_GL_SetSwapInterval(1) < 0) { std::cout << "Unable to set VSync\n"; return false; } glEnable(GL_PROGRAM_POINT_SIZE); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Enable depth test glEnable(GL_DEPTH_TEST); glEnable(GL_STENCIL_TEST); // Enable writing to depth buffer glDepthMask(GL_TRUE); // necessary for cubemaps to work correctly // glDepthFunc(GL_LEQUAL); // Enable MultiSampling // glEnable(GL_MULTISAMPLE); // Enable face culling glEnable(GL_CULL_FACE); int bits; SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &bits); std::cout << "Stencil Size: " << bits << "\n"; return true; } void Renderer::initializeScreenObject() { // glGenVertexArrays(1, &screenObject.vertexArray); // glGenBuffers(1, &screenObject.vertexBuffer); // glGenBuffers(1, &screenObject.uvBuffer); // glBindVertexArray(screenObject.vertexArray); // glEnableVertexAttribArray(0); // glBindBuffer(GL_ARRAY_BUFFER, screenObject.vertexBuffer); // glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // // NDC Coords // std::vector<float> vertices = { // -1.0f, -1.0f, // 1.0f, -1.0f, // -1.0f, 1.0f, // 1.0f, 1.0f // }; // glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GL_FLOAT), vertices.data(), GL_STATIC_DRAW); // glEnableVertexAttribArray(1); // glBindBuffer(GL_ARRAY_BUFFER, screenObject.uvBuffer); // glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // std::vector<float> uvs = { // 0.0f, 0.0f, // 1.0f, 0.0f, // 0.0f, 1.0f, // 1.0f, 1.0f // }; // glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(GL_FLOAT), uvs.data(), GL_STATIC_DRAW); } void Renderer::addModel(std::shared_ptr<Model> model) { model->setProjectionAndViewMatrices(camera->getProjectionMatrix(), camera->getViewMatrix()); model->setLights(lights); models.push_back(model); } void Renderer::addLight(std::shared_ptr<Light> light) { lights.push_back(light); for (auto& model : models) { model->setLights(lights); } } void Renderer::updateCameraRotation(glm::vec3 r) { camera->addRotation(r); } void Renderer::render() { // --- UPDATE UNIFORMS --- if (camera->isDirty()) { for (auto& model : models) { model->setProjectionAndViewMatrices(camera->getProjectionMatrix(), camera->getViewMatrix()); } camera->setDirty(false); } // TODO(mfirmin): Check if lights are dirty for (auto& model : models) { model->setLights(lights); model->applyModelMatrix(); } // --- RENDER STENCIL/AURA --- { // Bind the aura/stencil buffer glBindFramebuffer(GL_FRAMEBUFFER, auraTarget->getFramebuffer()); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // render 1 to each fragment glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); // Clear the stencil buffer // always draw fragments regardless of stencil value glStencilFunc(GL_ALWAYS, 1, 0xFF); glStencilMask(0xFF); glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glDisable(GL_STENCIL_TEST); glStencilMask(0x00); // record depth into framebuffer // glDepthMask(GL_FALSE); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // draw all aura materials into DEPTH BUFFER ONLY for (auto& model : models) { model->draw(MaterialType::aura); } // then draw the stencil only where it passes the depth test glEnable(GL_STENCIL_TEST); glStencilMask(0xFF); for (auto& model : models) { model->draw(MaterialType::stencil); } glClear(GL_DEPTH_BUFFER_BIT); // then render the aura's color only where the stencil is valid glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // only render the aura where the stencil is glStencilFunc(GL_EQUAL, 1, 0xFF); // do not write to stencil glStencilMask(0x00); for (auto& model : models) { model->draw(MaterialType::aura); } glDisable(GL_STENCIL_TEST); } // --- RENDER SCENE --- { glBindFramebuffer(GL_FRAMEBUFFER, sceneTarget->getFramebuffer()); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for (auto& model : models) { model->draw(MaterialType::standard); } } // --- Composite and render to screen --- { glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); auraEffect->render(sceneTarget->getColorTexture(), auraTarget->getColorTexture()); } glUseProgram(0); // Swap SDL_GL_SwapWindow(window); }
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r8 push %r9 push %rax push %rcx push %rdi push %rsi lea addresses_D_ht+0x6fc6, %r9 nop add $16708, %rsi movl $0x61626364, (%r9) nop nop and %r9, %r9 lea addresses_UC_ht+0x75cc, %rsi lea addresses_WT_ht+0x12efb, %rdi nop add $51929, %rax mov $63, %rcx rep movsb nop nop nop nop and $4685, %rdi lea addresses_WC_ht+0x7249, %rax clflush (%rax) nop nop nop nop nop cmp $41520, %r8 vmovups (%rax), %ymm1 vextracti128 $0, %ymm1, %xmm1 vpextrq $1, %xmm1, %rcx nop nop inc %r8 lea addresses_WC_ht+0x1ccc, %r12 nop add %rdi, %rdi movb $0x61, (%r12) inc %rdi lea addresses_normal_ht+0x63cc, %rcx nop nop nop nop nop sub %rsi, %rsi movups (%rcx), %xmm2 vpextrq $1, %xmm2, %rdi xor $49734, %rax lea addresses_UC_ht+0x10214, %r12 nop nop add %rax, %rax vmovups (%r12), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $0, %xmm2, %rcx nop nop and %rcx, %rcx lea addresses_WT_ht+0x16e3c, %rsi lea addresses_UC_ht+0x4752, %rdi nop nop nop and $21886, %r13 mov $44, %rcx rep movsw nop nop and %rsi, %rsi lea addresses_A_ht+0x4f4c, %r9 nop sub $11331, %rcx movb (%r9), %r13b nop nop and $37692, %rcx lea addresses_WC_ht+0x19a44, %r12 nop nop nop nop nop xor %r13, %r13 movl $0x61626364, (%r12) nop nop nop nop nop cmp %r12, %r12 lea addresses_WT_ht+0x13821, %rax nop nop nop nop nop add %r12, %r12 movl $0x61626364, (%rax) nop nop cmp %rsi, %rsi pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r8 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r15 push %r9 push %rax push %rbp // Faulty Load lea addresses_D+0x1b9cc, %rax nop nop nop nop nop sub %r15, %r15 movb (%rax), %r10b lea oracles, %rbp and $0xff, %r10 shlq $12, %r10 mov (%rbp,%r10,1), %r10 pop %rbp pop %rax pop %r9 pop %r15 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4}} {'src': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_WT_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 1}} {'src': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_UC_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %rbx push %rcx push %rdi push %rsi lea addresses_WC_ht+0x153e2, %rsi lea addresses_WT_ht+0x64cb, %rdi nop nop nop and %r13, %r13 mov $95, %rcx rep movsw and %r10, %r10 lea addresses_UC_ht+0xdce2, %r12 nop nop nop dec %rdi mov $0x6162636465666768, %rsi movq %rsi, %xmm3 vmovups %ymm3, (%r12) nop nop inc %r10 lea addresses_normal_ht+0x72b2, %r12 nop cmp %rbx, %rbx mov (%r12), %rcx nop nop nop nop nop cmp $47703, %rdi lea addresses_normal_ht+0x74e2, %r12 nop nop nop nop inc %rcx mov (%r12), %r13d cmp %r13, %r13 lea addresses_UC_ht+0x17ee2, %rdi nop add $63215, %r12 movb (%rdi), %r10b xor $24756, %r13 lea addresses_normal_ht+0xce9d, %r12 nop nop nop nop nop and %r13, %r13 mov (%r12), %esi nop nop nop nop xor $50572, %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r14 push %r15 push %rbp push %rbx push %rdi push %rdx // Store lea addresses_UC+0x6003, %rbp nop nop nop nop add $10907, %r15 mov $0x5152535455565758, %r11 movq %r11, %xmm2 vmovups %ymm2, (%rbp) nop nop nop nop nop and %rbp, %rbp // Store lea addresses_WT+0xe9f6, %rbp nop and %rdi, %rdi movw $0x5152, (%rbp) nop xor %r11, %r11 // Store lea addresses_normal+0x13ce2, %rbx nop inc %r11 mov $0x5152535455565758, %rbp movq %rbp, (%rbx) dec %rdx // Faulty Load lea addresses_A+0x14e2, %rdi nop nop xor $3262, %r14 mov (%rdi), %bx lea oracles, %rdx and $0xff, %rbx shlq $12, %rbx mov (%rdx,%rbx,1), %rbx pop %rdx pop %rdi pop %rbx pop %rbp pop %r15 pop %r14 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': False, 'type': 'addresses_UC'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1, 'same': False, 'type': 'addresses_WT'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': True, 'type': 'addresses_A'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 0, 'same': True, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 11, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 11, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 9, 'same': True, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'00': 1, '35': 21828} 00 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
StatModifierRatios: ; first byte is numerator, second byte is denominator db 25, 100 ; 0.25 db 28, 100 ; 0.28 db 33, 100 ; 0.33 db 40, 100 ; 0.40 db 50, 100 ; 0.50 db 66, 100 ; 0.66 db 1, 1 ; 1.00 db 15, 10 ; 1.50 db 2, 1 ; 2.00 db 25, 10 ; 2.50 db 3, 1 ; 3.00 db 35, 10 ; 3.50 db 4, 1 ; 4.00
; A183978: 1/4 the number of (n+1) X 2 binary arrays with all 2 X 2 subblock sums the same. ; 4,6,9,15,25,45,81,153,289,561,1089,2145,4225,8385,16641,33153,66049,131841,263169,525825,1050625,2100225,4198401,8394753,16785409,33566721,67125249,134242305,268468225,536920065,1073807361,2147581953,4295098369 mov $1,1 mov $2,$0 lpb $2 mov $3,3 lpb $3 mul $1,2 mov $3,1 lpe add $1,$0 trn $0,2 sub $2,1 sub $1,$2 lpe add $1,3
#pragma once #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <inttypes.h> #include <signal.h> #include <rte_eal.h> #include <rte_ethdev.h> #include <rte_cycles.h> #include <rte_lcore.h> #include <rte_mbuf.h> #include <rte_log.h> #include <rte_ether.h> #include <rte_ip.h> #include <rte_tcp.h> #include <rte_udp.h> #include <rte_icmp.h> #include <string> #include <vector> #include <fstream> #include <istream> #include <sstream> #include <unordered_map> #include <vector> #include <atomic> #define MBUF_PER_POOL 65535 #define MBUF_POOL_CACHE_SIZE 250 #define RX_RING_SIZE 512 #define TX_RING_SIZE 512 namespace QDPDK { enum RET{ OK = 0, FAIL, }; template<typename T> class DeqInterface{ protected: T queue; public: DeqInterface(T q):queue(q){} uint16_t Dequeue(rte_mbuf** bufs, size_t size) = delete; }; template<> uint16_t DeqInterface<int>::Dequeue(rte_mbuf** bufs, size_t size){ return rte_eth_rx_burst(queue, 0, bufs, size); } template<> uint16_t DeqInterface<rte_ring*>::Dequeue(rte_mbuf** bufs, size_t size){ return rte_ring_sc_dequeue_burst(queue, (void**)bufs, size, NULL); }; template<typename T> class EnqInterface{ protected: T queue; public: EnqInterface(T q):queue(q){} uint16_t Enqueue(rte_mbuf** bufs, size_t n) = delete; }; template<> uint16_t EnqInterface<int>::Enqueue(rte_mbuf** bufs, size_t n){ uint16_t nb_tx = rte_eth_tx_burst(queue, 0, bufs, n); if (unlikely(nb_tx < n)) { for (auto buf = nb_tx; buf < n; buf++) rte_pktmbuf_free(bufs[buf]); } return nb_tx; }; template<> uint16_t EnqInterface<rte_ring*>::Enqueue(rte_mbuf** bufs, size_t n){ uint16_t nb_tx = rte_ring_sp_enqueue_burst(queue, (void**)bufs, n, NULL); if (unlikely(nb_tx < n)) { for (auto buf = nb_tx; buf < n; buf++) rte_pktmbuf_free(bufs[buf]); } return nb_tx; }; class App{ public: static std::atomic<bool> quit; static std::atomic<bool> start; static struct rte_eth_conf port_conf; protected: rte_mempool *mbuf_pool; int mempool_size; int num_ports; int core_cnt; public: App(int num_ports, int argc, char *argv[]) : num_ports(num_ports){ AppInit(argc, argv);}; RET Run(); template<class C> RET SetCore(C*); rte_ring* CreateRing(const char *name, unsigned count, int socket_id, unsigned flags); static void Signal_handler(int signum); private: RET PortInit(int); RET AppInit(int, char**); template<class C> static RET CoreLoop(C*); unsigned int get_available_lcore_id(); }; std::atomic<bool> App::quit = false; std::atomic<bool> App::start = false; struct rte_eth_conf App::port_conf; void App::Signal_handler(int signum){ if (signum == SIGINT || signum == SIGTERM) { quit = true; } } RET App::PortInit(int port) { const uint16_t rx_rings = 1, tx_rings = 1; uint16_t nb_rxd = RX_RING_SIZE; uint16_t nb_txd = TX_RING_SIZE; int retval; uint16_t q; port_conf.rxmode.max_rx_pkt_len = ETHER_MAX_LEN; if (port >= rte_eth_dev_count()) return FAIL; retval = rte_eth_dev_configure(port, rx_rings, tx_rings, &port_conf); if (retval != 0) return FAIL; retval = rte_eth_dev_adjust_nb_rx_tx_desc(port, &nb_rxd, &nb_txd); if (retval != 0) return FAIL; for (q = 0; q < rx_rings; q++) { retval = rte_eth_rx_queue_setup(port, q, nb_rxd, rte_eth_dev_socket_id(port), NULL, mbuf_pool); if (retval < 0) return FAIL; } for (q = 0; q < tx_rings; q++) { retval = rte_eth_tx_queue_setup(port, q, nb_txd, rte_eth_dev_socket_id(port), NULL); if (retval < 0) return FAIL; } retval = rte_eth_dev_start(port); if (retval < 0) return FAIL; struct ether_addr addr; rte_eth_macaddr_get(port, &addr); printf("Port %u MAC: %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8 "\n", port, addr.addr_bytes[0], addr.addr_bytes[1], addr.addr_bytes[2], addr.addr_bytes[3], addr.addr_bytes[4], addr.addr_bytes[5]); rte_eth_promiscuous_enable(port); return OK; } RET App::AppInit(int argc, char *argv[]) { int ret = rte_eal_init(argc, argv); if (ret < 0) rte_exit(EXIT_FAILURE, "Error with EAL initialization\n"); argc -= ret; argv += ret; int nb_ports = rte_eth_dev_count(); if (nb_ports < num_ports) rte_exit(EXIT_FAILURE, "Error: fewer ports than the bind ports.\n"); mbuf_pool = rte_pktmbuf_pool_create("mbuf_pool", MBUF_PER_POOL, MBUF_POOL_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id()); if (mbuf_pool == NULL) rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n"); for (int portid = 0; portid < nb_ports; portid++) if (PortInit(portid) != 0) rte_exit(EXIT_FAILURE, "Cannot init port %" PRIu16 "\n", portid); core_cnt = rte_lcore_count(); signal(SIGINT, Signal_handler); signal(SIGTERM, Signal_handler); return OK; } template<class C> RET App::SetCore(C *core) { rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "SETTING CORE.\n"); if (--core_cnt < 0) rte_exit(EXIT_FAILURE, "Error: fewer cores than the set cores.\n"); rte_eal_remote_launch((lcore_function_t *) CoreLoop<C>, core, get_available_lcore_id()); return OK; } rte_ring* App::CreateRing(const char *name, unsigned count, int socket_id, unsigned flags=RING_F_SP_ENQ|RING_F_SC_DEQ) { rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "CREATING RING.\n"); return rte_ring_create(name, count, socket_id, flags); } template<class C> RET App::CoreLoop(C *core){ while(not start) rte_delay_ms(10); rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "START lcore:%d\n", rte_lcore_id()); core->FirstCycle(); while(not quit){ core->Cycle(); } core->LastCycle(); rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "FINISH lcore:%d\n", rte_lcore_id()); return OK; } RET App::Run() { rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "START master\n"); start = true; rte_eal_mp_wait_lcore(); rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "FINISH master\n"); return OK; } unsigned int App::get_available_lcore_id() { static bool assigned[RTE_MAX_LCORE] = {false,}; for (uint i = RTE_MAX_LCORE - 1; i >= 0; i--){ if (!rte_lcore_is_enabled(i)){ continue; } if (i == rte_get_master_lcore()){ continue; } if (assigned[i]){ continue; } assigned[i] = true; return i; } return 0; } }
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %r14 push %r15 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x82ac, %r13 add %rbx, %rbx mov $0x6162636465666768, %r12 movq %r12, %xmm1 movups %xmm1, (%r13) nop nop nop nop dec %r13 lea addresses_D_ht+0x1afac, %rbx add $53501, %rbp mov (%rbx), %r14 nop nop nop nop nop add %rbx, %rbx lea addresses_normal_ht+0x1c6ac, %r11 nop cmp %r15, %r15 mov (%r11), %bp nop nop nop nop nop xor %r12, %r12 lea addresses_UC_ht+0x78ac, %r14 nop nop nop cmp %rbp, %rbp movb $0x61, (%r14) nop nop nop nop add %r14, %r14 lea addresses_WT_ht+0xc1fc, %rsi lea addresses_normal_ht+0x190ac, %rdi clflush (%rdi) nop nop nop nop dec %r14 mov $80, %rcx rep movsq nop nop nop nop nop add $55102, %rbp lea addresses_WT_ht+0x146c, %rsi lea addresses_A_ht+0x136ec, %rdi nop nop nop add $13224, %r11 mov $61, %rcx rep movsw nop dec %rdi lea addresses_normal_ht+0x1202c, %r12 nop nop nop nop nop add $64173, %r11 movl $0x61626364, (%r12) add $60179, %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r15 pop %r14 pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r9 push %rbp push %rbx push %rdi push %rdx push %rsi // Store lea addresses_WC+0x6fac, %rbx nop and %rdx, %rdx movw $0x5152, (%rbx) nop nop inc %r12 // Store lea addresses_PSE+0x157ac, %rbp nop nop nop xor %rdi, %rdi mov $0x5152535455565758, %rsi movq %rsi, (%rbp) nop nop nop nop and %rdx, %rdx // Load lea addresses_normal+0x1d3ac, %rdi and $59608, %rsi movb (%rdi), %dl nop xor %r9, %r9 // Faulty Load lea addresses_UC+0x1b6ac, %rbx add %rsi, %rsi movups (%rbx), %xmm5 vpextrq $1, %xmm5, %rdx lea oracles, %r9 and $0xff, %rdx shlq $12, %rdx mov (%r9,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rbx pop %rbp pop %r9 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 8}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 8}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 10}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 6}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 10}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 5}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 7}} {'37': 21829} 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 */
; A186350: Adjusted joint rank sequence of (f(i)) and (g(j)) with f(i) before g(j) when f(i)=g(j), where f and g are the odd numbers and the triangular numbers. Complement of A186351. ; 1,3,5,7,8,10,11,12,14,15,16,18,19,20,22,23,24,25,27,28,29,30,31,33,34,35,36,37,39,40,41,42,43,45,46,47,48,49,50,52,53,54,55,56,57,58,60,61,62,63,64,65,66,68,69,70,71,72,73,74,76,77,78,79,80,81,82,83,85,86,87,88,89,90,91,92,93,95,96,97,98,99,100,101,102,103,105,106,107,108,109,110,111,112,113,115,116,117,118,119,120,121,122,123,124,126,127,128,129,130,131,132,133,134,135,136,138,139,140,141 mov $1,$0 mov $2,$0 add $2,$0 mov $3,1 lpb $2 sub $2,$3 trn $2,1 add $3,1 lpe add $1,$3
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>add_key(type, description, payload, plen, keyring) -> str Invokes the syscall add_key. See 'man 2 add_key' for more information. Arguments: type(char*): type description(char*): description payload(void*): payload plen(size_t): plen keyring(key_serial_t): keyring Returns: key_serial_t </%docstring> <%page args="type=0, description=0, payload=0, plen=0, keyring=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = ['type', 'description', 'payload'] can_pushstr_array = [] argument_names = ['type', 'description', 'payload', 'plen', 'keyring'] argument_values = [type, description, payload, plen, keyring] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_add_key']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* add_key(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
#include "Associativity.h" #include "AutoScheduleUtils.h" #include "Bounds.h" #include "CPlusPlusMangle.h" #include "CSE.h" #include "CodeGen_C.h" #include "CodeGen_PyTorch.h" #include "CodeGen_X86.h" #include "Deinterleave.h" #include "Func.h" #include "Generator.h" #include "IR.h" #include "IREquality.h" #include "IRMatch.h" #include "IRPrinter.h" #include "Interval.h" #include "ModulusRemainder.h" #include "Monotonic.h" #include "Reduction.h" #include "Solve.h" #include "UniquifyVariableNames.h" using namespace Halide; using namespace Halide::Internal; int main(int argc, const char **argv) { IRPrinter::test(); CodeGen_C::test(); // CodeGen_PyTorch::test(); ir_equality_test(); bounds_test(); expr_match_test(); deinterleave_vector_test(); modulus_remainder_test(); cse_test(); solve_test(); target_test(); cplusplus_mangle_test(); is_monotonic_test(); split_predicate_test(); associativity_test(); generator_test(); propagate_estimate_test(); uniquify_variable_names_test(); printf("Success!\n"); return 0; }
; A002055: Number of diagonal dissections of a convex n-gon into n-4 regions. ; 1,9,56,300,1485,7007,32032,143208,629850,2735810,11767536,50220040,212952285,898198875,3771484800,15775723920,65770848990,273420862110,1133802618000,4691140763400,19371432850770,79850555673174,328627887379776,1350540667070000,5543004766417300 mov $3,$0 add $0,2 mov $1,$0 add $1,$0 bin $1,$3 mov $2,2 lpb $0,1 mul $1,$0 sub $0,6 mul $1,3 add $2,1 add $1,$2 add $4,$3 add $5,$4 trn $0,$5 lpe sub $1,9 div $1,6 add $1,1
Name: ys_w25.asm Type: file Size: 21980 Last-Modified: '2016-05-13T04:51:15Z' SHA-1: 5B2DA954BD88EC94AA327515E8EA9E3A44075AF6 Description: null
; A318876: Sum of divisors d of n for which 2*phi(d) > d. ; 1,1,4,1,6,4,8,1,13,6,12,4,14,8,24,1,18,13,20,6,32,12,24,4,31,14,40,8,30,24,32,1,48,18,48,13,38,20,56,6,42,32,44,12,78,24,48,4,57,31,72,14,54,40,72,8,80,30,60,24,62,32,104,1,84,48,68,18,96,48,72,13,74,38,124,20,96,56,80,6,121,42,84,32,108,44,120,12,90,78,112,24,128,48,120,4,98,57,156,31 add $0,1 mov $2,$0 lpb $0 mov $3,$2 dif $3,$0 cmp $3,$2 cmp $3,0 mul $3,$0 sub $0,1 lpb $3,$3 add $1,$3 mod $3,2 lpe lpe add $1,1 mov $0,$1
; A004756: Binary expansion starts 100. ; 4,8,9,16,17,18,19,32,33,34,35,36,37,38,39,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292 mov $1,$0 mov $2,3 lpb $1 sub $1,1 div $1,2 mul $2,2 lpe add $0,$2 add $0,1
// 1655. 가운데를 말해요 // 2019.09.26 // 힙 #include<iostream> #include<queue> #include<algorithm> using namespace std; priority_queue<int, vector<int>, less<int>> maxHeap; // 최대 힙 priority_queue<int, vector<int>, greater<int>> minHeap; // 최소 힙 int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, num; cin >> n; while (n-- > 0) { cin >> num; // 두 힙의 크기가 같다면 최대힙에 추가 if (maxHeap.size() == minHeap.size()) { maxHeap.push(num); } // 그렇지 않다면 최소힙에 추가 else { minHeap.push(num); } // 두 힙이 비어있지 않고 최대힙의 첫번째 원소가 최소힙의 첫번째 원소보다 클때 서로 위치를 바꿔준다. if (!maxHeap.empty() && !minHeap.empty() && (maxHeap.top() > minHeap.top())) { int max = maxHeap.top(); int min = minHeap.top(); maxHeap.pop(); minHeap.pop(); maxHeap.push(min); minHeap.push(max); } // 항상 최대힙의 첫번째 원소를 출력한다. cout << maxHeap.top() << "\n"; } return 0; }
#ifndef STAN_MATH_PRIM_MAT_FUN_DIAG_POST_MULTIPLY_HPP #define STAN_MATH_PRIM_MAT_FUN_DIAG_POST_MULTIPLY_HPP #include <stan/math/prim/mat/err/check_vector.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> namespace stan { namespace math { template <typename T1, typename T2, int R1, int C1, int R2, int C2> Eigen::Matrix<return_type_t<T1, T2>, R1, C1> diag_post_multiply( const Eigen::Matrix<T1, R1, C1>& m1, const Eigen::Matrix<T2, R2, C2>& m2) { check_vector("diag_post_multiply", "m2", m2); check_size_match("diag_post_multiply", "m2.size()", m2.size(), "m1.cols()", m1.cols()); return m1 * m2.asDiagonal(); } } // namespace math } // namespace stan #endif
#include "CppUnitTest.h" #include "resourcemanager.hpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace GardenVexor_unittest { TEST_CLASS(UnitTest1) { public: TEST_METHOD(TestMethod1) { ResourceManager::initialize(); } }; }
asr(8) g13<1>.xD g5.4<0>.zD g5.4<0>.wUD { align16 1Q }; asr(8) g57<1>.xD g38<4>.xD 0x00000001UD { align16 1Q }; asr(8) g3<1>D g2<0,1,0>D g2.1<0,1,0>UD { align1 1Q }; asr(16) g3<1>D g2<0,1,0>D g2.1<0,1,0>UD { align1 1H }; asr(8) g6<1>D g5<8,8,1>D 0x00000001UD { align1 1Q }; asr(16) g8<1>D g6<8,8,1>D 0x00000001UD { align1 1H }; asr(8) g4<1>.xD g14<4>.xD 0x00000010UD { align16 NoDDClr 1Q }; asr(8) g4<1>.yD g1<0>.xD 0x00000010UD { align16 NoDDChk 1Q }; asr.nz.f0.0(8) null<1>D -g0<0,1,0>W 15D { align1 1Q }; asr.nz.f0.0(16) null<1>D -g0<0,1,0>W 15D { align1 1H }; asr(8) g2<1>D -g0<0,1,0>W 15D { align1 1Q }; asr(16) g2<1>D -g0<0,1,0>W 15D { align1 1H };
; unsigned char ulap_attr_from_pentp_penti(unsigned char pentp,unsigned char penti) SECTION code_clib SECTION code_arch PUBLIC asm_ulap_attr_from_pentp_penti asm_ulap_attr_from_pentp_penti: ; enter : l = unsigned char pentp ; h = unsigned char penti ; ; exit : l = attribute value ; ; uses : af, hl ld a,h and $07 ld h,a ld a,l add a,a add a,a ld l,a and $c0 or h ld h,a ld a,l add a,a and $38 or h ld l,a ret
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; WriteCr4.Asm ; ; Abstract: ; ; AsmWriteCr4 function ; ; Notes: ; ;------------------------------------------------------------------------------ .586p .model flat,C .code ;------------------------------------------------------------------------------ ; UINTN ; EFIAPI ; AsmWriteCr4 ( ; UINTN Cr4 ; ); ;------------------------------------------------------------------------------ AsmWriteCr4 PROC mov eax, [esp + 4] mov cr4, eax ret AsmWriteCr4 ENDP END
; encoding: utf-8 ; ff3_field_window_renderer.asm ; ; description: ; replaces field::draw_window_box($3f:ed02) related codes. ; this file implements 'renderer'-like logics, ; which renders window's content given by the callers by driving ppu. ; these logics are originally placed around $f40a-$f700. ; version: ; 0.1.0 ;================================================================================================== ff3_field_window_renderer_begin: .ifdef _OPTIMIZE_FIELD_WINDOW INIT_PATCH_EX field.window.ppu, $3f, $f40a, $f44b, textd.BULK_PATCH_FREE_BEGIN .ifndef _FEATURE_DEFERRED_RENDERING ;;# $3f:f40a field.set_vram_addr_for_window ;;### args: ;;+ [in] u8 $3a : x offset ;;+ [in] u8 $3b : y offset ;; ;;### callers: ;;`1F:F6B2:20 0A F4 JSR $F40A` @ $3f:f6aa field.upload_window_content ;;`1F:F6CE:20 0A F4 JSR $F40A` @ $3f:f6aa field.upload_window_content ;;`1F:F6E9:20 0A F4 JSR $F40A` @ $3f:f6aa field.upload_window_content ;;`1F:F705:20 0A F4 JSR $F40A` @ $3f:f6aa field.upload_window_content field.set_vram_addr_current_xy ;;$f40a .offsetX = $3a ldy <.offsetX field_x.set_vram_addr_current_y_with_specified_x ;[in] y : x offset ;[in] $3b : y offset ;[out] y : (offsetX & #$20) ^ #$20 ;[in] .offsetX = $3a .offsetY = $3b ;[ref] .vramAddrLow = $f4a1 .vramAddrHigh = $f4c1 ;-------------------------------------- tya pha ldy <.offsetY and #$20 tax beq .left_on_1st_bg lda #$04 .left_on_1st_bg: ora .vramAddrHigh,y sta $2006 pla and #$1f ora .vramAddrLow,y sta $2006 ;x = left & #20 txa eor #$20 tay rts .endif ;;_FEATURE_DEFERRED_RENDERING ;;field.get_vram_addr_of_line_above: ;; DECLARE_WINDOW_VARIABLES ;; ldx <.offset_y ; F435 A6 3B ;; dex ; F437 CA ;; bpl .positive ; F438 10 02 ;; ldx <.offset_y ; F43A A6 3B ;;.positive: ;; lda <.offset_x ; F43C A5 3A ;; and #$1F ; F43E 29 1F ;; ora $F4A1,x ; F440 1D A1 F4 ;; sta <$54 ; F443 85 54 ;; lda $F4C1,x ; F445 BD C1 F4 ;; sta <$55 ; F448 85 55 ;; rts ; F44A 60 field.window.ppu.FREE_BEGIN: VERIFY_PC_TO_PATCH_END field.window.ppu .endif ;;_OPTIMIZE_FIELD_WINDOW ;================================================================================================== .ifdef _OPTIMIZE_FIELD_WINDOW ;INIT_PATCH_EX menu.erase, $3f, $f44b, $f4a1, $f44b INIT_PATCH_EX menu.erase, $3f, $f44b, $f4a1, field.window.ppu.FREE_BEGIN ;; 1E:AA8E:20 4B F4 JSR $F44B menu.savefile.erase_window: ;;F44B FIX_ADDR_ON_CALLER $3d,$aa8e+1 ;; DECLARE_WINDOW_VARIABLES lda #$02 ; F44B A9 02 sta <.window_top ; F44D 85 39 sta <.offset_y ; F44F 85 3B lda #$09 ; F451 A9 09 sta <.window_left ; F453 85 38 lda #$16 ; F455 A9 16 sta <.window_width ; F457 85 3C lda #$04 ; F459 A9 04 sta <.window_height ; F45B 85 3D lda #$02 ; F45D A9 02 bne menu.erase_box_from_bottom ; F45F D0 19 ;-------------------------------------------------------------------------------------------------- ;; 1E:AF76:20 61 F4 JSR $F461 menu.erase_box_1e_x_14: FIX_ADDR_ON_CALLER $3d,$af76+1 ;; lda #$14 ; F461 A9 14 bne menu.erase_box_of_width_1e ; F463 D0 02 ;-------------------------------------------------------------------------------------------------- ;; 1E:A693:4C 65 F4 JMP $F465 menu.erase_box_1e_x_1c: FIX_ADDR_ON_CALLER $3d,$a693+1 ;; DECLARE_WINDOW_VARIABLES lda #$1C ; F465 A9 1C FALL_THROUGH_TO menu.erase_box_of_width_1e ;-------------------------------------------------------------------------------------------------- ;; 1E:9BD2:20 67 F4 JSR $F467 menu.erase_box_of_width_1e: FIX_ADDR_ON_CALLER $3c,$9bd2+1 ;; DECLARE_WINDOW_VARIABLES sta <.window_height ; F467 85 3D lda #$1B ; F469 A9 1B sta <.window_top ; F46B 85 39 sta <.offset_y ; F46D 85 3B lda #$01 ; F46F A9 01 sta <.window_left ; F471 85 38 lda #$1E ; F473 A9 1E sta <.window_width ; F475 85 3C lda <.window_height ; F477 A5 3D lsr a ; F479 4A FALL_THROUGH_TO menu.erase_box_from_bottom ;-------------------------------------------------------------------------------------------------- ;; in: ;; A: width menu.erase_box_from_bottom: DECLARE_WINDOW_VARIABLES .ifdef _FEATURE_DEFERRED_RENDERING ldx #(render_x.NO_BORDERS|render_x.PENDING_INIT|render_x.RENDER_RUNNING) jsr render_x.setup_deferred_rendering ;;this function preserves A. .endif .erase_loop: pha ; F47A 48 lda <.window_width ; F47B A5 3C sta <.output_index ; F47D 85 90 sta <.width_in_1st ; F47F 85 91 ; ldy #$1D ; F481 A0 1D ; lda #$00 ; F483 A9 00 ;.l_F485: ; sta $0780,y ; F485 99 80 07 ; sta $07A0,y ; F488 99 A0 07 ; dey ; F48B 88 ; bpl .l_F485 ; F48C 10 F7 ;;as `field.draw_window_content` fill up the buffer with default background, ;;it is needed to fill up with '0' for each time. lda #0 jsr field_x.fill_tile_buffer_with jsr field.draw_window_content ; F48E 20 92 F6 lda <.offset_y ; F491 A5 3B sec ; F493 38 sbc #$04 ; F494 E9 04 sta <.offset_y ; F496 85 3B pla ; F498 68 sec ; F499 38 sbc #$01 ; F49A E9 01 ;bne menu.erase_box_from_bottom ; F49C D0 DC bne .erase_loop .ifdef _FEATURE_DEFERRED_RENDERING jsr render_x.finalize .endif jmp field.restore_banks ; F49E 4C F5 EC VERIFY_PC_TO_PATCH_END menu.erase menu.erase.FREE_BEGIN: .endif ;;_OPTIMIZE_FIELD_WINDOW ;================================================================================================== .ifdef _OPTIMIZE_FIELD_WINDOW INIT_PATCH_EX field.window.renderer,$3f,$f670,$f727,$f670 field_x.get_available_width_in_bg: DECLARE_WINDOW_VARIABLES ;.left = $38 ;.width = $3c ;; if window across BG boundary (left + width >= 0x20) ;; then adjust the width to fit just enough to the BG lda <.window_left FALL_THROUGH_TO field_x.calc_available_width_in_bg ;; in ;; A : box left render_x.calc_available_width_in_bg DECLARE_WINDOW_VARIABLES and #$1f ;take mod of 0x20 to wrap around eor #$1f ;negate... clc ; adc #1 ;...done. A = (0x20 - left) % 0x20 cmp <.window_width bcc .store_result ;; there is enough space to draw entirely lda <.window_width .store_result: rts ;-------------------------------------------------------------------------------------------------- ;;callers: ;; 1F:ECE9:20 70 F6 JSR field::calc_size_and_init_buff @ $3f:ece5 field::draw_window_top ;; 1F:EEDB:20 70 F6 JSR field::calc_size_and_init_buff @ $3f:eec0 field::draw_string_in_window field.calc_draw_width_and_init_window_tile_buffer: ;; patch out callers { ;FIX_ADDR_ON_CALLER $3f,$eedb+1 ;; } ;;[in] ;.left = $38 ;.width = $3c .width_for_current_bg = $91 jsr field_x.get_available_width_in_bg .store_result: sta <.width_for_current_bg ;; fall through into $3f:f683 field::init_window_tile_buffer ;-------------------------------------------------------------------------------------------------- ;;$3f:f683 field::init_window_tile_buffer: ;;caller: ;; $3f:f692 field.draw_window_content field.init_window_tile_buffer: ;;[in] ;.tiles_1st = $0780 ;.tiles_2nd = $07a0 ;$f683 ; a = #ff ; for (y = #1d;y >= 0;y--) { ; $0780,y = a; ; $07a0,y = a; ; } ; clc; ; return; ;$f692: lda #$ff field_x.fill_tile_buffer_with: .tile_buffer = $0780 ;ldy #$1d ldy #$3d .copy_loop: sta .tile_buffer,y ;sta .tiles_2nd,y dey bpl .copy_loop clc rts ;VERIFY_PC $f692 ;-------------------------------------------------------------------------------------------------- ;INIT_PATCH $3f,$f692,$f6aa ;;$3f:f692 field::draw_window_content ;; [in] ;; u8 a: rendering disposition. ;; u8 $f0: frame_counter ;; u8 $93: per8k bank ;;callers: ;; 1F:EEE9:20 92 F6 JSR field::draw_window_content @ $3f:eec0 field.draw_string_in_window ;; 1F:EF49:20 92 F6 JSR field::draw_window_content @ $3f:eefa textd.draw_in_box ;; 1F:EFDE:20 92 F6 JSR field::draw_window_content @ ? (sub routine of $eefa) ;; 1F:F48E:20 92 F6 JSR field::draw_window_content @ $3f:f47a menu.erase_box_from_bottom field.draw_window_content: ;; patch out external callers { ;FIX_ADDR_ON_CALLER $3f,$eee9+1 ;FIX_ADDR_ON_CALLER $3f,$ef49+1 ;FIX_ADDR_ON_CALLER $3f,$efde+1 ;FIX_ADDR_ON_CALLER $3f,$f48e+1 ;;} DECLARE_WINDOW_VARIABLES .output_index = $90 ;; --- .ifndef _FEATURE_DEFERRED_RENDERING pha jsr waitNmiBySetHandler ;ff00 inc <field.frame_counter pla jsr field.upload_window_content ;f6aa jsr field_x.end_ppu_update ;sync_ppu_scroll+call_sound_driver jsr field_x.switch_to_text_bank jmp field.init_window_tile_buffer ;f683 .else ;_FEATURE_DEFERRED_RENDERING ;; 1. if required, capture attribute and write it into the buffer. ;; 2. composite borders with content. ;; 3. write the result into the buffer. ;; 4. update number of available bytes to notify it of renderer. tax lda render_x.q.init_flags and #(render_x.RENDER_RUNNING) beq .oops lda <.lines_drawn pha txa pha .composite_top: lda render_x.q.init_flags ;; mask off init-pending flag and #(~render_x.PENDING_INIT) sta render_x.q.init_flags bmi .composite_middle ;; queue top border tax and #(render_x.NEED_TOP_BORDER) beq .composite_middle txa and #(~render_x.NEED_TOP_BORDER) sta render_x.q.init_flags jsr render_x.queue_top_border .composite_middle: pla ;; A <-- rendering disposition. cmp #textd.WANT_ONLY_LOWER beq .lower_half lda #0 jsr render_x.queue_content .lower_half: lda #$20 jsr render_x.queue_content .composite_bottom: ;; note: ;; on next nmi the handler will be executed in somewhere ;; in another function sit on top of this function, ;; at arbitrary context. ;; therefore the handler never could safely destory ;; any values neither in regsiters nor memory. ;; this also implies the following restrictions apply to all of the callers: ;; 1) if a caller removes the handler, ;; then rest of contents pending rendering will be discarded. ;; 2) if a caller re-initilizes the queue this function utilizes, ;; before the handler executed, then the handler will see ;; unintentional re-init'd values and probably result in system crash. jsr render_x.set_deferred_renderer ;; ldy <.lines_drawn cpy <.window_height bne .update_queue_status ldx render_x.q.init_flags txa and #render_x.NEED_BOTTOM_BORDER beq .finalize_this_rendering ;; queue bottom border dex stx render_x.q.init_flags jsr render_x.queue_bottom_border .finalize_this_rendering: jsr render_x.finalize .update_queue_status: pla sta <.lines_drawn ;restore the original ;; reset output index. callers rely on this to continue parse lda #0 sta <.output_index ;;originally, 'field.upload_window_content's role jsr field_x.switch_to_text_bank jmp field.init_window_tile_buffer .oops: brk .endif ;;_FEATURE_DEFERRED_RENDERING ;-------------------------------------------------------------------------------------------------- .ifdef _FEATURE_DEFERRED_RENDERING render_x.fill_to_bottom.loop: .lines_drawn = $1f .window_height = $3d ldx #textd.WANT_ONLY_LOWER lsr A beq .do_half ldx #0 .do_half: txa FALL_THROUGH_TO render_x.fill_to_bottom render_x.fill_to_bottom: .lines_drawn = $1f .window_height = $3d .p_text = $3e pha jsr field.draw_window_content pla tax ;; XXX: ;; there no need to check the text end since ;; this call is made only under situations that is ;; safe and right to fill up to the bottom of window. ;; there are cases even if the text hasn't been read thru the end ;; but still need to fill, namely cases that ;; the following charcodes aborts processing due to empty item: ;; CHARCODE.ITEM_NAME_IN_SHOP (0x19) ;; CHARCODE.JOB_NAME (0x1e) ;; --------- ;; checks if this call is made on the text end ;ldy #0 ;lda [.p_text],y ;bne .done inc <.lines_drawn cpx #textd.WANT_ONLY_LOWER beq .test_end inc <.lines_drawn .test_end: lda <.window_height sec sbc <.lines_drawn bne render_x.fill_to_bottom.loop .done: rts ;-------------------------------------------------------------------------------------------------- render_x.draw_empty_box: DECLARE_WINDOW_VARIABLES ;; draw empty box by just rendering an empty string and fill up the box. ;; the trick here is set 0(CHAR.NUL) to both as a bank number and high byte of pointer. ;; [ptr] = $0093, [$0093] == CHAR.NUL / bank #0 lda #0 sta <.text_bank sta <.p_text+1 lda #.text_bank sta <.p_text jmp render_x.defer_window_text_with_border .endif ;;_FEATURE_DEFERRED_RENDERING ;-------------------------------------------------------------------------------------------------- ;VERIFY_PC $f6aa ;-------------------------------------------------------------------------------------------------- .ifndef _FEATURE_DEFERRED_RENDERING ;$3f:f6aa field::upload_window_content ;// [in] u8 $38 : offset x ;// [in] u8 $39 : offset per 2 line ;// [in,out] u8 $3b : offset y (wrap-around) ;; call tree: ;; $eb43: ? ;; $eec0: field.draw_string_in_window ;; $eefa: textd.draw_in_box ;; $f692: field.draw_window_content ;; ;; $ed02: field.draw_window_box ;; $edc6: field.draw_window_row ;;callers: ;; $3f:edc6 field.draw_window_row ;; $3f:f692 field.draw_window_content field.upload_window_content: DECLARE_WINDOW_VARIABLES cmp #textd.WANT_ONLY_LOWER beq .draw_lower_line lda #0 jsr .draw_line .draw_lower_line: lda #$20 .draw_line: ;[in] a = index offset pha sta <.offset_x bit $2002 lda <.width_in_1st ldy <.window_left jsr field_x.upload_tiles ;[out] y = offsetX & #20 ^ #20, $3a = offsetString clc pla adc <.window_width sec sbc <.offset_x bcc .next_line beq .next_line jsr field_x.upload_tiles .next_line: ldy <.offset_y iny cpy #30 bne .no_wrap ldy #0 .no_wrap: sty <.offset_y lda #0 sta <.output_index rts ;; in: ;; Y : vram high field_x.upload_tiles: DECLARE_WINDOW_VARIABLES pha jsr field_x.set_vram_addr_current_y_with_specified_x ;.beginOffset = .offsetString ;.endOffset = .beginOffset pla ;widthInCurrentBg ldx <.offset_x pha clc adc <.offset_x sta <.offset_x pla lsr a ror a bpl .length_even ;odd .length_odd: bcc .copy_loop_1 bcs .copy_loop_3 ;even .length_even: bcs .copy_loop_2 .copy_loop_0: lda .tile_buffer_upper,x sta $2007 inx .copy_loop_3: lda .tile_buffer_upper,x sta $2007 inx .copy_loop_2: lda .tile_buffer_upper,x sta $2007 inx .copy_loop_1: lda .tile_buffer_upper,x sta $2007 inx cpx <.offset_x bne .copy_loop_0 rts .endif ;;ifndef _FEATURE_DEFERRED_RENDERING ;VERIFY_PC $f727 VERIFY_PC_TO_PATCH_END field.window.renderer ;-------------------------------------------------------------------------------------------------- .endif ;;_OPTIMIZE_FIELD_WINDOW ;====================================================================================================== RESTORE_PC ff3_field_window_driver_begin
; A118263: a(3n) = 2^n, a(3n+1) = 3^n, a(3n+2) = 4^n. ; 1,1,1,2,3,4,4,9,16,8,27,64,16,81,256,32,243,1024,64,729,4096,128,2187,16384,256,6561,65536,512,19683,262144,1024,59049,1048576,2048,177147,4194304,4096,531441,16777216,8192,1594323,67108864,16384,4782969,268435456,32768,14348907,1073741824,65536,43046721,4294967296,131072,129140163,17179869184,262144,387420489,68719476736,524288,1162261467,274877906944,1048576,3486784401,1099511627776,2097152,10460353203,4398046511104,4194304,31381059609,17592186044416,8388608,94143178827,70368744177664,16777216,282429536481,281474976710656,33554432,847288609443,1125899906842624,67108864,2541865828329,4503599627370496,134217728,7625597484987 sub $0,1 lpb $0 mov $3,$0 sub $0,3 mov $1,$3 add $2,1 lpe pow $1,$2
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Om developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xdb; pchMessageStart[1] = 0xb4; pchMessageStart[2] = 0x0e; pchMessageStart[3] = 0xce; vAlertPubKey = ParseHex("047c92d8ebf2357e69135fec4aad0a2375cf56451151acc97347dbcdeb12fc1b8f5afcc34310ee2166f95ad26c3917b349a05f1410be5773794dd661f4013de408"); nDefaultPort = 9229; nRPCPort = 9230; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 32); nSubsidyHalvingInterval = 210000; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1480084209, nBits=1d00ffff, nNonce=0, vtx=1) // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) // vMerkleTree: 4a5e1e const char* pszTimestamp = "Phys.org New 3D structure shows optimal way to divide space"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1480084209; genesis.nBits = 0x1d00ffff; genesis.nNonce = 1736219647; hashGenesisBlock = genesis.GetHash(); if (false) { printf("Searching for genesis block...\n"); uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256(); uint256 thash; CBigNum bnTarget; bnTarget.SetCompact(genesis.nBits); while(1) { thash=genesis.GetHash(); if ((thash <= hashTarget) && (thash <= bnTarget.getuint256()) ) break; if ((genesis.nNonce & 0xFFF) == 0) { printf("nonce %08X: hash = %s (target = %s)\n",genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } printf("genesis.nTime = %u \n",genesis.nTime); printf("genesis.nNonce = %u \n",genesis.nNonce); printf("min nBit: %08x\n", bnProofOfWorkLimit.GetCompact()); printf("genesis.hashMerkleRoot = %s\n",genesis.hashMerkleRoot.ToString().c_str()); printf("genesis.GetHash = %s\n",genesis.GetHash().ToString().c_str()); exit(1); } assert(hashGenesisBlock == uint256("0x00000000f8bc3f32f2ac9c2d09ef2cbbcada74c57e76a0ea814b39bb0044b5db")); assert(genesis.hashMerkleRoot == uint256("0xde3b9a26538cbebd33ca1a7b63eb1293cb6dd11a4289b07067bf9e4f337ac12f")); vSeeds.push_back(CDNSSeedData("walletbuilders.com", "node.walletbuilders.com")); base58Prefixes[PUBKEY_ADDRESS] = list_of(80); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(208); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64 nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x14; pchMessageStart[1] = 0x2d; pchMessageStart[2] = 0xb0; pchMessageStart[3] = 0x8e; vAlertPubKey = ParseHex("0488cf68444bd88b74446d3602b6c8f4f5a04735d80736a94004fadda2b3a2d86de00ab42286545a559b636f7edbf791fb0a44c7e3d12244346a5c88b98402581c"); nDefaultPort = 19229; nRPCPort = 19230; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1480084209; genesis.nNonce = 1736219647; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000000f8bc3f32f2ac9c2d09ef2cbbcada74c57e76a0ea814b39bb0044b5db")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0x39; pchMessageStart[1] = 0xba; pchMessageStart[2] = 0x57; pchMessageStart[3] = 0xbd; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1480084209; genesis.nBits = 0x207fffff; genesis.nNonce = 2; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; }
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This transformation pass takes ops with the same `_tpu_replicate` attribute // in a block and clusters them together under a `tf_device.cluster`. // Associated TPUReplicateMetadata ops are removed and its attributes are copied // over to the associated `tf_device.cluster`. If a cluster should be // replicated, the associated `tf_device::LaunchOp` will be wrapped further with // a `tf_device.replicate`. This pass also assumes ops of the same cluster do // not have ops outside of the cluster that are both operands and results of the // cluster. Note, this currently does not handle side effecting ops yet. #include <algorithm> #include <iterator> #include <memory> #include <tuple> #include <utility> #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Casting.h" #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/Identifier.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/IR/Types.h" // from @llvm-project #include "mlir/IR/Value.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Pass/PassRegistry.h" // from @llvm-project #include "mlir/Support/LogicalResult.h" // from @llvm-project #include "mlir/Transforms/RegionUtils.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/analysis/resource_alias_analysis.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" namespace mlir { namespace TFTPU { namespace { constexpr char kTPUReplicateAttr[] = "_tpu_replicate"; constexpr char kDeviceAttr[] = "device"; constexpr char kNameAttr[] = "name"; constexpr char kNumReplicasAttr[] = "num_replicas"; constexpr char kReplicatedInputIndicesAttr[] = "_replicated_input_indices"; constexpr char kMirroredVariableIndicesAttr[] = "_mirrored_variable_indices"; constexpr char kBadTPUReplicateAttrMsg[] = "requires '_tpu_replicate' string attribute"; // Mapping for `_tpu_replicate` attribute to TPUReplicateMetadata attributes. using MetadataMap = llvm::SmallDenseMap<llvm::StringRef, MutableDictionaryAttr, 8>; // A set of operations in a cluster. using ClusterOps = llvm::SmallSetVector<Operation*, 8>; // Mapping for `_tpu_replicate` attribute to ops of a cluster. using ClusterMap = llvm::SmallDenseMap<llvm::StringRef, ClusterOps, 8>; struct TPUClusterFormation : public TF::PerFunctionAggregateAnalysisConsumerPass< TPUClusterFormation, TF::ResourceAliasAnalysis> { void getDependentDialects(DialectRegistry& registry) const override { registry.insert<tf_device::TensorFlowDeviceDialect>(); } void runOnFunction( FuncOp func, const TF::ResourceAliasAnalysis::Info& resource_alias_analysis); }; // Creates a mapping from the TPUReplicateMetadata ops `_tpu_replicate` // attribute to its attributes and removes the ops. If multiple // TPUReplicateMetadata ops have the same `_tpu_replicate` attribute, an error // will be returned. LogicalResult CollectMetadata(Block* block, MetadataMap* metadata_map) { // Just look at top-level operations in the block (not nested ones) for (Operation& op : llvm::make_early_inc_range(*block)) { auto metadata_op = dyn_cast<TF::TPUReplicateMetadataOp>(op); if (!metadata_op) continue; MutableDictionaryAttr attrs = metadata_op.getAttrs(); // Missing or bad `_tpu_replicate` attribute. auto tpu_replicate_attr = attrs.get(kTPUReplicateAttr); if (!tpu_replicate_attr) return metadata_op.emitError() << kBadTPUReplicateAttrMsg; auto tpu_replicate_attr_str = tpu_replicate_attr.dyn_cast<StringAttr>(); if (!tpu_replicate_attr_str || tpu_replicate_attr_str.getValue().empty()) return metadata_op.emitError() << kBadTPUReplicateAttrMsg; // Remove `name` attribute. attrs.remove(Identifier::get(kNameAttr, metadata_op.getContext())); auto it = metadata_map->try_emplace(tpu_replicate_attr_str.getValue(), std::move(attrs)); // There are multiple TPUReplicateMetadata ops with the same // `_tpu_replicate` attribute. if (!it.second) { return metadata_op.emitError() << "multiple TPUReplicateMetadata ops with the same '" << kTPUReplicateAttr << "' attribute '" << tpu_replicate_attr_str.getValue() << "' found"; } metadata_op.erase(); } return success(); } // Collects and clusters ops with the same `_tpu_replicate` attribute. This will // return an error if a `_tpu_replicate` attribute of an op is empty. LogicalResult CollectAndGroupClusterOps(Block* block, ClusterMap* clusters) { for (Operation& op : *block) { if (auto attr = op.getAttrOfType<StringAttr>(kTPUReplicateAttr)) { if (attr.getValue().empty()) return op.emitError() << "attribute '" << kTPUReplicateAttr << "' is empty"; auto it = clusters->try_emplace(attr.getValue()); it.first->getSecond().insert(&op); } } return success(); } // Collects all resource ids from an op. void CollectResourceIdsFromOp( Operation& op, const TF::ResourceAliasAnalysis::Info& resource_alias_analysis, llvm::SmallDenseSet<int64_t>& observed_resource_ids) { op.walk([&](Operation* inner_op) { for (Value operand : TF::filter_resources(inner_op->getOperands())) { if (resource_alias_analysis.IsUnknownResource(operand)) continue; const auto& ids = resource_alias_analysis.GetResourceUniqueIds(operand); observed_resource_ids.insert(ids.begin(), ids.end()); } for (Value result : TF::filter_resources(inner_op->getResults())) { if (resource_alias_analysis.IsUnknownResource(result)) continue; const auto& ids = resource_alias_analysis.GetResourceUniqueIds(result); observed_resource_ids.insert(ids.begin(), ids.end()); } }); } // Checks if an op should be moved after a cluster. There may be users of a // cluster interleaved among the cluster ops. bool ShouldMoveOpAfterCluster( Block* block, Operation* op, const ClusterOps& cluster_ops, const llvm::SmallSetVector<Operation*, 8>& preceding_users, const TF::ResourceAliasAnalysis::Info& resource_alias_analysis, const llvm::SmallDenseSet<int64_t>& observed_resource_ids) { auto result = op->walk([&](Operation* inner_op) { for (Value operand : inner_op->getOperands()) { Operation* def = operand.getDefiningOp(); // Operands may not have a defining op (BlockArgument) or is from a // different block. if (!def || def->getBlock() != block) continue; if (cluster_ops.count(def) != 0 || preceding_users.count(def) != 0) { // Op is a user of a cluster or another op that is a user of the // cluster (transitively), but is before the cluster. return WalkResult::interrupt(); } } // Check for uses of any resource in or after cluster. for (Value operand : TF::filter_resources(inner_op->getOperands())) { if (resource_alias_analysis.IsUnknownResource(operand)) continue; auto ids = resource_alias_analysis.GetResourceUniqueIds(operand); for (const auto& id : ids) if (observed_resource_ids.contains(id)) return WalkResult::interrupt(); } return WalkResult::advance(); }); return result.wasInterrupted(); } // Collects ops that are before ops in the cluster but are users of other ops // in the cluster. This may happen because users of individual ops in the // cluster may be interleaved with other ops in the cluster. Resource id's are // also captured, to keep track of resource usage before, in, or after the // cluster. // TODO(lyandy): Extend this to handle all side effecting ops while handling // transitive data dependencies. llvm::SmallSetVector<Operation*, 8> CollectClusterPrecedingUsers( Block* block, const ClusterOps& cluster_ops, const TF::ResourceAliasAnalysis::Info& resource_alias_analysis) { llvm::SmallSetVector<Operation*, 8> preceding_users; llvm::SmallDenseSet<int64_t> observed_resource_ids; auto front = Block::iterator(cluster_ops.front()); auto back = Block::iterator(cluster_ops.back()); for (Operation& op : llvm::make_range(front, back)) { if (cluster_ops.contains(&op)) { CollectResourceIdsFromOp(op, resource_alias_analysis, observed_resource_ids); } else if (ShouldMoveOpAfterCluster( block, &op, cluster_ops, preceding_users, resource_alias_analysis, observed_resource_ids)) { preceding_users.insert(&op); CollectResourceIdsFromOp(op, resource_alias_analysis, observed_resource_ids); } } return preceding_users; } // Collects results and associated types of the cluster that are used outside of // the cluster. These results and types are used to create the clusters // `tf_device.cluster` and associated terminator. Results that have no uses // outside of the cluster (i.e. results of ops in the cluster are only consumed // by other ops in the cluster) are pruned. llvm::SmallVector<Value, 8> CollectClusterResults( Block* block, const ClusterOps& cluster_ops) { llvm::SmallVector<Value, 8> results; for (Operation* op : cluster_ops) { for (Value result : op->getResults()) { for (Operation* user : result.getUsers()) { // Check if user is not an op in the cluster. if (cluster_ops.count(block->findAncestorOpInBlock(*user)) == 0) { results.push_back(result); break; } } } } return results; } // Creates a `tf_device.cluster` to wrap cluster ops. tf_device::ClusterOp CreateClusterOp( Block* block, const ClusterOps& cluster_ops, llvm::ArrayRef<Value> results, llvm::ArrayRef<Operation*> preceding_users) { // `tf_device.cluster` will be placed at where the last op of the cluster is. Operation* last_cluster_op = cluster_ops.back(); OpBuilder builder(last_cluster_op); llvm::SmallVector<Type, 8> result_types; for (Value result : results) result_types.push_back(result.getType()); auto cluster = builder.create<tf_device::ClusterOp>(last_cluster_op->getLoc(), result_types); Block* body = new Block; cluster.body().push_back(body); // Move cluster ops to the cluster body. Also remove `_tpu_replicate` and // `device` attribute from ops in the cluster as that information will be // present in the `tf_device.cluster`. Do this for all ops including nested // ops. for (Operation* cluster_op : cluster_ops) { cluster_op->moveBefore(body, body->end()); cluster_op->walk([&](Operation* inner_op) { inner_op->removeAttr(kTPUReplicateAttr); inner_op->removeAttr(kDeviceAttr); }); } // Add terminator. builder.setInsertionPointToEnd(body); builder.create<tf_device::ReturnOp>(last_cluster_op->getLoc(), results); // Replaces uses of cluster ops results outside of cluster with the associated // `tf_device.cluster` results. for (auto ret_vals : llvm::zip(results, cluster.getResults())) { Value old_ret = std::get<0>(ret_vals); Value new_ret = std::get<1>(ret_vals); for (auto& use : llvm::make_early_inc_range(old_ret.getUses())) { Operation* user = use.getOwner(); if (!body->findAncestorOpInBlock(*user)) use.set(new_ret); } } // Move users of cluster that are before the cluster to after the cluster. Operation* op_after_cluster = cluster.getOperation()->getNextNode(); for (Operation* user : preceding_users) user->moveBefore(op_after_cluster); return cluster; } // Sorts `tf.TPUReplicatedInput` ops by `index` attribute. Ops with an `index` // of -1 are always after ops with a non negative `index`, and an arbitrary // ordering is used as there are no dependencies on their relative ordering. If // there are multiple `tf.TPUReplicatedInput` ops with the same non negative // index or if indices are less than -1, an error will be returned. LogicalResult SortTPUReplicatedInputsByIndex( llvm::ArrayRef<Operation*> inputs, llvm::SmallVectorImpl<Operation*>* sorted_inputs) { llvm::SmallDenseSet<int64_t, 8> unique_indices; for (Operation* input : inputs) { int64_t index = llvm::cast<TF::TPUReplicatedInputOp>(input).index(); if (index < -1) return input->emitOpError() << "requires index to be at least -1, but got " << index; if (index == -1) continue; if (!unique_indices.insert(index).second) return input->emitOpError() << "requires indices to be unique, but found multiple '" << input->getName() << "' ops with index " << index; } // Sort all TPUReplicatedInputs by `index` attribute to have // TPUReplicatedInputs with indices be added to the `tf_device.replicate` op // deterministically. If `index` attribute is -1, instead move them to the // end. sorted_inputs->assign(inputs.begin(), inputs.end()); std::stable_sort( sorted_inputs->begin(), sorted_inputs->end(), [](Operation* l, Operation* r) { int64_t l_index = llvm::cast<TF::TPUReplicatedInputOp>(l).index(); int64_t r_index = llvm::cast<TF::TPUReplicatedInputOp>(r).index(); if (l_index == -1 && r_index != -1) return false; if (r_index == -1 && l_index != -1) return true; return l_index < r_index; }); return success(); } // Creates a `tf_device.replicate` to represent replication for the cluster, if // necessary. LogicalResult ReplicateCluster(tf_device::ClusterOp cluster, int num_replicas) { // No need to replicate. if (num_replicas == 1) return success(); if (num_replicas < 1) return cluster.emitError() << "requires '" << kNumReplicasAttr << "' int attribute to be at least 1"; // Collect all used TPUReplicatedInput ops and sort by `index`. llvm::SmallSetVector<Operation*, 8> unique_replicated_input_ops; mlir::visitUsedValuesDefinedAbove( cluster.body(), cluster.body(), [&](mlir::OpOperand* operand) { Operation* def = operand->get().getDefiningOp(); if (def && llvm::isa<TF::TPUReplicatedInputOp>(def)) unique_replicated_input_ops.insert(def); }); llvm::SmallVector<Operation*, 8> replicated_input_ops; if (failed(SortTPUReplicatedInputsByIndex( unique_replicated_input_ops.getArrayRef(), &replicated_input_ops))) return failure(); // Index attribute value stored on TPUReplicatedInput op. These will be used // later for dynamic padder. llvm::SmallVector<int64_t, 8> replicated_input_indices; llvm::SmallVector<int64_t, 8> packed_input_indices; bool has_replicated_input_index = false; // Indices of the replicate op's arguments that are mirrored variables. llvm::SmallVector<int64_t, 8> mirrored_variable_indices; // Check if number of operands of each used TPUReplicatedInput op matches // `num_replicas` or 1. Collect all their operands and associated type for // creating the replicate op. llvm::SmallVector<std::pair<ValueRange, Type>, 8> replicated_inputs; llvm::SmallVector<Value, 8> packed_inputs; for (auto& pos_and_input : llvm::enumerate(replicated_input_ops)) { auto input = pos_and_input.value(); bool is_packed = llvm::cast<TF::TPUReplicatedInputOp>(input).is_packed(); const int num_operands = input->getNumOperands(); int num_inputs = is_packed ? 1 : num_replicas; if (num_operands != num_inputs) return input->emitOpError() << "requires " << num_inputs << " operands"; auto tpu_replicated_input = llvm::cast<TF::TPUReplicatedInputOp>(input); int64_t tpu_replicated_input_index = tpu_replicated_input.index(); if (is_packed) { packed_inputs.push_back(input->getOperand(0)); packed_input_indices.push_back(tpu_replicated_input_index); } else { replicated_inputs.push_back( {input->getOperands(), input->getOperand(0).getType()}); replicated_input_indices.push_back(tpu_replicated_input_index); } if (tpu_replicated_input_index != -1) has_replicated_input_index = true; if (tpu_replicated_input.is_mirrored_variable()) mirrored_variable_indices.push_back(pos_and_input.index()); } replicated_input_indices.append(packed_input_indices.begin(), packed_input_indices.end()); // Create replicate op. OpBuilder builder(cluster); auto replicate_op = builder.create<tf_device::ReplicateOp>( cluster.getLoc(), num_replicas, llvm::SmallDenseMap<llvm::StringRef, llvm::SmallVector<StringRef, 4>>(), replicated_inputs, packed_inputs, cluster.getResultTypes()); if (has_replicated_input_index) replicate_op.setAttr(kReplicatedInputIndicesAttr, builder.getI64ArrayAttr(replicated_input_indices)); if (!mirrored_variable_indices.empty()) replicate_op.setAttr(kMirroredVariableIndicesAttr, builder.getI64ArrayAttr(mirrored_variable_indices)); // Replace replicated cluster results with replicate op results. for (auto result_and_idx : llvm::enumerate(cluster.getResults())) { Value result = result_and_idx.value(); int idx = result_and_idx.index(); for (auto& use : result.getUses()) { Operation* def = use.getOwner(); if (!def || !llvm::isa<TF::TPUReplicatedOutputOp>(def)) return cluster.emitError() << "requires output of " << cluster.getOperationName() << " to lead to a 'tf.TPUReplicatedOutput' op"; const int def_NumResults = def->getNumResults(); if (def_NumResults != num_replicas) return def->emitOpError() << "requires " << num_replicas << " results"; auto replicate_outputs = llvm::make_range( std::next(replicate_op.result_begin(), idx * num_replicas), std::next(replicate_op.result_begin(), (idx + 1) * num_replicas)); def->replaceAllUsesWith(replicate_outputs); } } // Update replicated inputs with replicate op block arguments. for (auto input_and_block_arg : llvm::zip(replicated_input_ops, replicate_op.GetBody().getArguments())) { Operation* input = std::get<0>(input_and_block_arg); Value block_arg = std::get<1>(input_and_block_arg); mlir::replaceAllUsesInRegionWith(input->getResult(0), block_arg, cluster.body()); } // Create terminator for replicate op and move `tf_device.cluster` into // replicate. builder.setInsertionPointToEnd(&replicate_op.GetBody()); auto return_op = builder.create<tf_device::ReturnOp>(replicate_op.getLoc(), cluster.getResults()); cluster.getOperation()->moveBefore(return_op); return success(); } // Forms clusters with ops of the same `_tpu_replicate` attribute under a block. // // For a given block, clusters are formed via grouping ops by `_tpu_replicate` // attributes. // For every cluster formed: // 1. Find associated TPUReplicateMetadata attributes with the same // `_tpu_replicate` attribute. // 2. Find users not in cluster that are interleaved between cluster ops. // 3. Find external uses of cluster ops. // 4. Create `tf_device.cluster` with results consisting of the external uses // of cluster ops determined at 3. // 5. Move cluster ops to `tf_device.cluster` body. // 6. Replace external uses of cluster ops uses with `tf_device.cluster` // results. // 7. Move users from 2 to after the `tf_device.cluster`. // 8. Wrap cluster (`tf_device.cluster`) in a `tf_device.replicate` if // attribute `num_replicas` is greater than 1. // 9. Copy over TPUReplicateMetadata attributes to `tf_device.cluster`. LogicalResult FormClustersInBlock( Block* block, const TF::ResourceAliasAnalysis::Info& resource_alias_analysis) { MetadataMap metadata_map; LogicalResult result = CollectMetadata(block, &metadata_map); if (failed(result)) return result; // If there is no TPUReplicateMetadata op in this block, process blocks in // regions attached to the op's in the block. if (metadata_map.empty()) { for (Operation& op : *block) { for (Region& region : op.getRegions()) { if (!llvm::hasSingleElement(region)) return op.emitOpError("Expected single block region"); if (failed( FormClustersInBlock(&region.front(), resource_alias_analysis))) return failure(); } } return success(); } ClusterMap clusters; result = CollectAndGroupClusterOps(block, &clusters); if (failed(result)) return result; for (const auto& cluster_metadata_and_ops : clusters) { const auto& cluster_ops = cluster_metadata_and_ops.getSecond(); auto cluster_metadata = metadata_map.find(cluster_metadata_and_ops.getFirst()); // No TPUReplicateMetadata for a `_tpu_replicate` attribute. if (cluster_metadata == metadata_map.end()) { cluster_ops.front()->emitWarning() << "TPUReplicateMetadata for associated '" << kTPUReplicateAttr << "' attribute '" << cluster_metadata_and_ops.getFirst() << "' is missing"; continue; } llvm::SmallSetVector<Operation*, 8> preceding_users = CollectClusterPrecedingUsers(block, cluster_ops, resource_alias_analysis); llvm::SmallVector<Value, 8> results = CollectClusterResults(block, cluster_ops); tf_device::ClusterOp cluster = CreateClusterOp( block, cluster_ops, results, preceding_users.getArrayRef()); auto num_replicas = cluster_metadata->getSecond().get(kNumReplicasAttr); if (!num_replicas || !num_replicas.isa<mlir::IntegerAttr>()) return cluster.emitError() << "requires '" << kNumReplicasAttr << "' int attribute"; if (failed(ReplicateCluster( cluster, num_replicas.cast<mlir::IntegerAttr>().getInt()))) return failure(); // Copy TPUReplicateMetadata attributes to `tf_device.cluster`. cluster.setAttrs(cluster_metadata->second); // Exclude `num_replicas` as cluster should be replicated if necessary. cluster.removeAttr(kNumReplicasAttr); } return success(); } void TPUClusterFormation::runOnFunction( FuncOp func, const TF::ResourceAliasAnalysis::Info& resource_alias_analysis) { if (!llvm::hasSingleElement(func)) { func.emitOpError("Expecting a single block function"); return signalPassFailure(); } if (failed(FormClustersInBlock(&func.front(), resource_alias_analysis))) return signalPassFailure(); // Remove TPUReplicatedInput and TPUReplicatedOutput nodes. auto remove_result = func.walk([&](Operation* op) { if (!llvm::isa<TF::TPUReplicatedInputOp, TF::TPUReplicatedOutputOp>(op)) return WalkResult::advance(); // Forward operand to result. When `num_replicas` attribute is 1, no // `tf_device.replicate` is created and replicated (1) operands/results are // untouched. if (op->getNumOperands() == 1 && op->getNumResults() == 1) op->getResult(0).replaceAllUsesWith(op->getOperand(0)); // Leftover TPUReplicatedInput/TPUReplicatedOutput that are not of // `num_replicas` to 1. if (!op->use_empty()) { op->emitOpError() << "expects " << op->getName().getStringRef() << " to have no uses"; return WalkResult::interrupt(); } op->erase(); return WalkResult::advance(); }); if (remove_result.wasInterrupted()) return signalPassFailure(); } } // anonymous namespace std::unique_ptr<OperationPass<ModuleOp>> CreateTPUClusterFormationPass() { return std::make_unique<TPUClusterFormation>(); } static PassRegistration<TPUClusterFormation> pass( "tf-tpu-cluster-formation", "Form clusters from operations assigned to the same TPU cluster"); } // namespace TFTPU } // namespace mlir
.global s_prepare_buffers s_prepare_buffers: push %r15 push %r9 push %rbp push %rbx push %rdi push %rdx push %rsi lea addresses_A_ht+0x1601e, %rbx clflush (%rbx) nop nop nop nop sub %rdx, %rdx mov $0x6162636465666768, %rbp movq %rbp, %xmm1 movups %xmm1, (%rbx) nop nop nop dec %r15 lea addresses_UC_ht+0x1524a, %r9 nop nop nop nop nop sub $12870, %rsi movb (%r9), %bl nop nop nop nop nop xor $24657, %r15 pop %rsi pop %rdx pop %rdi pop %rbx pop %rbp pop %r9 pop %r15 ret .global s_faulty_load s_faulty_load: push %r14 push %r15 push %r8 push %r9 push %rax push %rbx push %rsi // Store lea addresses_WT+0x8a04, %r9 nop nop nop nop nop cmp %r14, %r14 movw $0x5152, (%r9) nop nop nop dec %rsi // Store lea addresses_WC+0x1b55e, %r14 nop nop nop xor $55688, %rax movl $0x51525354, (%r14) nop nop and %r15, %r15 // Store mov $0x41e, %r14 nop nop xor $23087, %rbx mov $0x5152535455565758, %rax movq %rax, %xmm7 movups %xmm7, (%r14) nop nop and %rbx, %rbx // Store lea addresses_US+0x5e5e, %r9 nop nop sub $23770, %rax movl $0x51525354, (%r9) nop nop cmp %r9, %r9 // Faulty Load lea addresses_D+0x1e81e, %r14 nop xor $44472, %rax mov (%r14), %r9w lea oracles, %r15 and $0xff, %r9 shlq $12, %r9 mov (%r15,%r9,1), %r9 pop %rsi pop %rbx pop %rax pop %r9 pop %r8 pop %r15 pop %r14 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_WT', 'AVXalign': False, 'size': 2}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_WC', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_P', 'AVXalign': False, 'size': 16}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_US', 'AVXalign': False, 'size': 4}} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16}} {'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
// Copyright 2013 The Goma Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "directive_filter.h" #include <string.h> #include <memory> #include <vector> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "content.h" #include "glog/logging.h" namespace devtools_goma { // static std::unique_ptr<Content> DirectiveFilter::MakeFilteredContent( const Content& content) { const size_t content_length = content.size(); std::unique_ptr<char[]> buffer(new char[content_length + 1]); size_t length = RemoveComments(content.buf(), content.buf_end(), buffer.get()); length = FilterOnlyDirectives(buffer.get(), buffer.get() + length, buffer.get()); length = RemoveEscapedNewLine(buffer.get(), buffer.get() + length, buffer.get()); return Content::CreateFromBuffer(buffer.get(), length); } // static const char* DirectiveFilter::SkipSpaces(const char* pos, const char* end) { while (pos != end) { if (*pos == ' ' || *pos == '\t') { ++pos; continue; } int newline_byte = IsEscapedNewLine(pos, end); if (newline_byte > 0) { pos += newline_byte; continue; } return pos; } return end; } /* static */ const char* DirectiveFilter::NextLineHead(const char* pos, const char* end) { while (pos != end) { if (*pos == '\n') return pos + 1; int newline_byte = IsEscapedNewLine(pos, end); if (newline_byte) pos += newline_byte; else pos += 1; } return end; } // static int DirectiveFilter::CaptureRawStringLiteral(const char* pos, const char* end) { absl::string_view input(pos, end - pos); absl::string_view s = input; CHECK(absl::ConsumePrefix(&s, "R\"")) << input; absl::string_view::size_type p = s.find('('); if (p == absl::string_view::npos) { s = input; if (s.size() >= 80UL) { s = s.substr(0, 80); } LOG(ERROR) << "failed to detect raw string literal:" << s; return input.size(); } absl::string_view delimiter = s.substr(0, p); CHECK_EQ(s[p], '('); s = s.substr(p + 1); int n = 0; while (!s.empty()) { p = s.find(')'); if (p == absl::string_view::npos) { return input.size(); } CHECK_EQ(s[p], ')'); absl::string_view r = s.substr(p + 1); n += p; if (absl::ConsumePrefix(&r, delimiter) && !r.empty() && r[0] == '"') { // raw string literal ends. return strlen("R\"") + delimiter.size() + strlen("(") + n + strlen(")") + delimiter.size() + strlen("\""); } n++; s = r; } return input.size(); } // static int DirectiveFilter::CopyStringLiteral(const char* pos, const char* end, char* dst) { const char* initial_pos = pos; DCHECK_EQ(*pos, '\"'); DCHECK(pos != end); // Copy '\"' *dst++ = *pos++; while (pos != end) { // String literal ends. if (*pos == '\"') { *dst++ = *pos++; break; } // Corresponding " was not found. Keep this as is. if (*pos == '\n') { *dst++ = *pos++; break; } int newline_byte = IsEscapedNewLine(pos, end); if (newline_byte > 0) { while (newline_byte--) { *dst++ = *pos++; } continue; } // \" does not end string literal. // I don't think we need to support trigraph. So, we don't consider "??/", // which means "\". if (*pos == '\\' && pos + 1 != end && *(pos + 1) == '\"') { *dst++ = *pos++; *dst++ = *pos++; continue; } *dst++ = *pos++; } return pos - initial_pos; } // static int DirectiveFilter::IsEscapedNewLine(const char* pos, const char* end) { if (*pos != '\\') return 0; if (pos + 1 < end && *(pos + 1) == '\n') return 2; if (pos + 2 < end && *(pos + 1) == '\r' && *(pos + 2) == '\n') return 3; return 0; } // Copied |src| to |dst| with removing comments. // It also removes raw string literal that contains "#", because // such string literal confuses include processor (detect it as // directives) and assumes such literal may not be used for // C preprocessor. http://b/123493120 // TODO: We assume '"' is not in include pathname. // When such pathname exists, this won't work well. e.g. #include <foo"bar> // static size_t DirectiveFilter::RemoveComments(const char* src, const char* end, char* dst) { const char* original_src = src; const char* original_dst = dst; while (src != end) { // Raw string literal starts. if (*src == 'R' && src + 1 < end && *(src + 1) == '\"' && (src == original_src || (!absl::ascii_isalnum(*(src - 1)) && *(src - 1) != '_'))) { int num = CaptureRawStringLiteral(src, end); const absl::string_view literal(src, num); VLOG(5) << "raw string literal=" << literal; if (literal.find('#') != absl::string_view::npos) { src += num; continue; } // copy it as is. memcpy(dst, src, num); src += num; dst += num; continue; } // String starts. if (*src == '\"') { int num_copied = CopyStringLiteral(src, end, dst); src += num_copied; dst += num_copied; continue; } // Check a comment does not start. if (*src != '/' || src + 1 == end) { *dst++ = *src++; continue; } // Block comment starts. if (*(src + 1) == '*') { const char* end_comment = nullptr; const char* pos = src + 2; while (pos + 2 <= end) { if (*pos == '*' && *(pos + 1) == '/') { end_comment = pos; break; } ++pos; } // When block comment end is not found, we don't skip them. if (end_comment == nullptr) { while (src < end) *dst++ = *src++; return dst - original_dst; } src = end_comment + 2; *dst++ = ' '; continue; } // One-line comment starts. if (*(src + 1) == '/') { src = DirectiveFilter::NextLineHead(src + 2, end); *dst++ = '\n'; continue; } *dst++ = *src++; } return dst - original_dst; } // static size_t DirectiveFilter::RemoveEscapedNewLine( const char* src, const char* end, char* dst) { const char* initial_dst = dst; while (src != end) { int newline_bytes = IsEscapedNewLine(src, end); if (newline_bytes == 0) { *dst++ = *src++; } else { src += newline_bytes; } } return dst - initial_dst; } // static size_t DirectiveFilter::FilterOnlyDirectives( const char* src, const char* end, char* dst) { const char* const original_dst = dst; while (src != end) { src = DirectiveFilter::SkipSpaces(src, end); if (src != end && *src == '#') { *dst++ = *src++; // Omit spaces after '#' in directive. src = DirectiveFilter::SkipSpaces(src, end); const char* next_line_head = DirectiveFilter::NextLineHead(src, end); memmove(dst, src, next_line_head - src); dst += next_line_head - src; src = next_line_head; } else { src = DirectiveFilter::NextLineHead(src, end); } } return dst - original_dst; } } // namespace devtools_goma
; A284777: Positions of 1 in A284775; complement of A284776. ; 2,5,6,8,10,13,14,17,18,20,23,24,26,29,30,32,34,37,38,41,42,44,46,49,50,53,54,56,59,60,62,64,67,68,71,72,74,77,78,80,82,85,86,89,90,92,95,96,98,101,102,104,106,109,110,113,114,116,118,121,122,125,126,128,131,132,134,137,138,140,142,145,146,149,150,152,154,157,158,161,162,164,167,168,170,172,175,176,179,180,182,185,186,188,191,192,194,196,199,200 mov $1,$0 mul $0,2 add $1,1 seq $1,284817 ; a(n) = 2n - 1 - A284776(n). add $0,$1 add $0,2
; A050271: Numbers n such that n = floor(sqrt(n)*ceiling(sqrt(n))). ; 1,2,3,4,7,8,9,14,15,16,23,24,25,34,35,36,47,48,49,62,63,64,79,80,81,98,99,100,119,120,121,142,143,144,167,168,169,194,195,196,223,224,225,254,255,256,287,288,289,322,323,324,359,360,361,398,399,400,439,440,441,482,483,484,527,528,529,574,575,576,623,624,625,674,675,676,727,728,729,782,783,784,839,840,841,898,899,900,959,960,961,1022,1023,1024,1087,1088,1089,1154,1155,1156,1223,1224,1225,1294,1295,1296,1367,1368,1369,1442,1443,1444,1519,1520,1521,1598,1599,1600,1679,1680,1681,1762,1763,1764,1847,1848,1849,1934,1935,1936,2023,2024,2025,2114,2115,2116,2207,2208,2209,2302,2303,2304,2399,2400,2401,2498,2499,2500,2599,2600,2601,2702,2703,2704,2807,2808,2809,2914,2915,2916,3023,3024,3025,3134,3135,3136,3247,3248,3249,3362,3363,3364,3479,3480,3481,3598,3599,3600,3719,3720,3721,3842,3843,3844,3967,3968,3969,4094,4095,4096,4223,4224,4225,4354,4355,4356,4487,4488,4489,4622,4623,4624,4759,4760,4761,4898,4899,4900,5039,5040,5041,5182,5183,5184,5327,5328,5329,5474,5475,5476,5623,5624,5625,5774,5775,5776,5927,5928,5929,6082,6083,6084,6239,6240,6241,6398,6399,6400,6559,6560,6561,6722,6723,6724,6887,6888,6889,7054,7055,7056 mov $1,$0 mov $2,$0 lpb $2,1 add $1,$3 trn $2,3 add $3,2 lpe add $1,1
; char *strcat(char * restrict s1, const char * restrict s2) SECTION code_string PUBLIC _strcat EXTERN asm_strcat _strcat: pop af pop de pop hl push hl push de push af jp asm_strcat
<% from pwnlib.shellcraft.powerpc.linux import syscall %> <%page args="ss, oss"/> <%docstring> Invokes the syscall sigaltstack. See 'man 2 sigaltstack' for more information. Arguments: ss(sigaltstack): ss oss(sigaltstack): oss </%docstring> ${syscall('SYS_sigaltstack', ss, oss)}
.data input_h: .word 80 input_w: .word 80 input_bmi: .word 80 prompt_h: .asciiz "high: " prompt_w: .asciiz "weigh: " prompt_bmi: .asciiz "bmi:" output: .asciiz "echo: " .text input_h_d: la $a0, prompt_h li $v0, 4 syscall li $v0, 6 syscall mov.s $f2, $f0 input_w_d: la $a0, prompt_w li $v0, 4 syscall li $v0, 6 syscall mov.s $f3, $f0 output_bmi: mul.s $f4 $f2 $f2 div.s $f5 $f3 $f4 mov.s $f12 $f5 li $v0 ,2 syscall
kb_Data:=$F50010 init: ld iy,ti.flags call ti.HomeUp call ti.RunIndicOff call libload_load jr z,main_init ld iy,ti.flags call ti.ClrLCDFull call ti.HomeUp call ti.DrawStatusBar ld hl,.needlibload call ti.PutS xor a,a ld (ti.curCol),a inc a ld (ti.curRow),a call ti.PutS .GetCSC: call ti.GetCSC or a,a jr z,.GetCSC jp ti.JForceCmdNoChar .needlibload: db "Need libLoad",0 db "tiny.cc/clibs",0 main_init: call lcd_init call ti_CloseAll call delete_packet_file call config_load ld hl,_ico_cursor ld (cursor+4),hl ld l,255 push hl call gfx_SetTransparentColor ld l,0 ex (sp),hl call gfx_SetTextTransparentColor ld hl,(config_colors) ex (sp),hl call gfx_SetTextBGColor ld hl,(config_colors+1) ex (sp),hl call gfx_SetTextFGColor pop hl ld hl,data_temp_prgm call util_openVarHL jq nz,main_draw call gfx_SetDrawBuffer ld hl,(config_colors) push hl call gfx_FillScreen pop hl or a,a sbc hl,hl push hl push hl call gfx_SetTextXY pop hl ld hl,data_save_temp_prgm ex (sp),hl call gfx_PrintStringLines pop hl .saveloop: ld iy,ti.flags call util_get_csc cp a,26 jp z,edit_temp_prgm cp a,34 jr z,main_draw cp a,18 jr nz,.saveloop .savetempprgm: ld l,5 push hl ld hl,backup_prgm_name push hl ld hl,data_temp_prgm push hl call ti_RenameVar pop hl pop hl pop hl main_draw: call countHomeItems call gfx_SetDrawBuffer ld hl,(config_colors) push hl call gfx_FillScreen pop hl call drawHomeScreen call gfx_SetDrawScreen call gfx_BlitBuffer main_loop: call drawCursor call kb_Scan ld hl,kb_Data+2 ; Group 1 ld a,(hl) inc hl inc hl bit 0,a jp nz,right_click bit 1,a jp nz,left_click bit 5,a jp nz,left_click bit 6,a jp nz,settings_menu bit 7,a jp nz,delete_file ; Group 2 ld a,(hl) inc hl inc hl bit 7,a jp nz,right_click ; Group 3 ld a,(hl) inc hl inc hl ; Group 4 ld a,(hl) inc hl inc hl ; Group 5 ld a,(hl) inc hl inc hl ; Group 6 ld a,(hl) inc hl inc hl bit 1,a jp nz,nextpage ;+ key bit 2,a jp nz,prevpage ;- key bit 6,a jr nz,.exit ; Is the clear key pressed? ; Group 7 ld a,(hl) and a,$f call nz,eraseCursor bit 0,a call nz,cursorDown ;down arrow bit 1,a call nz,cursorLeft ;left arrow bit 2,a call nz,cursorRight;right arrow bit 3,a call nz,cursorUp ;up arrow jp main_loop .exit: call config_save call ti_CloseAll jp exit_full nextpage: ld hl,(homeSkip) ld de,4 add hl,de ld de,0 maxHomeSkip:=$-3 or a,a sbc hl,de jr nc,.done add hl,de ld (homeSkip),hl .done: jp main_draw prevpage: ld hl,(homeSkip) ld de,4 or a,a sbc hl,de jr nc,.done or a,a sbc hl,hl jr .set .done: ld a,l and a,$FC ld l,a .set: ld (homeSkip),hl jp main_draw
; A079498: Numbers whose sum of digits in base b gives 0 (mod b), for b = 3. ; Submitted by Jamie Morken(w1) ; 0,5,7,11,13,15,19,21,26,29,31,33,37,39,44,45,50,52,55,57,62,63,68,70,74,76,78,83,85,87,91,93,98,99,104,106,109,111,116,117,122,124,128,130,132,135,140,142,146,148,150,154,156,161,163,165,170,171,176,178,182,184,186,189,194,196,200,202,204,208,210,215,218,220,222,226,228,233,234,239,241,245,247,249,253,255,260,261,266,268,271,273,278,279,284,286,290,292,294,297 mov $2,$0 lpb $0 add $3,$0 div $0,3 lpe mul $3,5 lpb $3 mod $3,3 lpe mov $4,$2 mul $4,3 add $3,$4 mov $0,$3
global isr0 global isr1 global isr2 global isr3 global isr4 global isr5 global isr6 global isr7 global isr8 global isr9 global isr10 global isr11 global isr12 global isr13 global isr14 global isr15 global isr16 global isr17 global isr18 global isr19 global isr20 global isr21 global isr22 global isr23 global isr24 global isr25 global isr26 global isr27 global isr28 global isr29 global isr30 global isr31 ; 0: Divide By Zero Exception isr0: cli push byte 0 ; A normal ISR stub that pops a dummy error code to keep a ; uniform stack frame push byte 0 jmp isr_common_stub ; 1: Debug Exception isr1: cli push byte 0 push byte 1 jmp isr_common_stub isr2: cli push byte 0 push byte 1 jmp isr_common_stub isr3: cli push byte 0 push byte 1 jmp isr_common_stub isr4: cli push byte 0 push byte 1 jmp isr_common_stub isr5: cli push byte 0 push byte 1 jmp isr_common_stub isr6: cli push byte 0 push byte 1 jmp isr_common_stub isr7: cli push byte 0 push byte 1 jmp isr_common_stub ; 8: Double Fault Exception (With Error Code!) isr8: cli push byte 8 ; Note that we DON'T push a value on the stack in this one! ; It pushes one already! Use this type of stub for exceptions ; that pop error codes! jmp isr_common_stub isr9: cli push byte 0 push byte 1 jmp isr_common_stub isr10: cli push byte 0 jmp isr_common_stub isr11: cli push byte 0 jmp isr_common_stub isr12: cli push byte 0 jmp isr_common_stub isr13: cli push byte 0 jmp isr_common_stub isr14: cli push byte 0 jmp isr_common_stub isr15: cli push byte 0 push byte 1 jmp isr_common_stub isr16: cli push byte 0 push byte 1 jmp isr_common_stub isr17: cli push byte 0 push byte 1 jmp isr_common_stub isr18: cli push byte 0 push byte 1 jmp isr_common_stub isr19: cli push byte 0 push byte 1 jmp isr_common_stub isr20: cli push byte 0 push byte 1 jmp isr_common_stub isr21: cli push byte 0 push byte 1 jmp isr_common_stub isr22: cli push byte 0 push byte 1 jmp isr_common_stub isr23: cli push byte 0 push byte 1 jmp isr_common_stub isr24: cli push byte 0 push byte 1 jmp isr_common_stub isr25: cli push byte 0 push byte 1 jmp isr_common_stub isr26: cli push byte 0 push byte 1 jmp isr_common_stub isr27: cli push byte 0 push byte 1 jmp isr_common_stub isr28: cli push byte 0 push byte 1 jmp isr_common_stub isr29: cli push byte 0 push byte 1 jmp isr_common_stub isr30: cli push byte 0 push byte 1 jmp isr_common_stub isr31: cli push byte 0 push byte 1 jmp isr_common_stub ; We call a C function in here. We need to let the assembler know ; that '_fault_handler' exists in another file extern fault_handler ; This is our common ISR stub. It saves the processor state, sets ; up for kernel mode segments, calls the C-level fault handler, ; and finally restores the stack frame. isr_common_stub: pusha push ds push es push fs push gs mov ax, 0x10 ; Load the Kernel Data Segment descriptor! mov ds, ax mov es, ax mov fs, ax mov gs, ax mov eax, esp ; Push us the stack push eax mov eax, fault_handler call eax ; A special call, preserves the 'eip' register pop eax pop gs pop fs pop es pop ds popa add esp, 8 ; Cleans up the pushed error code and pushed ISR number iret ; pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP!
; A045319: Primes congruent to {1, 2, 3, 4} mod 5. ; 2,3,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547 mov $2,$0 lpb $0 mov $0,1 mov $1,$2 lpe add $0,$1 seq $0,40 ; The prime numbers.
dnl ARM mpn_invert_limb -- Invert a normalized limb. dnl Copyright 2001, 2009, 2011, 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') ASM_START() PROLOGUE(mpn_invert_limb) LEA( r2, approx_tab-512) mov r3, r0, lsr #23 mov r3, r3, asl #1 ldrh r3, [r3, r2] mov r1, r3, asl #17 mul r12, r3, r3 umull r3, r2, r12, r0 sub r1, r1, r2, asl #1 umull r3, r2, r1, r1 umull r12, r3, r0, r3 umull r2, r12, r0, r2 adds r2, r2, r3 adc r12, r12, #0 rsb r1, r12, r1 mvn r2, r2, lsr #30 add r2, r2, r1, asl #2 umull r12, r3, r0, r2 adds r1, r12, r0 adc r3, r3, r0 rsb r0, r3, r2 return lr EPILOGUE() RODATA ALIGN(2) approx_tab: .short 0xffc0,0xfec0,0xfdc0,0xfcc0,0xfbc0,0xfac0,0xfa00,0xf900 .short 0xf800,0xf700,0xf640,0xf540,0xf440,0xf380,0xf280,0xf180 .short 0xf0c0,0xefc0,0xef00,0xee00,0xed40,0xec40,0xeb80,0xeac0 .short 0xe9c0,0xe900,0xe840,0xe740,0xe680,0xe5c0,0xe500,0xe400 .short 0xe340,0xe280,0xe1c0,0xe100,0xe040,0xdf80,0xdec0,0xde00 .short 0xdd40,0xdc80,0xdbc0,0xdb00,0xda40,0xd980,0xd8c0,0xd800 .short 0xd740,0xd680,0xd600,0xd540,0xd480,0xd3c0,0xd340,0xd280 .short 0xd1c0,0xd140,0xd080,0xcfc0,0xcf40,0xce80,0xcdc0,0xcd40 .short 0xcc80,0xcc00,0xcb40,0xcac0,0xca00,0xc980,0xc8c0,0xc840 .short 0xc780,0xc700,0xc640,0xc5c0,0xc540,0xc480,0xc400,0xc380 .short 0xc2c0,0xc240,0xc1c0,0xc100,0xc080,0xc000,0xbf80,0xbec0 .short 0xbe40,0xbdc0,0xbd40,0xbc80,0xbc00,0xbb80,0xbb00,0xba80 .short 0xba00,0xb980,0xb900,0xb840,0xb7c0,0xb740,0xb6c0,0xb640 .short 0xb5c0,0xb540,0xb4c0,0xb440,0xb3c0,0xb340,0xb2c0,0xb240 .short 0xb1c0,0xb140,0xb0c0,0xb080,0xb000,0xaf80,0xaf00,0xae80 .short 0xae00,0xad80,0xad40,0xacc0,0xac40,0xabc0,0xab40,0xaac0 .short 0xaa80,0xaa00,0xa980,0xa900,0xa8c0,0xa840,0xa7c0,0xa740 .short 0xa700,0xa680,0xa600,0xa5c0,0xa540,0xa4c0,0xa480,0xa400 .short 0xa380,0xa340,0xa2c0,0xa240,0xa200,0xa180,0xa140,0xa0c0 .short 0xa080,0xa000,0x9f80,0x9f40,0x9ec0,0x9e80,0x9e00,0x9dc0 .short 0x9d40,0x9d00,0x9c80,0x9c40,0x9bc0,0x9b80,0x9b00,0x9ac0 .short 0x9a40,0x9a00,0x9980,0x9940,0x98c0,0x9880,0x9840,0x97c0 .short 0x9780,0x9700,0x96c0,0x9680,0x9600,0x95c0,0x9580,0x9500 .short 0x94c0,0x9440,0x9400,0x93c0,0x9340,0x9300,0x92c0,0x9240 .short 0x9200,0x91c0,0x9180,0x9100,0x90c0,0x9080,0x9000,0x8fc0 .short 0x8f80,0x8f40,0x8ec0,0x8e80,0x8e40,0x8e00,0x8d80,0x8d40 .short 0x8d00,0x8cc0,0x8c80,0x8c00,0x8bc0,0x8b80,0x8b40,0x8b00 .short 0x8a80,0x8a40,0x8a00,0x89c0,0x8980,0x8940,0x88c0,0x8880 .short 0x8840,0x8800,0x87c0,0x8780,0x8740,0x8700,0x8680,0x8640 .short 0x8600,0x85c0,0x8580,0x8540,0x8500,0x84c0,0x8480,0x8440 .short 0x8400,0x8380,0x8340,0x8300,0x82c0,0x8280,0x8240,0x8200 .short 0x81c0,0x8180,0x8140,0x8100,0x80c0,0x8080,0x8040,0x8000 ASM_END()
; JSR $9034 ; 012DD0:FF UNDEFINED ; 04:ADC0:FF UNDEFINED .org $ADC0 LDA $0008 AND #$40 BEQ _2x2_LETTER ; 如果是大字就跳 (24x24) _LARGE_LETTER: LDA $0008 CLC SBC #$40 ; 后面的代码没改过 JMP $90A0 _2x2_LETTER: LDA $0008 ASL ; A <<= 2 (字符 * 4) ASL AND #$7F TAY ; Y = A ; A = (a * 4 overflow) ? 20 : 0 ; Offset = A LDA $0008 ; A = [0008] AND #$20 ; 20 表示写出位置 + 20 CLC ; 坐标~ ADC $0042 STA $0000 LDA #$00 ADC $0043 STA $0001 ; Load x offset. LDX $0021 LDA #$01 STA $0700,X STA $0706,X ; 写出坐标 LDA $0000 STA $0702,X CLC ADC #$20 STA $0708,X LDA $0001 STA $0701,X ADC #$00 STA $0707,X LDA _TITLE_CHAR_TABLE + 0, Y STA $0703,X LDA _TITLE_CHAR_TABLE + 1, Y STA $0704,X LDA _TITLE_CHAR_TABLE + 2, Y STA $0709,X LDA _TITLE_CHAR_TABLE + 3, Y STA $070A,X LDA #$FF STA $0705,X STA $070B,X TXA ; A = X CLC ADC #$0C ; A += 0x0C STA $0021 ; Write x-offset ; 向右移动两个字节 LDA $0042 CLC ADC #$02 STA $0042 RTS _TITLE_CHAR_TABLE: .byte $0,$1,$10,$11 .byte $2,$3,$12,$13 .byte $4,$5,$14,$15 .byte $6,$7,$16,$17 .byte $8,$9,$18,$19 .byte $a,$b,$1a,$1b .byte $c,$d,$1c,$1d .byte $e,$f,$1e,$1f .byte $20,$21,$30,$31 .byte $22,$23,$32,$33 .byte $24,$25,$34,$35 .byte $26,$27,$36,$37 .byte $28,$29,$38,$39 .byte $2a,$2b,$3a,$3b ; 前引号 ; .byte $2c,$2d,$3c,$3d .byte $0B,$00,$00,$00 ; 逗号 ; .byte $2e,$2f,$3e,$3f .byte $00,$00,$1B,$00 ; 句号 (10) ; .byte $40,$41,$50,$51 .byte $00,$00,$0A,$00 ; 之 (11) .byte $F7,$F8,$F9,$FA ; 名 .byte $FB,$FC,$FD,$FE .byte $46,$47,$56,$57 .byte $48,$49,$58,$59 .byte $4a,$4b,$5a,$5b .byte $4c,$4d,$5c,$5d .byte $4e,$4f,$5e,$5f .byte $60,$61,$70,$71 .byte $62,$63,$72,$73 .byte $64,$65,$74,$75 .byte $66,$67,$76,$77 .byte $68,$69,$78,$79 .byte $6a,$6b,$7a,$7b .byte $6c,$6d,$7c,$7d .byte $6e,$6f,$7e,$7f
; ; enterTCHelper - MSVC Edition ; ; This helper routine is written in assembly to take care of the details ; when transferring control between jitted code and the translator. ; ; Note that this is only used when compiling under MSVC. The .S version ; of this file is used by everything else. ; ; The columns are registers of Linux and Mac ABI / Windows ABI / ARM ABI. ; rdi / rcx / x0: Cell* vm_sp ; rsi / rdx / x1: Cell* vm_fp ; rdx / r8 / x2: unsigned char* start ; rcx / r9 / x4: ActRec* firstAR ; r8 / stack / x5: uint8_t* targetCacheBase ; r9 / stack / x6: ActRec* calleeAR ; ; Note that on Windows, ETCH_GET_ARG5/6 borrow r10/r11 respectively .CODE enterTCHelper PROC FRAME mov r10, [rsp + 28h] mov r11, [rsp + 30h] push rbp .pushframe .endprolog ; Set firstAR->m_sfp to point to this frame. mov [r9], rsp ; Set up special registers used for translated code. mov rbx, rcx ; rVmSp mov r12, r10 ; rVmTl mov rbp, rdx ; rVmFp sub rsp, 8 ; If we're entering the TC at a function prologue, make it look like we got ; there via a callphp{} by pushing return addresses, setting the callee frame ; pointer, then jumping to the prologue. We leave the TC with a ret ; instruction, so if we enter it with a jmp, that will unbalance the RSB and ; cause tons of branch mispredictions in the frames above us. To avoid this, ; we get to the prologue by calling a stub that pops the return address ; pushed by the call and jumps to the prologue. This pushes a bogus address ; on the RSB but the ret to callToExit always mispredicts anyway, and this ; keeps the RSB balanced. test r11, r11 jz enterTCHelper$callTC push IMAGEREL enterTCExit push QWORD PTR [r11 + 8] mov rbp, r11 call enterTCHelper$prologue enterTCHelper$callTC: ; The translated code we are about to enter does not follow the ; standard prologue of pushing rbp at entry, so we are purposely 8 ; bytes short of 16-byte alignment before this call instruction so ; that the return address being pushed will make the native stack ; 16-byte aligned. call r8 ; enterTCExit is never called directly; this exists to give the jit ; access to the address of the expected return address while in the TC. public enterTCExit enterTCExit LABEL PTR ; Eager vm-reg save. Must match values in rds-header.h mov [r12 + 10h], rbx mov [r12 + 20h], rbp add rsp, 8 ; Epilogue pop rbp ret enterTCHelper$prologue: pop rax jmp r8 enterTCHelper ENDP ; This is the mangled name of MCGenerator::handleServiceRequest, as ; we can't explicitly set the name of a member's mangle in MSVC. ?handleServiceRequest@MCGenerator@jit@HPHP@@QEAAPEAEAEAUReqInfo@svcreq@23@@Z PROTO .DATA? EXTERN mcg : QWORD .CODE ; handleSRHelper: Translated code will jump to this stub to perform all ; service requests. It calls out to C++ to handle the request, then jumps ; to the returned address (which may be the callToExit stub). handleSRHelper PROC ; Sync vmsp & vmfp mov [r12 + 10h], rbx mov [r12 + 20h], rbp ; Push a ServiceReqInfo struct onto the stack and call handleServiceRequest. push r8 push rcx push rdx push rsi push r10 push rdi ; call mcg->handleServiceRequest(%rsp) mov rcx, mcg mov rdx, rsp call ?handleServiceRequest@MCGenerator@jit@HPHP@@QEAAPEAEAEAUReqInfo@svcreq@23@@Z ; Pop the ServiceReqInfo off the stack. add rsp, 30h ; rVmTl was preserved by the callee, but vmsp and vmfp might've changed if ; we interpreted anything. Reload them. mov rbx, [r12 + 10h] mov rbp, [r12 + 20h] jmp rax handleSRHelper ENDP END
; DFS/ADFS Disk op routines ; helpful for streaming, faster loading to SWR etc. ; http://chrisacorns.computinghistory.org.uk/docs/Acorn/Manuals/Acorn_DiscSystemUGI2.pdf ; Our SWR loader is 60% faster than *SRLOAD disksys_loadto_addr = &3000 .beeb_disksys_start \*------------------------------- \* DISKSYS OSFILE PARAMS \*------------------------------- .osfile_params .osfile_nameaddr EQUW &FFFF ; file load address .osfile_loadaddr EQUD 0 ; file exec address .osfile_execaddr EQUD 0 ; start address or length .osfile_length EQUD 0 ; end address of attributes .osfile_endaddr EQUD 0 ;-------------------------------------------------------------- ; Load a file from disk to memory (SWR supported) ; Loads in sector granularity so will always write to page aligned address ;-------------------------------------------------------------- ; A=memory address MSB (page aligned) ; X=filename address LSB ; Y=filename address MSB .disksys_load_direct { STA osfile_loadaddr+1 \ Point to filename STX osfile_nameaddr STY osfile_nameaddr+1 \ Ask OSFILE to load our file LDX #LO(osfile_params) LDY #HI(osfile_params) LDA #&FF JMP osfile } .disksys_load_file { \ Final destination STA write_to+1 \ Where to? LDA write_to+1 BPL load_direct \ Load to screen if can't load direct LDA #HI(disksys_loadto_addr) \ Load the file .load_direct JSR disksys_load_direct \ Do we need to copy it anywhere? .write_to LDX #&FF BPL disksys_copy_block_return \ Get filesize LDY osfile_length+1 LDA osfile_length+0 BEQ no_extra_page INY ; always copy a whole number of pages .no_extra_page \ Read from LDA #HI(disksys_loadto_addr) } \\ Fall through! ; A=read from PAGE, X=write to page, Y=#pages .disksys_copy_block { STA read_from+2 STX write_to+2 \ We always copy a complete number of pages LDX #0 .read_from LDA &FF00, X .write_to STA &FF00, X INX BNE read_from INC read_from+2 INC write_to+2 DEY BNE read_from } .disksys_copy_block_return RTS IF 0 \\ enable when we have PuCrunch .disksys_decrunch_file { \ Final destination is baked into pu file STA unpack_addr+1 \ Load to screen as can't load direct LDA #HI(disksys_loadto_addr) JSR disksys_load_direct .unpack_addr LDA #&00 LDX #LO(disksys_loadto_addr) LDY #HI(disksys_loadto_addr) JMP decrunch } ENDIF .beeb_disksys_end
; A183221: Complement of the 9-gonal numbers. ; 2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105 add $0,1 mov $3,$0 lpb $0,1 trn $2,$0 trn $4,$3 mov $1,$4 add $4,$2 mov $2,$0 add $3,1 add $4,2 sub $0,$4 trn $0,5 add $1,$3 lpe
bits 32 dd 0x1BADB002 dd 0x0 dd - 0x1BADB002 extern kmain global _start _start: cli call kmain jmp $
; BOOT CRITICAL ; Stage2 Required Includes ; ; %include "../boot/betterRealMode.asm" ; %include "../boot/IDTmain.asm" %include "../Drivers/PS2/PS_2.asm" ; init should be dealt with in kernel, not s2! ; BootCritical Signature ; stage2_minloadSig : dd 0xDEADF154 ; KERNEL CRITICAL ; Memory Check Includes ; ; %include "../boot/detection.asm" ; PS/2 Driver Includes ; %include "../Drivers/PS2/Generic_Mouse.asm" %include "../Drivers/PS2/Generic_Keyboard.asm" ; NEW MODULE SYSTEM %include "../newModules/WinMan.asm" ; GRAPHICS ; Graphics Driver Includes ; %include "../Drivers/GFX/Generic_Display.asm" ; 3GXlib Includes ; %include "../Graphics/3GXlib/L3gxImage.asm" %include "../Graphics/3GXlib/DrawRect.asm" %include "../Graphics/3GXlib/ClearImage.asm" %include "../Graphics/3GXlib/DrawImage.asm" ; Text and Font Includes ; %include "../Graphics/TextHandler.asm" %include "../Graphics/Font/SysDefault.asm" ; Dolphin Includes ; %include "../modules/dolphin/Dolphin.asm" ; depricated %include "../Meta/Graphics/Window.asm" ; depricated %include "../modules/dolphin2/Dolphin2.asm" %include "../modules/dolphin2/DolphinConfig.asm" %include "../modules/dolphin2/PromptBox.asm" %include "../modules/dolphin2/FileChooser.asm" %include "../modules/dolphin/WindowTools.asm" ; depricated %include "../modules/dolphin/Update_Text.asm" ; Catfish Includes ; %include "../modules/catfish/Catfish.asm" ; Component Includes ; %include "../Graphics/RenderTextThing.asm" %include "../Graphics/TextArea.asm" %include "../Graphics/Image.asm" %include "../Graphics/Grouping.asm" %include "../Graphics/Button.asm" %include "../Graphics/WindowGrouping.asm" %include "../Graphics/GroupingScrollable.asm" %include "../Graphics/SelectionPanel.asm" ; USER SIDE ; iConsole Includes ; %include "../OrcaHLL/iConsole.asm" ; depricated %include "../modules/console/iConsole.asm" ; depricated %include "../modules/console/iConsole2.asm" ; Module Includes ; %include "../modules/textEditor/TextEditor.asm" %include "../modules/imageEditor/ImageEditor.asm" %include "../modules/video/Video.asm" ; here on needs method traces added %include "../modules/simpleRender/SimpleRender.asm" %include "../modules/systemMemoryMap/SystemMemoryMap.asm" %include "../modules/bfParse/bfParse.asm" %include "../modules/hexEditor/HexEditor.asm" ; Program Loader Includes ; %include "../kernel/ProgramLoader.asm" ; depricated in part ; Syscall Includes ; %include "../modules/xlib/int30.asm" ; DRIVER CRITICAL ; PCI Driver Includes ; %include "../Drivers/PCI/Generic_ComponentInterface.asm" ; %include "..\Drivers\PCI\PCI_LookupTables.asm" ; HARD-DRIVE AND FILESYSTEM ; HDD Driver Includes ; %include "../Drivers/HDD/rmATA.asm" %include "../Drivers/HDD/ATA_DETECT.asm" %include "../Drivers/HDD/AHCI_COMMANDS.asm" %include "../Drivers/HDD/AHCI_DMAWRITE.asm" ; MinnowFS Includes ; ;%include "../Tools/System/Minnow2.asm" ; depricated %include "../Tools/System/Minnow3.asm" ; depricated %include "../Tools/System/Minnow4.asm" %include "../Tools/System/Minnow5.asm" ; SYSTEM MISC ; System Tool Includes ; %include "../Tools/System/Time.asm" %include "../Tools/System/Guppy.asm" %include "../Guppy2.asm" ;; TESTING ONLY %include "../Tools/System/GetValue.asm" ; %include "..\Tools\System\TaskSwapHandler.asm" ; System Utility Includes ; %include "../Tools/Utility/Clock.asm" ; depricated in part ; System Security Includes ; %include "../Tools/Security/Manager.asm" %include "../Tools/Security/HaltScreen.asm" ; System Debug Includes ; %include "../debug/TextMode.asm" %include "../debug/MemoryCheck.asm" %include "../debug/print.asm" ; depricated ; UTILITY ; Graphics Utility Includes ; %include "../Graphics/Image/Tools.asm" %include "../Graphics/Image/TransparencyUtils.asm" ; String Utility Includes ; %include "../Tools/String/General.asm" %include "../Tools/String/EqualityTests.asm" ; Number Utility Includes ; %include "../Tools/Number/BCDconversions.asm" %include "../Tools/Number/parsing.asm" ; Buffer Utility Includes ; %include "../Meta/Buffer.asm" ; MISC ; Paging Includes ; %include "../kernel/Paging.asm" ; unimplemented %include "../kernel/betterPaging.asm" ; EHCI Driver Includes ; %include "../Drivers/USB/EHCI.asm" ; unimplemented %include "../$Emulator/map.asm" ; DEFINITIONS ; Truthy / Falsey TRUE equ 0xFF true equ 0xFF FALSE equ 0x00 false equ 0x00 ; Null null equ 0x0 nullptr : dq 0 ; String endstr equ 0x0 ; 255-Color Palette WHITE equ 0xFF
#include "IMU.h" IMU * imu_pointer; IMU::IMU() { } IMU::~IMU() { } int IMU::init(u32 com_port, u32 baudrate) { imu_pointer = this; EKF = false; // Settings u8 temp_string[20] = {0}; u8 enable = 1; u8 data_stream_format_descriptors[10]; u16 data_stream_format_decimation[10]; u8 data_stream_format_num_entries = 0; u16 device_descriptors_size = 128*2; u8 com_mode = 0; float angles[3] = {0}; filter_valid_packet_count = 0; ahrs_valid_packet_count = 0; filter_timeout_packet_count = 0; ahrs_timeout_packet_count = 0; filter_checksum_error_packet_count = 0; ahrs_checksum_error_packet_count = 0; //Initialize the interface to the device if(mip_interface_init(com_port, baudrate, &device_interface, DEFAULT_PACKET_TIMEOUT_MS) != MIP_INTERFACE_OK) return -1; // Putting Device Into Standard Mode device_descriptors_size = 128*2; com_mode = MIP_SDK_GX5_25_IMU_STANDARD_MODE; //Set communication mode while(mip_system_com_mode(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &com_mode) != MIP_INTERFACE_OK){} //Verify device mode setting while(mip_system_com_mode(&device_interface, MIP_FUNCTION_SELECTOR_READ, &com_mode) != MIP_INTERFACE_OK){} if(com_mode != MIP_SDK_GX5_25_IMU_STANDARD_MODE) printf("ERROR: Standard mode not established\n\n"); else { /* // Put the GX5-25 into idle mode while(mip_base_cmd_idle(&device_interface) != MIP_INTERFACE_OK){} // Try to ping the GX5-25 while(mip_base_cmd_ping(&device_interface) != MIP_INTERFACE_OK){} // Reset the filter while(mip_filter_reset_filter(&device_interface) != MIP_INTERFACE_OK){} // Initialize the filter with Euler Angles angles[0] = angles[1] = angles[2] = 0; while(mip_filter_set_init_attitude(&device_interface, angles) != MIP_INTERFACE_OK){} // Reset the filter while(mip_filter_reset_filter(&device_interface) != MIP_INTERFACE_OK){} // Initialize the filter with a heading while(mip_filter_set_init_heading(&device_interface, angles[0]) != MIP_INTERFACE_OK){} // Reset the filter while(mip_filter_reset_filter(&device_interface) != MIP_INTERFACE_OK){} */ // Setup the GX5-25 dataset callbacks if(mip_interface_add_descriptor_set_callback(&device_interface, MIP_FILTER_DATA_SET, NULL, &filter_packet_callback) != MIP_INTERFACE_OK) return -1; if(mip_interface_add_descriptor_set_callback(&device_interface, MIP_AHRS_DATA_SET, NULL, &ahrs_packet_callback) != MIP_INTERFACE_OK) return -1; if(EKF) { // Setup the FILTER datastream format data_stream_format_descriptors[0] = MIP_FILTER_DATA_ATT_EULER_ANGLES; data_stream_format_descriptors[1] = MIP_FILTER_DATA_LINEAR_ACCELERATION; data_stream_format_descriptors[2] = MIP_FILTER_DATA_COMPENSATED_ANGULAR_RATE; data_stream_format_decimation[0] = 0x01; data_stream_format_decimation[1] = 0x01; data_stream_format_decimation[2] = 0x01; data_stream_format_num_entries = 3; while(mip_3dm_cmd_filter_message_format(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &data_stream_format_num_entries, data_stream_format_descriptors, data_stream_format_decimation) != MIP_INTERFACE_OK) {} // Poll the Estimation Filter data while(mip_3dm_cmd_poll_filter( &device_interface, MIP_3DM_POLLING_ENABLE_ACK_NACK, data_stream_format_num_entries, data_stream_format_descriptors) != MIP_INTERFACE_OK){} // Enable the FILTER datastream while(mip_3dm_cmd_continuous_data_stream(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, MIP_3DM_INS_DATASTREAM, &enable) != MIP_INTERFACE_OK){} } else { // Setup the AHRS datastream format data_stream_format_descriptors[0] = MIP_AHRS_DATA_ACCEL_SCALED; data_stream_format_descriptors[1] = MIP_AHRS_DATA_GYRO_SCALED; data_stream_format_descriptors[2] = MIP_AHRS_DATA_EULER_ANGLES; data_stream_format_decimation[0] = 0x01; data_stream_format_decimation[1] = 0x01; data_stream_format_decimation[2] = 0x01; data_stream_format_num_entries = 3; while(mip_3dm_cmd_ahrs_message_format(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &data_stream_format_num_entries, data_stream_format_descriptors, data_stream_format_decimation) != MIP_INTERFACE_OK){} // Poll the AHRS data while(mip_3dm_cmd_poll_ahrs(&device_interface, MIP_3DM_POLLING_ENABLE_ACK_NACK, data_stream_format_num_entries, data_stream_format_descriptors) != MIP_INTERFACE_OK){} // Enable the AHRS datastream while(mip_3dm_cmd_continuous_data_stream(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, MIP_3DM_AHRS_DATASTREAM, &enable) != MIP_INTERFACE_OK){} } } } void IMU::update(float euler[3], float linacc[3], float angvel[3]) { //Update the parser (this function reads the port and parses the bytes mip_interface_update(&device_interface); if(EKF) { euler[0] = curr_filter_angles.roll; euler[1] = curr_filter_angles.pitch; euler[2] = curr_filter_angles.yaw; linacc[0] = curr_filter_accel.x; linacc[1] = curr_filter_accel.y; linacc[2] = curr_filter_accel.z; angvel[0] = curr_filter_gyro.x; angvel[1] = curr_filter_gyro.y; angvel[2] = curr_filter_gyro.z; } else { euler[0] = curr_ahrs_angles.roll; euler[1] = curr_ahrs_angles.pitch; euler[2] = curr_ahrs_angles.yaw; linacc[0] = curr_ahrs_accel.scaled_accel[0]; linacc[1] = curr_ahrs_accel.scaled_accel[1]; linacc[2] = curr_ahrs_accel.scaled_accel[2]; angvel[0] = curr_ahrs_gyro.scaled_gyro[0]; angvel[1] = curr_ahrs_gyro.scaled_gyro[1]; angvel[2] = curr_ahrs_gyro.scaled_gyro[2]; } } void filter_packet_callback(void *user_ptr, u8 *packet, u16 packet_size, u8 callback_type) { mip_field_header *field_header; u8 *field_data; u16 field_offset = 0; //The packet callback can have several types, process them all switch(callback_type) { /// //Handle valid packets /// case MIP_INTERFACE_CALLBACK_VALID_PACKET: { imu_pointer->filter_valid_packet_count++; /// //Loop through all of the data fields /// while(mip_get_next_field(packet, &field_header, &field_data, &field_offset) == MIP_OK) { /// // Decode the field /// switch(field_header->descriptor) { /// // Estimated Attitude, Euler Angles /// case MIP_FILTER_DATA_ATT_EULER_ANGLES: { memcpy(&imu_pointer->curr_filter_angles, field_data, sizeof(mip_filter_attitude_euler_angles)); //For little-endian targets, byteswap the data field mip_filter_attitude_euler_angles_byteswap(&imu_pointer->curr_filter_angles); }break; case MIP_FILTER_DATA_LINEAR_ACCELERATION: { memcpy(&imu_pointer->curr_filter_accel, field_data, sizeof(mip_filter_linear_acceleration)); //For little-endian targets, byteswap the data field mip_filter_linear_acceleration_byteswap(&imu_pointer->curr_filter_accel); }break; case MIP_FILTER_DATA_COMPENSATED_ANGULAR_RATE: { memcpy(&imu_pointer->curr_filter_gyro, field_data, sizeof(mip_filter_compensated_angular_rate)); //For little-endian targets, byteswap the data field mip_filter_compensated_angular_rate_byteswap(&imu_pointer->curr_filter_gyro); }break; default: break; } } }break; /// //Handle checksum error packets /// case MIP_INTERFACE_CALLBACK_CHECKSUM_ERROR: { imu_pointer->filter_checksum_error_packet_count++; }break; /// //Handle timeout packets /// case MIP_INTERFACE_CALLBACK_TIMEOUT: { imu_pointer->filter_timeout_packet_count++; }break; default: break; } } void ahrs_packet_callback(void *user_ptr, u8 *packet, u16 packet_size, u8 callback_type) { mip_field_header *field_header; u8 *field_data; u16 field_offset = 0; //The packet callback can have several types, process them all switch(callback_type) { /// //Handle valid packets /// case MIP_INTERFACE_CALLBACK_VALID_PACKET: { imu_pointer->ahrs_valid_packet_count++; /// //Loop through all of the data fields /// while(mip_get_next_field(packet, &field_header, &field_data, &field_offset) == MIP_OK) { /// // Decode the field /// switch(field_header->descriptor) { /// // Scaled Accelerometer /// case MIP_AHRS_DATA_ACCEL_SCALED: { memcpy(&imu_pointer->curr_ahrs_accel, field_data, sizeof(mip_ahrs_scaled_accel)); //For little-endian targets, byteswap the data field mip_ahrs_scaled_accel_byteswap(&imu_pointer->curr_ahrs_accel); }break; /// // Scaled Gyro /// case MIP_AHRS_DATA_GYRO_SCALED: { memcpy(&imu_pointer->curr_ahrs_gyro, field_data, sizeof(mip_ahrs_scaled_gyro)); //For little-endian targets, byteswap the data field mip_ahrs_scaled_gyro_byteswap(&imu_pointer->curr_ahrs_gyro); }break; /// // Euler /// case MIP_AHRS_DATA_EULER_ANGLES: { memcpy(&imu_pointer->curr_ahrs_angles, field_data, sizeof(mip_ahrs_euler_angles)); //For little-endian targets, byteswap the data field mip_ahrs_euler_angles_byteswap(&imu_pointer->curr_ahrs_angles); }break; default: break; } } }break; /// //Handle checksum error packets /// case MIP_INTERFACE_CALLBACK_CHECKSUM_ERROR: { imu_pointer->ahrs_checksum_error_packet_count++; }break; /// //Handle timeout packets /// case MIP_INTERFACE_CALLBACK_TIMEOUT: { imu_pointer->ahrs_timeout_packet_count++; }break; default: break; } }
#include "iarduino_I2C_Matrix_8x8.h" // // // Инициализация дисплея: // Возвращаемое значение: результат инициализации. bool iarduino_I2C_Matrix_8x8::begin (void){ // Параметр: отсутствует uint8_t tmpImage[8]; // Объявляем массив для временного хранения изображения экрана. // Инициируем работу с шиной I2C: // objI2C->begin(100); // Инициируем передачу данных по шине I2C на скорости 100 кГц. // Если адрес не указан, то ищим модуль на шине I2C: // if(valAddrTemp==0){ // for(int i=1; i<127; i++){ // Проходим по всем адресам на шине I2C if( objI2C->checkAddress(i) ){ valAddr=i; delay(2); // Если на шине I2C есть устройство с адресом i, то используем этот адрес для проверки найденного модуля... if(_readBytes(REG_MODEL,4) ){ // Читаем 4 байта начиная с регистра «REG_MODEL» в массив «data». if( data[0] == DEF_MODEL_8X8 ){ // Если у модуля с адресом i в регистре «MODEL» (data[0]) хранится значение DEF_MODEL_8X8, то ... if((data[2]>>1) == i || data[2] == 0xFF ){ // Если у модуля с адресом i в регистре «ADDRESS» (data[2]) хранится значение i (адрес+младший бит) или 0xFF (адрес не задавался), то ... if( data[3] == DEF_CHIP_ID_FLASH || data[3] == DEF_CHIP_ID_METRO){ // Если у модуля с адресом i в регистре «CHIP_ID» (data[3]) хранится значение DEF_CHIP_ID_FLASH (идентификатор модулей Flash), или DEF_CHIP_ID_METRO (идентификатор модулей Metro), то ... valAddrTemp=i; i=128; // Считаем что модуль обнаружен, сохраняем значение i как найденный адрес и выходим из цикла. }}}}} // } // } // // Если модуль не найден, то возвращаем ошибку инициализации: // if( valAddrTemp == 0 ){ valAddr=0; return false;} // // Проверяем наличие модуля на шине I2C: // if( objI2C->checkAddress(valAddrTemp) == false ){ valAddr=0; return false;} // Если на шине I2C нет устройств с адресом valAddrTemp, то возвращаем ошибку инициализации valAddr=valAddrTemp; // Сохраняем адрес модуля на шине I2C. // Проверяем значения регистров модуля: // if(_readBytes(REG_MODEL,4)==false ){ valAddr=0; return false;} // Если не удалось прочитать 4 байта в массив «data» из модуля начиная с регистра «REG_MODEL», то возвращаем ошибку инициализации. if( data[0] != DEF_MODEL_8X8 ){ valAddr=0; return false;} // Если значение регистра «MODEL» (data[0]) не совпадает со значением DEF_MODEL_8X8, то возвращаем ошибку инициализации. if((data[2]>>1) != valAddrTemp && data[2] !=0xFF ){ valAddr=0; return false;} // Если значение регистра «ADDRESS» (data[2]) не совпадает с адресом модуля и не совпадает со значением 0xFF, то возвращаем ошибку инициализации. if( data[3] != DEF_CHIP_ID_FLASH && data[3] != DEF_CHIP_ID_METRO ){ valAddr=0; return false;} // Если значение регистра «CHIP_ID» (data[3]) не совпадает со значением DEF_CHIP_ID_FLASH и DEF_CHIP_ID_METRO, то возвращаем ошибку инициализации. valVers=data[1]; // Сохраняем байт регистра «VERSION» (data[1]) в переменую «valVers». // Определяем значения переменных: // objI2C->readByte(valAddr,REG_FLAGS_0); // Читаем флаги регистра «REG_FLAGS_0» в никуда. data[0]=0; _writeBytes(REG_8X8_SYMBOL_INPUT,1); // Загружаем 0 в регистр «SYMBOL_INPUT», тогда символ с кодом 0 отобразится на дисплее, но это не символ, а значения ширины, интервала и отступа символов. getImage(tmpImage); // Сохраняем текущее изображение дисплея в массив tmpImage. charWidth=tmpImage[0]; // Извлекаем значение ширины символов. charInterval=tmpImage[1]; // Извлекаем значение межсимвольного интервала. charIndent=tmpImage[2]; // Извлекаем значение отступа символа от левого края экрана. delay(5); // clrScr(); // Чистим экран. return true; // Возвращаем флаг успешной инициализаии. } // // // Смена адреса модуля: // Возвращаемое значение: резульат смены адреса. bool iarduino_I2C_Matrix_8x8::changeAddress (uint8_t newAddr){ // Параметр: newAddr - новый адрес модуля. if(valAddr){ // Если дисплей был инициализирован, то ... // Проверяем новый адрес: // if(newAddr>0x7F){newAddr>>=1;} // Корректируем адрес, если он указан с учётом бита RW. if(newAddr==0x00 || newAddr==0x7F){return false;} // Запрещаем устанавливать адрес 0x00 и 0x7F. // Записываем новый адрес: // if(_readBytes(REG_BITS_0,1)==false){return false;} // Читаем 1 байт регистра «BITS_0» в массив data. data[0] |= 0b00000010; // Устанавливаем бит «SET_PIN_ADDRES» if(_writeBytes(REG_BITS_0,1)==false){return false;} // Записываем 1 байт в регистр «BITS_0» из массива data. data[0] = (newAddr<<1)|0x01; // Готовим новый адрес к записи в модуль. if(_writeBytes(REG_ADDRESS,1)==false){return false;} // Записываем 1 байт в регистр «ADDRESS» из массива data. delay(200); // Даём более чем достаточное время для применения модулем нового адреса. // Проверяем наличие модуля с новым адресом на шине I2C: // if(objI2C->checkAddress(newAddr)==false){return false;} // Если на шине I2C нет модуля с адресом newAddr, то возвращаем ошибку. valAddr = newAddr; // Сохраняем новый адрес как текущий. valAddrTemp = newAddr; // Сохраняем новый адрес как указанный. return true; // Возвращаем флаг успеха. }else{ // Иначе, если дисплей не инициализирован, то ... return false; // Возвращаем ошибку } // } // // // Перезагрузка модуля: // Возвращаемое значение: результат перезагрузки. bool iarduino_I2C_Matrix_8x8::reset (void){ // Параметр: отсутствует. if(valAddr){ // Если дисплей был инициализирован, то ... // Устанавливаем бит перезагрузки: // if(_readBytes(REG_BITS_0,1)==false){return false;} // Читаем 1 байт регистра «BITS_0» в массив data. data[0] |= 0b10000000; // Устанавливаем бит «SET_RESET» if(_writeBytes(REG_BITS_0,1)==false){return false;} // Записываем 1 байт в регистр «BITS_0» из массива data. // Ждём установки флага завершения перезагрузки: // do{ if(_readBytes(REG_FLAGS_0,1)==false){return false;} } // Читаем 1 байт регистра «REG_FLAGS_0» в массив data. while( (data[0]&0b10000000) == 0); // Повторяем чтение пока не установится флаг «FLG_RESET». return true; // }else{ // Иначе, если дисплей не инициализирован, то ... return false; // Возвращаем ошибку } // } // // // Автоопределение кодировки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::codingDetect (const char* str){ // Параметр: строка состоящая из символа 'п' и символа конца строки. if(strlen (str )== 2){codingName=X8_TXT_UTF8; } // Если символ 'п' занимает 2 байта, значит текст скетча в кодировке UTF8. else if(uint8_t(str[0])==0xAF){codingName=X8_TXT_CP866; } // Если символ 'п' имеет код 175, значит текст скетча в кодировке CP866. else if(uint8_t(str[0])==0xEF){codingName=X8_TXT_WIN1251;} // Если символ 'п' имеет код 239, значит текст скетча в кодировке WIN1251. } // // // Очистить дисплей: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::clrScr (uint8_t func){ // Параметр: функция анимации исчезания или 0. if(func<100){func=0;} // if(valAddr){ // Если дисплей был инициализирован, то ... // Очистка дисплея с анимацией: // if(func){ // // Определяем номер функции анимации: // data[0] = func-100; // func=100,101,102,103 => data[0]=0x04 - Исчезновение рябью в пустой фон data[0]/=4; // func=104,105,106,107 => data[0]=0x08 - Исчезновение сверху-вниз в пустой фон data[0]*=4; // func=108,109,110,111 => data[0]=0x0C - Исчезновение снизу-вверх в пустой фон data[0]+=4; // func=... // Записываем номер функции анимации: // _writeBytes(REG_8X8_FUNCTIONS,1); // Записываем 1 байт в регистр «FUNCTIONS» из массива data. // Ждём сброса регистра анимации: // do{ _readBytes(REG_8X8_FUNCTIONS,1); delay(500); }while( data[0] > 0 ); // Читаем 1 байт регистра «FUNCTIONS» в массив data, пока значение этого регистра не будет сброшено. // Очистка дисплея без анимации: // }else{ // // Останавливаем бегущую строку: // data[0]=0; _writeBytes(REG_8X8_TIME_STEP,1); // Сбрасываем регистр «TIME_STEP» для остановки бегущей строки, если она сейчас выводится. // Устанавливаем бит очистки дисплея: // _readBytes(REG_8X8_DATA,1); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data. data[0] |= 0b00010000; // Устанавливаем бит «CLEAR_SCR» _writeBytes(REG_8X8_DATA,1); // Записываем 1 байт в регистр «REG_8X8_DATA» из массива data. // Ждём сброса бита очистки дисплея: // do{ _readBytes(REG_8X8_DATA,1); }while( (data[0]&0b00010000) > 0 ); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data, пока в нём не сбросится бит «CLEAR_SCR». } // } // } // // // Залить дисплей: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::fillScr (uint8_t func){ // Параметр: функция анимации исчезания или 0. if(func<100){func=0;} // if(valAddr){ // Если дисплей был инициализирован, то ... // Заливка дисплея с анимацией: // if(func){ // // Определяем номер функции анимации: // data[0] = func-100; // func=100,101,102,103 => data[0]=0x06 - Исчезновение рябью в закрашенный фон data[0]/=4; // func=104,105,106,107 => data[0]=0x0A - Исчезновение сверху-вниз в закрашенный фон data[0]*=4; // func=108,109,110,111 => data[0]=0x0E - Исчезновение снизу-вверх в закрашенный фон data[0]+=6; // func=... // Записываем номер функции анимации: // _writeBytes(REG_8X8_FUNCTIONS,1); // Записываем 1 байт в регистр «FUNCTIONS» из массива data. // Ждём сброса регистра анимации: // do{ _readBytes(REG_8X8_FUNCTIONS,1); delay(500); }while( data[0] > 0 ); // Читаем 1 байт регистра «FUNCTIONS» в массив data, пока значение этого регистра не будет сброшено. // Заливка дисплея без анимации: // }else{ // // Останавливаем бегущую строку: // data[0]=0; _writeBytes(REG_8X8_TIME_STEP,1); // Сбрасываем регистр «TIME_STEP» для остановки бегущей строки, если она сейчас выводится. // Устанавливаем бит очистки дисплея: // _readBytes(REG_8X8_DATA,1); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data. data[0] |= 0b00100000; // Устанавливаем бит «FILL_SCR» _writeBytes(REG_8X8_DATA,1); // Записываем 1 байт в регистр «REG_8X8_DATA» из массива data. // Ждём сброса бита очистки дисплея: // do{ _readBytes(REG_8X8_DATA,1); }while( (data[0]&0b00100000) > 0 ); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data, пока в нём не сбросится бит «FILL_SCR». } // } // } // // // Инверсия цветов: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::invScr (void){ // Параметр: отсутствует. if(valAddr){ // Если дисплей был инициализирован, то ... delay(5); // Ждём 5мс. Это время требуется для выздать если функция invScr() была запущена сразу после вывода числа или символа. _readBytes(REG_8X8_DATA+1,8); // Читаем 8 байт начиная с регистра «REG_8X8_DATA_1» в массив data. for(int i=0; i<8; i++){ data[i] = ~data[i]; } // Инвертируем все биты в 8 элементах массива data. _writeBytes(REG_8X8_DATA+1,8); // Записываем 8 байт в регистры начиная с «REG_8X8_DATA_1» из массива data. } // } // // // Вывод изображения: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::drawImage (uint8_t* arr, uint8_t i, uint8_t j){ // Параметры: массив с изображением, [функция анимации появления] , и или [тип памяти массива]. uint8_t func=0; if(i>99){func=i;} if(j>99){func=j;} if(func%2){func--;} // Определяем наличие функции анимации в переданных параметрах. uint8_t memArr=X8_IMG_RAM; if(i==X8_IMG_ROM){memArr=X8_IMG_ROM;} if(j==X8_IMG_ROM){memArr=X8_IMG_ROM;} // Определяем наличие указаний, что изобрадение хранится в ПЗУ. if(valAddr){ // Если дисплей был инициализирован, то ... // Останавливаем бегущую строку: // data[0]=0; _writeBytes(REG_8X8_TIME_STEP,1); // Сбрасываем регистр «TIME_STEP» для остановки бегущей строки, если она сейчас выводится. // Если указано использовать анимацию появления, то: // if(func){ // if(func%4<2){ // X8_EMPTY_...: 100, 104, 108 ... // Если указана функция появления из пустого фона: // data[0]=1; _writeBytes(REG_8X8_FUNCTIONS,1); // Загружаем номер анимации предварительной очистки дисплея в регистр «FUNCTIONS». }else{ // X8_FILLED_...: 102, 106, 110 ... // Если указана функция появления из закрашенного фона: // data[0]=2; _writeBytes(REG_8X8_FUNCTIONS,1); // Загружаем номер анимации предварительной заливки дисплея в регистр «FUNCTIONS». } // delay(50); // Ждём применения функции предварительной очистки/закраски дисплея } // // Загружаем изображение: // for(int k=0; k<8; k++){ if(memArr==X8_IMG_RAM){ data[k]=arr[k]; }else{ data[k]=pgm_read_byte(&arr[k]); }} // Получаем данные для массива data по адресу arr из ОЗУ или ПЗУ. _writeBytes(REG_8X8_DATA+1,8); // Записываем 8 байт массива data в модуль начиная с регистра «REG_8X8_DATA_1». // Если указано использовать анимацию появления, то: // if(func){ // // Определяем и загружаем номер функции в регистр анимации: // data[0]=func-100+3; // 100=>3, 102=>5, 104=>7, 106=>9, 108=>B, 110=>D ... _writeBytes(REG_8X8_FUNCTIONS,1); // // Ждём сброса регистра анимации: // do{ _readBytes(REG_8X8_FUNCTIONS,1); delay(500); }while( data[0] > 0 ); // Читаем 1 байт регистра «FUNCTIONS» в массив data, пока значение этого регистра не будет сброшено. } // } // } // // // Вывод цифры: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::_printNum (uint8_t num, uint8_t func){ // Параметры: цифра, [функция анимации появления]. num%=10; // Делаем из числа цифру. if(func%2){func--;} // Делаем номер функции чётным: 101=>100, 103=>102, 105=>104, ... if(valAddr){ // Если дисплей был инициализирован, то ... // Останавливаем бегущую строку: // data[0]=0; _writeBytes(REG_8X8_TIME_STEP,1); // Сбрасываем регистр «TIME_STEP» для остановки бегущей строки, если она сейчас выводится. // Если указано использовать анимацию появления, то: // if(func){ // if(func%4<2){ // X8_EMPTY_...: 100, 104, 108 ... // Если указана функция появления из пустого фона: // data[0]=1; _writeBytes(REG_8X8_FUNCTIONS,1); // Загружаем номер анимации предварительной очистки дисплея в регистр «FUNCTIONS». }else{ // X8_FILLED_...: 102, 106, 110 ... // Если указана функция появления из закрашенного фона: // data[0]=2; _writeBytes(REG_8X8_FUNCTIONS,1); // Загружаем номер анимации предварительной заливки дисплея в регистр «FUNCTIONS». } // delay(50); // Ждём применения функции предварительной очистки/закраски дисплея } // // Загружаем цифру: // data[0]=num+0x30; _writeBytes(REG_8X8_SYMBOL_INPUT,1); // Загружаем код символа цифры в регистр «SYMBOL_INPUT», тогда символ цифры отобразится на дисплее. // Если указано использовать анимацию появления, то: // if(func){ // // Определяем и загружаем номер функции в регистр анимации: // data[0]=func-100+3; // 100=>3, 102=>5, 104=>7, 106=>9, 108=>B, 110=>D ... _writeBytes(REG_8X8_FUNCTIONS,1); // // Ждём сброса регистра анимации: // do{ _readBytes(REG_8X8_FUNCTIONS,1); delay(500); }while( data[0] > 0 ); // Читаем 1 байт регистра «FUNCTIONS» в массив data, пока значение этого регистра не будет сброшено. } // } // } // // // Вывод символа или загрузка строки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::_printStr (String str, uint8_t func){ // Параметры: символ или строка, [функция анимации появления]. if(str.length()==0){return;} // if(func%2){func--;} // Делаем номер функции чётным: 101=>100, 103=>102, 105=>104, ... if(valAddr){ // Если дисплей был инициализирован, то ... // Останавливаем бегущую строку: // data[0]=0; _writeBytes(REG_8X8_TIME_STEP,1); // Сбрасываем регистр «TIME_STEP» для остановки бегущей строки, если она сейчас выводится. // Если указано использовать анимацию появления, то: // if(func){ // if(func%4<2){ // X8_EMPTY_...: 100, 104, 108 ... // Если указана функция появления из пустого фона: // data[0]=1; _writeBytes(REG_8X8_FUNCTIONS,1); // Загружаем номер анимации предварительной очистки дисплея в регистр «FUNCTIONS». }else{ // X8_FILLED_...: 102, 106, 110 ... // Если указана функция появления из закрашенного фона: // data[0]=2; _writeBytes(REG_8X8_FUNCTIONS,1); // Загружаем номер анимации предварительной заливки дисплея в регистр «FUNCTIONS». } // delay(50); // Ждём применения функции предварительной очистки/закраски дисплея } // // Если str содержит 1 символ, то выводим его на дисплей: // if((str.length()==1)||(str.length()==2&&codingName==X8_TXT_UTF8&&(uint8_t(str[0])==208||uint8_t(str[0])==209))){// Если в str 1 символ или (в str 2 символа в кодировке UTF8 и код первого символа равен 208 или 209), то ... data[0]=_codingCP866(str).charAt(0); _writeBytes(REG_8X8_SYMBOL_INPUT,1); // Загружаем код символа в регистр «SYMBOL_INPUT», тогда символ отобразится на дисплее. // Если str содержит строку, то загружаем её в модуль: // }else{ // // Устанавливаем бит очистки текста бегущей строки: // _readBytes(REG_8X8_DATA,1); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data. data[0] |= 0b00001000; // Устанавливаем бит «CLEAR_STR» _writeBytes(REG_8X8_DATA,1); // Записываем 1 байт в регистр «REG_8X8_DATA» из массива data. // Ждём сброса бита очистки текста: // do{ _readBytes(REG_8X8_DATA,1); }while( (data[0]&0b00001000) > 0 ); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data, пока в нём не сбросится бит «CLEAR_STR». // Определяем количество символов которое требуется записать в память дисплея // stringLen=_codingCP866(str).length(); // Определяем количество символов строки str в кодировке CP866. // Загружаем новую строку посимвольно: // for(int i=0; i<stringLen; i++){ // Проходим по всем символам строки str в кодировке CP866 ... data[0]=_codingCP866(str).charAt(i); _writeBytes(REG_8X8_TEXT_INPUT,1); // Извлекаем код очередного символа из строки str и загружаем его в регистр «TEXT_INPUT». do{ _readBytes(REG_8X8_TEXT_INPUT,1); }while( data[0] > 0 ); // Читаем 1 байт регистра «TEXT_INPUT» в массив data, пока значение этого регистра не будет сброшено. } data[0]=0; _writeBytes(REG_8X8_TEXT_INPUT,1); // Загружаем код символа конца строки в регистр «TEXT_INPUT». } // // Если указано использовать анимацию появления, то: // if(func){ // // Определяем и загружаем номер функции в регистр анимации: // data[0]=func-100+3; // 100=>3, 102=>5, 104=>7, 106=>9, 108=>B, 110=>D ... _writeBytes(REG_8X8_FUNCTIONS,1); // // Ждём сброса регистра анимации: // do{ _readBytes(REG_8X8_FUNCTIONS,1); delay(500); }while( data[0] > 0 ); // Читаем 1 байт регистра «FUNCTIONS» в массив data, пока значение этого регистра не будет сброшено. } // } // } // // // Установка скорости бегущей строки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::autoScroll (uint8_t speed, uint16_t pause){ // Параметр: скорость от 0 до 255, [пауза от 0 до 25500 мс]). if(valAddr){ // Если дисплей был инициализирован, то ... data[0] = uint8_t(256-speed); // Определяем значение для регистра «TIME_STEP» Время затрачиваемое на один шаг автопрокрутки бегущей строки в сотых долях секунд от 0 (0,00 сек) до 255 (2,55 сек). data[1] = uint8_t(pause/100); // Определяем значение для регистра «TIME_PAUSE» Время паузы до повторной автопрокрутки всей бегущей строки в десятых долях секунд от 0 (0,0 сек) до 255 (25.5 сек). _writeBytes(REG_8X8_TIME_STEP,2); // Загружаем 2 байта массива data в модуль начиная с регистра «TIME_STEP». } // } // // // Установка позиции бегущей строки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::scrollPos (uint16_t pos){ // Параметр: позиция (либо в пикселях, либо в символах, зависит от scrollMod). if(valAddr){ // Если дисплей был инициализирован, то ... // Записываем значение в регистр сдвига бегущей строки: // data[0] = lowByte (pos); // Сохраняем младший байт из pos в массив data. data[1] = highByte(pos); // Сохраняем старший байт из pos в массив data. _writeBytes(REG_8X8_STEP_LEN,2); // Записываем 2 байта в двухбайтный регистр «STEP_LEN» из массива data. // Ждём сброса регистра сдвига бегущей строки: // do{ _readBytes(REG_8X8_STEP_LEN,2); }while( (data[0]>0)||(data[1]>0) ); // Читаем 2 байта двухбайтного регистра «REG_8X8_DATA» в массив data, пока оба байта не сбросятся в 0. } // } // // // Выбор направления движения бегущей строки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::scrollDir (bool f){ // Параметр: направление (1-право/0-лево). if(valAddr){ // Если дисплей был инициализирован, то ... _readBytes(REG_8X8_DATA,1); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data. if(f){data[0] |= 0b00000010;} // Устанавливаем бит «STEP_ROUTE». else {data[0] &= 0b11111101;} // Сбрасываем бит «STEP_ROUTE». _writeBytes(REG_8X8_DATA,1); // Записываем 1 байт в регистр «REG_8X8_DATA» из массива data. } // } // // // Выбор режима прокрутки бегущей строки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::scrollMod (bool f){ // Параметр: режим (1-посимвольный/0-попиксельный). if(valAddr){ // Если дисплей был инициализирован, то ... _readBytes(REG_8X8_DATA,1); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data. if(f){data[0] |= 0b00000100;} // Устанавливаем бит «STEP_MOD». else {data[0] &= 0b11111011;} // Сбрасываем бит «STEP_MOD». _writeBytes(REG_8X8_DATA,1); // Записываем 1 байт в регистр «REG_8X8_DATA» из массива data. } // } // // // Пошаговый сдвиг бегущей строки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::scrollStep (void){ // Параметр: отсутствует. if(valAddr){ // Если дисплей был инициализирован, то ... data[0] = 0b10000000; // Устанавливаем бит «STEP_ONE». _writeBytes(REG_8X8_STEP_LEN+1,1); // Записываем 1 байт в старший байт двухбайтного регистра «STEP_LEN» из массива data. } // } // // // Установка времени простоя на первом символе бегущей строки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::setTimeIdleFirst(uint16_t time){ // Параметр: время простоя в мс. if(valAddr){ // Если дисплей был инициализирован, то ... data[0] = uint8_t(time/10); // Определяем значение для регистра «TIME_START» Время простоя на первом символе бегущей строки в сотых долях секунд от 0 (0,00 сек) до 255 (2.55 сек). _writeBytes(REG_8X8_TIME_START,1); // Загружаем 1 байт массива data в регистр «TIME_START». } // } // // // Установка времени простоя на последнем символе бегущей строки: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::setTimeIdleLast(uint16_t time){ // Параметр: время простоя в мс. if(valAddr){ // Если дисплей был инициализирован, то ... data[0] = uint8_t(time/10); // Определяем значение для регистра «TIME_STOP» Время простоя на последнем символе бегущей строки в сотых долях секунд от 0 (0,00 сек) до 255 (2.55 сек). _writeBytes(REG_8X8_TIME_STOP,1); // Загружаем 1 байт массива data в регистр «TIME_STOP». } // } // // // поворот дисплея: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::angle (uint16_t deg){ // Параметр: угол 0°, 90°, 180°, 270°. if(valAddr){ // Если дисплей был инициализирован, то ... _readBytes(REG_8X8_DATA,1); // Читаем 1 байт регистра «REG_8X8_DATA» в массив data. data[0] &= 0b00111111; // Сбрасываем биты «TURN». data[0] |= (uint8_t(deg/90)<<6); // Устанавливаем биты «TURN» в соответствии со значением deg. _writeBytes(REG_8X8_DATA,1); // Записываем 1 байт в регистр «REG_8X8_DATA» из массива data. } // } // // // Установка скорости обновления дисплея: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::fps (uint8_t i){ // Параметр: количество кадров в секунду от 10 до 255. if(valAddr){ // Если дисплей был инициализирован, то ... data[0] = (i<10)? 10:i; // Сохраняем количество кадров в массив data. _writeBytes(REG_FREQUENCY,1); // Загружаем 1 байт массива data в регистр «FREQUENCY». } // } // // // Установка яркости дисплея: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::bright (uint8_t i){ // Параметр: яркость от 0 до 255. if(valAddr){ // Если дисплей был инициализирован, то ... data[0] = i; // Сохраняем яркость в массив data. _writeBytes(REG_BRIGHTNESS,1); // Загружаем 1 байт массива data в регистр «BRIGHTNESS». } // } // // // Замена изображения символа: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::changeChar (uint8_t i){ // Параметр: код символа изображение которого требуется изменить. if(valAddr){ // Если дисплей был инициализирован, то ... if(i==0){return;} // // Записываем код символа в регистр перезаписи изображения символа: // data[0]=i; _writeBytes(REG_8X8_SAVE_AS,1); // Записываем 1 байт в регистр «SAVE_AS» из массива data. // Ждём сброса регистра перезаписи изображения символа: // do{ _readBytes(REG_8X8_SAVE_AS,1); }while( data[0]>0 ); // Читаем 1 байт регистра «SAVE_AS» в массив data, пока он не сбросятся в 0. } // } // // // Установка ширины изображений всех символов: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::setCharWidth (uint8_t i){ // Параметр: ширина символов в пикселях от 3 до 7. if(valAddr){ // Если дисплей был инициализирован, то ... if( (i<3)||(i>7) ){return;} charWidth=i; _setChar0(); // Проверяем введённые данные и сохраняем их. } // } // // // Установка межсимвольного интервала: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::setCharInterval(uint8_t i){ // Параметр: межсимвольный интервал в пикселях. if(valAddr){ // Если дисплей был инициализирован, то ... charInterval=i; _setChar0(); // Сохраняем межсимвольный интервал. } // } // // // Установка отступа от левого края до символа: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::setCharIndent (uint8_t i){ // Параметр: отступ от левого края в пикселях. if(valAddr){ // Если дисплей был инициализирован, то ... if( i>=8 ){return;} charIndent = i; _setChar0(); // Проверяем введённые данные и сохраняем их. } // } // // // Установка ширины, интервала и отступа символов: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::_setChar0 (void){ // Объявляем функцию установки ширины, интервала и отступа символов (Параметр: отсутствует). if(valAddr){ // Если дисплей был инициализирован, то ... uint8_t tmpImage[8]; // Объявляем массив для временного хранения изображения экрана. uint8_t tmpImageChar0[8]; // Объявляем массив для временного хранения изображения символа с кодом 0. uint8_t tmpTimeStep; // Объявляем переменную для временного хранения времени затрачиваемого на один шаг автопрокрутки бегущей строки. // Готовим изображение символа с кодом 0: // memset(tmpImageChar0,0,8); // Чистим массив tmpImageChar0 tmpImageChar0[0]=charWidth; // Добавляем в массив tmpImageChar0 значение ширины символов. tmpImageChar0[1]=charInterval; // Добавляем в массив tmpImageChar0 значение межсимвольного интервала. tmpImageChar0[2]=charIndent; // Добавляем в массив tmpImageChar0 значение отступа от левого края экрана до символа. // Останавливаем бегущую строку: // _readBytes(REG_8X8_TIME_STEP,1); tmpTimeStep=data[0]; // Читаем 1 байт из регистра «TIME_STEP» через массив data в переменную tmpTimeStep. if(tmpTimeStep>0){ data[0]=0; _writeBytes(REG_8X8_TIME_STEP,1); } // Если включена автопрокрутка бегущей строки (tmpTimeStep>0) то останавливаем бегущую строку сбросив регистр «TIME_STEP» в 0. // Сохраняем текущее изображение матрицы в массив tmpImage: // getImage(tmpImage); // Сохраняем текущее изображение матрицы в массив tmpImage. // Сохраняем изображение символа с кодом 0: // drawImage(tmpImageChar0); // Выводим изображение из массива tmpImageChar0 data[0]=0; _writeBytes(REG_8X8_SAVE_AS,1); // Записываем 1 байт в регистр «SAVE_AS» из массива data. delay(50); // Ждём пока изображение экрана не сохранится в таблицу символов. // Восстанавливаем изображение экрана на то, что было до вызова функции _setChar0(): // if(tmpTimeStep>0){ data[0]=tmpTimeStep; _writeBytes(REG_8X8_TIME_STEP,1); } // Если прокручивалась бегущая строка, то возобновляем её прокрутку. else{drawImage(tmpImage);} // Иначе восстанавливаем изображение. } // } // // // Получение массива с данными текущего изображения на экране: // Возвращаемое значение: отсутствует. void iarduino_I2C_Matrix_8x8::getImage (uint8_t* i){ // Параметр: указатель на массив в который требуется сохранить изображение. if(valAddr){ // Если дисплей был инициализирован, то ... delay(5); // Ждём 5мс. Это время требуется для выздать если функция invScr() была запущена сразу после вывода числа или символа. _readBytes(REG_8X8_DATA+1,8); // Читаем 8 байт начиная с регистра «REG_8X8_DATA_1» в массив data. for(int j=0; j<8; j++){ i[j] = data[j]; } // Копируем данный массива data в массив i. } // } // // // Чтение данных из регистров в массив data: // Возвращаемое значение: результат чтения (true/false). bool iarduino_I2C_Matrix_8x8::_readBytes (uint8_t reg, uint8_t sum){ // Параметры: reg - номер первого регистра, sum - количество читаемых байт. bool result=false; // Определяем флаг для хранения результата чтения. uint8_t sumtry=10; // Определяем переменную для подсчёта количества оставшихся попыток чтения. do{ result = objI2C->readBytes(valAddr, reg, data, sum); // Считываем из модуля valAddr, начиная с регистра reg, в массив data, sum байт. sumtry--; if(!result){delay(1);} // Уменьшаем количество попыток чтения и устанавливаем задержку при неудаче. } while (!result && sumtry>0); // Повторяем чтение если оно завершилось неудачей, но не более sumtry попыток. delayMicroseconds(500); // Между пакетами необходимо выдерживать паузу. return result; // Возвращаем результат чтения (true/false). } // // // Запись данных в регистры из массива data: // Возвращаемое значение: результат записи (true/false). bool iarduino_I2C_Matrix_8x8::_writeBytes (uint8_t reg, uint8_t sum, uint8_t num){ // Параметры: reg - номер первого регистра, sum - количество записываемых байт, num - номер первого элемента массива data. bool result=false; // Определяем флаг для хранения результата записи. uint8_t sumtry=10; // Определяем переменную для подсчёта количества оставшихся попыток записи. do{ result = objI2C->writeBytes(valAddr, reg, &data[num], sum); // Записываем в модуль valAddr начиная с регистра reg, sum байи из массива data начиная с элемента num. sumtry--; if(!result){delay(1);} // Уменьшаем количество попыток записи и устанавливаем задержку при неудаче. } while (!result && sumtry>0); // Повторяем запись если она завершилась неудачей, но не более sumtry попыток. delayMicroseconds(500); // Между пакетами необходимо выдерживать паузу. return result; // Возвращаем результат записи (true/false). } // // // Преобразование строки из кодировки codingName в кодировку CP866 // Возвращаемое значение: строка в кодировке CP866. String iarduino_I2C_Matrix_8x8::_codingCP866 (String StrIn){ // Параметр: строка в кодировке codingName. String StrOut; // Определяем строку для вывода результата. uint8_t i = 0; // Определяем переменную хранящую номер символа в строке StrIn. switch(codingName){ // Тип кодировки строки StrIn. // Преобразуем текст из кодировки UTF-8: // case X8_TXT_UTF8: // while ( uint8_t(StrIn[i])> 0 && i < 0xFF ){ // Если код текущего символа строки StrIn больше 0 и № текушего символа строки StrIn меньше 255, то ... if( uint8_t(StrIn[i])==0xD0 && uint8_t(StrIn[i+1])>=0x90 && uint8_t(StrIn[i+1])<=0xBF ){StrOut+=char(uint8_t(StrIn[i+1])-0x10); i++;}else // Если код текущего символа равен 208, а за ним следует символ с кодом 144...191, значит это буква «А»...«п» требующая преобразования к коду 128...175 if( uint8_t(StrIn[i])==0xD0 && uint8_t(StrIn[i+1])==0x81 ){StrOut+= 0xF0 ; i++;}else // Если код текущего символа равен 208, а за ним следует символ с кодом 129 , значит это буква «Ё» требующая преобразования к коду 240 if( uint8_t(StrIn[i])==0xD1 && uint8_t(StrIn[i+1])>=0x80 && uint8_t(StrIn[i+1])<=0x8F ){StrOut+=char(uint8_t(StrIn[i+1])+0x60); i++;}else // Если код текущего символа равен 209, а за ним следует символ с кодом 128...143, значит это буква «р»...«я» требующая преобразования к коду 224...239 if( uint8_t(StrIn[i])==0xD1 && uint8_t(StrIn[i+1])==0x91 ){StrOut+= 0xF1 ; i++;}else // Если код текущего символа равен 209, а за ним следует символ с кодом 145 , значит это буква «ё» требующая преобразования к коду 241 {StrOut+=char( StrIn[i] ); } i++; // Иначе не меняем символ. } // break; // // Преобразуем текст из кодировки WINDOWS-1251: // case X8_TXT_WIN1251: // while ( uint8_t(StrIn[i])> 0 && i < 0xFF ){ // Если код текущего символа строки StrIn больше 0 и № текушего символа строки StrIn меньше 255, то ... if( uint8_t(StrIn[i])>=0xC0 && uint8_t(StrIn[i])<=0xEF ){StrOut+=char(uint8_t(StrIn[i])-0x40);}else // Если код текущего символа равен 192...239, значит это буква «А»...«п» требующая преобразования к коду 128...175 if( uint8_t(StrIn[i])>=0xF0 && uint8_t(StrIn[i])<=0xFF ){StrOut+=char(uint8_t(StrIn[i])-0x10);}else // Если код текущего символа равен 240...255, значит это буква «р»...«я» требующая преобразования к коду 224...239 if( uint8_t(StrIn[i])==0xA8 ){StrOut+= 0xF0 ;}else // Если код текущего символа равен 168 , значит это буква «Ё» требующая преобразования к коду 240 if( uint8_t(StrIn[i])==0xB8 ){StrOut+= 0xF1 ;}else // Если код текущего символа равен 184 , значит это буква «ё» требующая преобразования к коду 241 {StrOut+=char( StrIn[i] );} i++; // Иначе не меняем символ. } // break; // default: StrOut=StrIn; // } return StrOut; // Возвращаем строку StrOut. } //
; A011942: [ n(n-1)(n-2)(n-3)/32 ]. ; 0,0,0,0,0,3,11,26,52,94,157,247,371,536,750,1023,1365,1785,2295,2907,3633,4488,5486,6641,7969,9487,11212,13162,15356,17813,20553,23598,26970,30690,34782,39270,44178 bin $0,4 mul $0,24 div $0,32
; Troy's HBC-56 - LCD Tilemap tests ; ; Copyright (c) 2021 Troy Schrapel ; ; This code is licensed under the MIT license ; ; https://github.com/visrealm/hbc-56 ; !src "hbc56kernel.inc" !align 255, 0 c64FontData: !bin "lcd/fonts/c64-font-ascii.bin" ; ----------------------------------------------------------------------------- ; metadata for the HBC-56 kernel ; ----------------------------------------------------------------------------- hbc56Meta: +setHbcMetaTitle "LCD TILEMAP" +consoleLCDMode rts hbc56Main: jsr lcdInit jsr lcdHome jsr lcdClear jsr lcdGraphicsMode +tilemapCreateDefault (TILEMAP_SIZE_X_16 | TILEMAP_SIZE_Y_8), c64FontData +tilemapSetActive TILEMAP_FIXED_ADDRESS TILE_OFFSET = $c0 lda #32 sta TILE_OFFSET start: ldy #0 clc - tya clc adc TILE_OFFSET sta (TILEMAP_TMP_BUFFER_ADDR), y iny cpy #128 bne - ;+memcpy TILEMAP_DEFAULT_BUFFER_ADDRESS, screenBuffer, 128 jsr tilemapRenderToLcd inc TILE_OFFSET jsr delay jmp start medDelay: jsr delay jsr delay delay: ldx #255 ldy #255 .loop: dex bne .loop ldx #255 dey bne .loop rts screenBuffer: !text "* HBC-56 BASIC *" !text " 64K RAM SYSTEM " !text " " !text "READY. " !text "LOAD *,8,1 " !text "LOADING... " !text "RUN "
/************************************************************************** Copyright (c) 2017 sewenew 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. *************************************************************************/ #ifdef _MSC_VER #include <unordered_map> #include <vector> #else #include <unistd.h> // for getopt on non-Windows platform #endif #include <string> #include <chrono> #include <tuple> #include <iostream> #include <sw/redis++/redis++.h> #include "sanity_test.h" #include "connection_cmds_test.h" #include "keys_cmds_test.h" #include "string_cmds_test.h" #include "list_cmds_test.h" #include "hash_cmds_test.h" #include "set_cmds_test.h" #include "zset_cmds_test.h" #include "hyperloglog_cmds_test.h" #include "geo_cmds_test.h" #include "script_cmds_test.h" #include "pubsub_test.h" #include "pipeline_transaction_test.h" #include "threads_test.h" #include "stream_cmds_test.h" #include "benchmark_test.h" namespace { #ifdef _MSC_VER // A simple implementation of `getopt` on Windows platform. char *optarg = nullptr; int optind = 1; int getopt(int argc, char **argv, const char *optstring); #endif struct TestOptions { bool run_thread_test = false; }; void print_help(); auto parse_options(int argc, char **argv) -> std::tuple<sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::test::BenchmarkOptions>, TestOptions>; template <typename RedisInstance> void run_test(const sw::redis::ConnectionOptions &opts, const TestOptions &test_options); template <typename RedisInstance> void run_benchmark(const sw::redis::ConnectionOptions &opts, const sw::redis::test::BenchmarkOptions &benchmark_opts); } int main(int argc, char **argv) { try { sw::redis::Optional<sw::redis::ConnectionOptions> opts; sw::redis::Optional<sw::redis::ConnectionOptions> cluster_node_opts; sw::redis::Optional<sw::redis::test::BenchmarkOptions> benchmark_opts; TestOptions test_options; std::tie(opts, cluster_node_opts, benchmark_opts, test_options) = parse_options(argc, argv); if (opts) { std::cout << "Testing Redis..." << std::endl; if (benchmark_opts) { run_benchmark<sw::redis::Redis>(*opts, *benchmark_opts); } else { run_test<sw::redis::Redis>(*opts, test_options); } } if (cluster_node_opts) { std::cout << "Testing RedisCluster..." << std::endl; if (benchmark_opts) { run_benchmark<sw::redis::RedisCluster>(*cluster_node_opts, *benchmark_opts); } else { run_test<sw::redis::RedisCluster>(*cluster_node_opts, test_options); } } std::cout << "Pass all tests" << std::endl; } catch (const sw::redis::Error &e) { std::cerr << "Test failed: " << e.what() << std::endl; return -1; } return 0; } namespace { #ifdef _MSC_VER std::vector<std::string> split(const std::string &str) { if (str.empty()) { return {}; } std::vector<std::string> result; std::string::size_type pos = 0; std::string::size_type idx = 0; while (true) { pos = str.find(':', idx); if (pos == std::string::npos) { result.push_back(str.substr(idx)); break; } result.push_back(str.substr(idx, pos - idx)); idx = pos + 1; } return result; } std::unordered_map<char, bool> parse_opt_map(const std::string &opts) { auto fields = split(opts); if (fields.empty()) { return {}; } std::unordered_map<char, bool> opt_map; for (auto iter = fields.begin(); iter != fields.end() - 1; ++iter) { const auto &field = *iter; if (field.empty()) { continue; } for (auto it = field.begin(); it != field.end() - 1; ++it) { opt_map.emplace(*it, false); } opt_map.emplace(field.back(), true); } const auto &last_opts = fields.back(); if (!last_opts.empty()) { for (auto c : last_opts) { opt_map.emplace(c, false); } } return opt_map; } int getopt(int argc, char **argv, const char *optstring) { if (argc < 1 || argv == nullptr || optstring == nullptr || optind >= argc) { return -1; } auto opt_map = parse_opt_map(optstring); std::string opt = *(argv + optind); if (opt.size() != 2 || opt.front() != '-') { return -1; } auto result = opt.back(); auto iter = opt_map.find(result); if (iter == opt_map.end()) { return -1; } ++optind; if (iter->second) { if (optind == argc) { return -1; } optarg = *(argv + optind); ++optind; } return result; } #endif void print_help() { std::cerr << "Usage: test_redis++ -h host -p port" << " -n cluster_node -c cluster_port [-a auth] [-b]\n\n"; std::cerr << "See https://github.com/sewenew/redis-plus-plus#run-tests-optional" << " for details on how to run test" << std::endl; } auto parse_options(int argc, char **argv) -> std::tuple<sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::test::BenchmarkOptions>, TestOptions> { std::string host; int port = 0; std::string auth; std::string cluster_node; int cluster_port = 0; bool benchmark = false; sw::redis::test::BenchmarkOptions tmp_benchmark_opts; TestOptions test_options; int opt = 0; while ((opt = getopt(argc, argv, "h:p:a:n:c:k:v:r:t:bs:m")) != -1) { try { switch (opt) { case 'h': host = optarg; break; case 'p': port = std::stoi(optarg); break; case 'a': auth = optarg; break; case 'n': cluster_node = optarg; break; case 'c': cluster_port = std::stoi(optarg); break; case 'b': benchmark = true; break; case 'k': tmp_benchmark_opts.key_len = std::stoi(optarg); break; case 'v': tmp_benchmark_opts.val_len = std::stoi(optarg); break; case 'r': tmp_benchmark_opts.total_request_num = std::stoi(optarg); break; case 't': tmp_benchmark_opts.thread_num = std::stoi(optarg); break; case 's': tmp_benchmark_opts.pool_size = std::stoi(optarg); break; case 'm': test_options.run_thread_test = true; break; default: throw sw::redis::Error("Unknow command line option"); break; } } catch (const sw::redis::Error &e) { print_help(); throw; } catch (const std::exception &e) { print_help(); throw sw::redis::Error("Invalid command line option"); } } sw::redis::Optional<sw::redis::ConnectionOptions> opts; if (!host.empty() && port > 0) { sw::redis::ConnectionOptions tmp; tmp.host = host; tmp.port = port; tmp.password = auth; opts = sw::redis::Optional<sw::redis::ConnectionOptions>(tmp); } sw::redis::Optional<sw::redis::ConnectionOptions> cluster_opts; if (!cluster_node.empty() && cluster_port > 0) { sw::redis::ConnectionOptions tmp; tmp.host = cluster_node; tmp.port = cluster_port; tmp.password = auth; cluster_opts = sw::redis::Optional<sw::redis::ConnectionOptions>(tmp); } if (!opts && !cluster_opts) { print_help(); throw sw::redis::Error("Invalid connection options"); } sw::redis::Optional<sw::redis::test::BenchmarkOptions> benchmark_opts; if (benchmark) { benchmark_opts = sw::redis::Optional<sw::redis::test::BenchmarkOptions>(tmp_benchmark_opts); } return std::make_tuple(std::move(opts), std::move(cluster_opts), std::move(benchmark_opts), test_options); } template <typename RedisInstance> void run_test(const sw::redis::ConnectionOptions &opts, const TestOptions &test_options) { auto instance = RedisInstance(opts); sw::redis::test::SanityTest<RedisInstance> sanity_test(opts, instance); sanity_test.run(); std::cout << "Pass sanity tests" << std::endl; sw::redis::test::ConnectionCmdTest<RedisInstance> connection_test(instance); connection_test.run(); std::cout << "Pass connection commands tests" << std::endl; sw::redis::test::KeysCmdTest<RedisInstance> keys_test(instance); keys_test.run(); std::cout << "Pass keys commands tests" << std::endl; sw::redis::test::StringCmdTest<RedisInstance> string_test(instance); string_test.run(); std::cout << "Pass string commands tests" << std::endl; sw::redis::test::ListCmdTest<RedisInstance> list_test(instance); list_test.run(); std::cout << "Pass list commands tests" << std::endl; sw::redis::test::HashCmdTest<RedisInstance> hash_test(instance); hash_test.run(); std::cout << "Pass hash commands tests" << std::endl; sw::redis::test::SetCmdTest<RedisInstance> set_test(instance); set_test.run(); std::cout << "Pass set commands tests" << std::endl; sw::redis::test::ZSetCmdTest<RedisInstance> zset_test(instance); zset_test.run(); std::cout << "Pass zset commands tests" << std::endl; sw::redis::test::HyperloglogCmdTest<RedisInstance> hll_test(instance); hll_test.run(); std::cout << "Pass hyperloglog commands tests" << std::endl; sw::redis::test::GeoCmdTest<RedisInstance> geo_test(instance); geo_test.run(); std::cout << "Pass geo commands tests" << std::endl; sw::redis::test::ScriptCmdTest<RedisInstance> script_test(instance); script_test.run(); std::cout << "Pass script commands tests" << std::endl; sw::redis::test::PubSubTest<RedisInstance> pubsub_test(instance); pubsub_test.run(); std::cout << "Pass pubsub tests" << std::endl; sw::redis::test::PipelineTransactionTest<RedisInstance> pipe_tx_test(instance); pipe_tx_test.run(); std::cout << "Pass pipeline and transaction tests" << std::endl; if (test_options.run_thread_test) { sw::redis::test::ThreadsTest<RedisInstance> threads_test(opts); threads_test.run(); std::cout << "Pass threads tests" << std::endl; } sw::redis::test::StreamCmdsTest<RedisInstance> stream_test(instance); stream_test.run(); std::cout << "Pass stream commands tests" << std::endl; } template <typename RedisInstance> void run_benchmark(const sw::redis::ConnectionOptions &opts, const sw::redis::test::BenchmarkOptions &benchmark_opts) { std::cout << "Benchmark test options:" << std::endl; std::cout << " Thread number: " << benchmark_opts.thread_num << std::endl; std::cout << " Connection pool size: " << benchmark_opts.pool_size << std::endl; std::cout << " Length of key: " << benchmark_opts.key_len << std::endl; std::cout << " Length of value: " << benchmark_opts.val_len << std::endl; auto instance = RedisInstance(opts); sw::redis::test::BenchmarkTest<RedisInstance> benchmark_test(benchmark_opts, instance); benchmark_test.run(); } }