text
stringlengths
1
1.05M
#!/ur/local/bin/zasm -o original/ .org 100h .align 16 .db "AAA " .if 11 < 0x100 .db "richtig " .else .db "falsch " .endif .db " EEE" .align 16 .db "AAA " .if 1100 < 0x100 .db "falsch" .else .db "richtig" .endif .db " EEE" .macro TEST &arg1 .align 16 .db "AA " .if &arg1 < 0x100 .if &arg1<0 .db "arg < 0" .else .db "arg < 256" .endif .else .db "arg >= 256" .endif .db " EE" .endm TEST 1 TEST 0 TEST 255 TEST 256 TEST 3000 TEST -20556 .align 16 .db "----------------" .if 0 .db "falsch" .elif 0 .db "falsch" .elif 0 .db "falsch" .elif 1 .db "richtig" .elif 1 .db "falsch" .elif 0 .db "falsch" .else .db "falsch" .endif .align 16 .db "----------------" .if 0 .db "falsch" .elif 0 .db "falsch" .elif 0 .db "falsch" .elif 0 .db "falsch" .elif 0 .db "falsch" .else .db "richtig" .endif .align 16 .db "----------------" .if 1 .if 1 .db "richtig" .elif 0 .db "falsch" .else .db "falsch" .endif .else .if 1 .db "falsch" .elif 0 .db "falsch" .else .db "falsch" .endif .endif .align 16 .db "----------------" .if 1 .if 0 .db "falsch" .elif 0 .db "falsch" .else .db "richtig" .endif .else .if 0 .db "falsch" .elif 0 .db "falsch" .else .db "falsch" .endif .endif .align 16 .db "----------------" .if 0 .if 0 .db "falsch" .elif 0 .db "falsch" .else .db "falsch" .endif .else .if 0 .db "falsch" .elif 0 .db "falsch" .else .db "richtig" .endif .endif .align 16 .db "----------------" .if 0 .if 0 .db "falsch" .elif 0 .db "falsch" .else .db "falsch" .endif .else .if 0 .db "falsch" .elif 1 .db "richtig" .else .db "falsch" .endif .endif .align 16 .db "----------------" .if 0 .if 0 .db "falsch" .elif 0 .db "falsch" .else .db "falsch" .endif .else .if 1 .db "richtig" .elif 0 .db "falsch" .else .db "falsch" .endif .endif .align 16 .db "----------------" .if 1 .if 0 .db "falsch" .elif 0 .db "falsch" .else .db "richtig" .endif .elif 1 .if 1 .db "falsch" .elif 0 .db "falsch" .else .db "falsch" .endif .else .if 1 .db "falsch" .elif 0 .db "falsch" .else .db "falsch" .endif .endif
SECTION code_fp_am9511 PUBLIC exp2 EXTERN cam32_sccz80_exp2 defc exp2 = cam32_sccz80_exp2 ; SDCC bridge for Classic IF __CLASSIC PUBLIC _exp2 EXTERN cam32_sdcc_exp2 defc _exp2 = cam32_sdcc_exp2 ENDIF
; A017795: Binomial coefficients C(79,n). ; 1,79,3081,79079,1502501,22537515,277962685,2898753715,26088783435,205811513765,1440680596355,9036996468045,51209646652255,263926640438545,1244225590638855,5391644226101705,21566576904406820,79923196763389980,275291011073898820,883829035553043580,2651487106659130740,7449416156804224460,19639369867938409940,48671481846629972460,113566790975469935740,249846940146033858628,518912875687916475612,1018606755979984192868,1891698261105684929612,3326779700565170048628,5544632834275283414380,8764097060628673784020,13146145590943010676030,18723298265888530356770,25331521183260952835630,32569098664192653645810,39806676145124354455990,46261812817306682205610,51131477324391596121990,53753604366668088230810,53753604366668088230810,51131477324391596121990,46261812817306682205610,39806676145124354455990,32569098664192653645810,25331521183260952835630,18723298265888530356770,13146145590943010676030,8764097060628673784020,5544632834275283414380,3326779700565170048628,1891698261105684929612,1018606755979984192868,518912875687916475612,249846940146033858628,113566790975469935740,48671481846629972460,19639369867938409940,7449416156804224460,2651487106659130740,883829035553043580,275291011073898820,79923196763389980,21566576904406820,5391644226101705,1244225590638855,263926640438545,51209646652255,9036996468045,1440680596355,205811513765,26088783435,2898753715,277962685,22537515,1502501,79079,3081,79,1 mov $1,79 bin $1,$0 mov $0,$1
; ******************************************************************************************** ; ******************************************************************************************** ; ; Name : char.asm ; Purpose : .. ; Created : 15th Nov 1991 ; Updated : 4th Jan 2021 ; Authors : Fred Bowen ; ; ******************************************************************************************** ; ******************************************************************************************** ;***************************************************************** ;* CHAR draw a character string ;* ;* Syntax : CHAR column, row, height, width, direction, "string" [,charsetadr [,bank]] ;* ;* parm1 = column# ;* parm2 = row lo ;* parm3 = row hi ;* parm4 = height ;* parm5 = width ;* parm6 = direction ;* parm7 = len of string ;* parm8 = lo addr of string ;* parm9 = hi addr of string ;* parm10 = lo addr of character set $29800 default ;* parm11 = hi addr of character set ;* parm12 = bank of character set [910912] ;**************************************************************** C65__char jsr CheckGraphicMode jsr getbyt ; get column stx GKI__parm1 jsr comsad ; get row sty GKI__parm2 sta GKI__parm3 jsr combyt ; get height stx GKI__parm4 jsr combyt ; get width stx GKI__parm5 jsr combyt ; get direction stx GKI__parm6 jsr chkcom jsr frmevl ; evaluate the string jsr chkstr ; type mismatch error if not string ldy #0 jsr indfmo ; pointer to string descriptor is left in the fac by frmevl sta GKI__parm7 ; length ???? check for null string ???? pha iny jsr indfmo sta GKI__parm8 ; adrlo iny jsr indfmo sta GKI__parm9 ; adrhi jsr frefac ; [910917] pla jsr getspa jsr optwrd ; get charset address (????bank) bcs l277_1 ; given ldy #<$9800 ; not given- use ROM as default [910207] FAB lda #>$9800 ; ???? uc/lc or graphic set ???? l277_1 sty GKI__parm10 ; lo sta GKI__parm11 ; hi ldx #2 ; default to ROM bank 2 [910912] FAB jsr optbyt stx GKI__parm12 lda GKI__parm7 ; ???? check for null string ???? beq l277_2 jmp ($802c) ; bra kg65.char l277_2 rts ; ******************************************************************************************** ; ; Date Changes ; ==== ======= ; ; ********************************************************************************************
10001011 // push 11 (20) 10001010 // push 10 (10) 00000000 // add 10101010// pop -> 10 10001001//push 9 (3) 10001000//push 8 (4) 00000000// add 10101011//pop -> 11 00000100//DATA ... 00000011 00001010 00010100 00000000 00000000 00000000 00000000
; test source file for assembling to binary files ; build with: ; nasm -f bin -o bintest.com bintest.asm ; When run (as a DOS .COM file), this program should print ; hello, world ; on two successive lines, then exit cleanly. ; This file should test the following: ; [1] Define a text-section symbol ; [2] Define a data-section symbol ; [3] Define a BSS-section symbol ; [4] Define a NASM local label ; [5] Reference a NASM local label ; [6] Reference a text-section symbol in the text section ; [7] Reference a data-section symbol in the text section ; [8] Reference a BSS-section symbol in the text section ; [9] Reference a text-section symbol in the data section ; [10] Reference a data-section symbol in the data section ; [11] Reference a BSS-section symbol in the data section BITS 16 ORG 0x100 SECTION .text jmp start ; [6] endX mov ax,0x4c00 ; [1] int 0x21 start mov byte [bss_sym],',' ; [1] [8] mov bx,[bssptr] ; [7] mov al,[bx] mov bx,[dataptr] ; [7] mov [bx],al mov cx,2 .loop mov dx,datasym ; [1] [4] [7] mov ah,9 push cx int 0x21 pop cx loop .loop ; [5] [6] mov bx,[textptr] ; [7] jmp bx SECTION .data datasym db 'hello world', 13, 10, '$' ; [2] bssptr dw bss_sym ; [2] [11] dataptr dw datasym+5 ; [2] [10] textptr dw endX ; [2] [9] SECTION .bss bss_sym resb 1 ; [3]
#include "il2cpp-config.h" #include "metadata/GenericMetadata.h" #include "metadata/GenericMethod.h" #include "metadata/GenericSharing.h" #include "metadata/Il2CppGenericMethodCompare.h" #include "metadata/Il2CppGenericMethodHash.h" #include "os/Mutex.h" #include "utils/Memory.h" #include "vm/Class.h" #include "vm/Exception.h" #include "vm/GenericClass.h" #include "vm/MetadataAlloc.h" #include "vm/MetadataCache.h" #include "vm/MetadataLock.h" #include "vm/Method.h" #include "vm/Runtime.h" #include "vm/Type.h" #include "utils/Il2CppHashMap.h" #include "il2cpp-class-internals.h" #include "il2cpp-runtime-metadata.h" #include "il2cpp-runtime-stats.h" #include <string> using il2cpp::metadata::GenericMetadata; using il2cpp::metadata::GenericSharing; using il2cpp::os::FastAutoLock; using il2cpp::vm::Class; using il2cpp::vm::GenericClass; using il2cpp::vm::MetadataCalloc; using il2cpp::vm::MetadataCache; using il2cpp::vm::Method; using il2cpp::vm::Runtime; using il2cpp::vm::Type; namespace il2cpp { namespace metadata { typedef Il2CppHashMap<const Il2CppGenericMethod*, MethodInfo*, Il2CppGenericMethodHash, Il2CppGenericMethodCompare> Il2CppGenericMethodMap; static Il2CppGenericMethodMap s_GenericMethodMap; static void AGenericMethodWhichIsTooDeeplyNestedWasInvoked() { vm::Exception::Raise(vm::Exception::GetMaxmimumNestedGenericsException()); } const MethodInfo* GenericMethod::GetMethod(const Il2CppGenericMethod* gmethod, bool copyMethodPtr) { FastAutoLock lock(&il2cpp::vm::g_MetadataLock); // This can be NULL only when we have hit the generic recursion depth limit. if (gmethod == NULL) { MethodInfo* newMethod = (MethodInfo*)MetadataCalloc(1, sizeof(MethodInfo)); newMethod->methodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked; return newMethod; } Il2CppGenericMethodMap::const_iterator iter = s_GenericMethodMap.find(gmethod); if (iter != s_GenericMethodMap.end()) return iter->second; if (copyMethodPtr) { Il2CppGenericMethod *newGMethod = vm::MetadataAllocGenericMethod(); newGMethod->methodDefinition = gmethod->methodDefinition; newGMethod->context = gmethod->context; gmethod = newGMethod; } const MethodInfo* methodDefinition = gmethod->methodDefinition; Il2CppClass* declaringClass = methodDefinition->klass; if (gmethod->context.class_inst) { IL2CPP_ASSERT(!declaringClass->generic_class); Il2CppGenericClass* genericClassDeclaringType = GenericMetadata::GetGenericClass(methodDefinition->klass, gmethod->context.class_inst); declaringClass = GenericClass::GetClass(genericClassDeclaringType); // we may fail if we cannot construct generic type if (!declaringClass) return NULL; } MethodInfo* newMethod = (MethodInfo*)MetadataCalloc(1, sizeof(MethodInfo)); // we set this here because the initialization may recurse and try to retrieve the same generic method // this is safe because we *always* take the lock when retrieving the MethodInfo from a generic method. // if we move lock to only if MethodInfo needs constructed then we need to revisit this since we could return a partially initialized MethodInfo s_GenericMethodMap.insert(std::make_pair(gmethod, newMethod)); newMethod->klass = declaringClass; newMethod->flags = methodDefinition->flags; newMethod->iflags = methodDefinition->iflags; newMethod->slot = methodDefinition->slot; newMethod->name = methodDefinition->name; newMethod->is_generic = false; newMethod->is_inflated = true; newMethod->token = methodDefinition->token; newMethod->return_type = GenericMetadata::InflateIfNeeded(methodDefinition->return_type, &gmethod->context, true); newMethod->parameters_count = methodDefinition->parameters_count; newMethod->parameters = GenericMetadata::InflateParameters(methodDefinition->parameters, methodDefinition->parameters_count, &gmethod->context, true); newMethod->genericMethod = gmethod; if (!gmethod->context.method_inst) { if (methodDefinition->is_generic) newMethod->is_generic = true; if (!declaringClass->generic_class) { newMethod->genericContainerHandle = methodDefinition->genericContainerHandle; } newMethod->methodMetadataHandle = methodDefinition->methodMetadataHandle; } else { // we only need RGCTX for generic instance methods newMethod->rgctx_data = GenericMetadata::InflateRGCTX(gmethod->methodDefinition->klass->image, gmethod->methodDefinition->token, &gmethod->context); } newMethod->invoker_method = MetadataCache::GetInvokerMethodPointer(methodDefinition, &gmethod->context); newMethod->methodPointer = MetadataCache::GetMethodPointer(methodDefinition, &gmethod->context); ++il2cpp_runtime_stats.inflated_method_count; return newMethod; } const Il2CppGenericContext* GenericMethod::GetContext(const Il2CppGenericMethod* gmethod) { return &gmethod->context; } static std::string FormatGenericArguments(const Il2CppGenericInst* inst) { std::string output; if (inst) { output.append("<"); for (size_t i = 0; i < inst->type_argc; ++i) { if (i != 0) output.append(", "); output.append(Type::GetName(inst->type_argv[i], IL2CPP_TYPE_NAME_FORMAT_FULL_NAME)); } output.append(">"); } return output; } std::string GenericMethod::GetFullName(const Il2CppGenericMethod* gmethod) { const MethodInfo* method = gmethod->methodDefinition; std::string output; output.append(Type::GetName(&gmethod->methodDefinition->klass->byval_arg, IL2CPP_TYPE_NAME_FORMAT_FULL_NAME)); output.append(FormatGenericArguments(gmethod->context.class_inst)); output.append("::"); output.append(Method::GetName(method)); output.append(FormatGenericArguments(gmethod->context.method_inst)); return output; } void GenericMethod::ClearStatics() { s_GenericMethodMap.clear(); } } /* namespace vm */ } /* namespace il2cpp */
;------------------------------------------------------------------------------ ; ; GetInterruptState() function for ARM ; ; Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.<BR> ; Portions copyright (c) 2008 - 2009, Apple Inc. 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. ; ;------------------------------------------------------------------------------ EXPORT GetInterruptState AREA Interrupt_enable, CODE, READONLY ;/** ; Retrieves the current CPU interrupt state. ; ; Returns TRUE is interrupts are currently enabled. Otherwise ; returns FALSE. ; ; @retval TRUE CPU interrupts are enabled. ; @retval FALSE CPU interrupts are disabled. ; ;**/ ; ;BOOLEAN ;EFIAPI ;GetInterruptState ( ; VOID ; ); ; GetInterruptState MRS R0, CPSR TST R0, #0x80 ;Check if IRQ is enabled. MOVEQ R0, #1 MOVNE R0, #0 BX LR END
; A097613: a(n) = binomial(2n-3,n-1) + binomial(2n-2,n-2). ; Submitted by Christian Krause ; 1,2,7,25,91,336,1254,4719,17875,68068,260338,999362,3848222,14858000,57500460,222981435,866262915,3370764540,13135064250,51250632510,200205672810,782920544640,3064665881940,12007086477750,47081501377326,184753963255176,725510446350004 seq $0,51924 ; a(n) = binomial(2*n,n) - binomial(2*n-2,n-1); or (3n-2)*C(n-1), where C = Catalan numbers (A000108). dif $0,2
; A315742: Coordination sequence Gal.5.302.5 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,6,12,18,23,28,33,38,44,50,56,62,68,74,79,84,89,94,100,106,112,118,124,130,135,140,145,150,156,162,168,174,180,186,191,196,201,206,212,218,224,230,236,242,247,252,257,262,268,274 mov $2,$0 lpb $0 add $3,3 sub $0,$3 trn $0,4 add $0,$3 add $3,3 lpe mov $1,$0 trn $1,1 lpb $2 add $1,5 sub $2,1 lpe add $1,1
; PSOS Development Build ; https://github.com/TheBenPerson/PSOS/tree/dev ; ; Copyright (C) 2016 - 2017 Ben Stockett <thebenstockett@gmail.com> ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in all ; copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ; SOFTWARE. [BITS 16] SECTION .text extern kbdHandler global kbdISR kbdISR: ; keyboard ISR handler cli pushad mov ax, ds ; save ds mov bx, cs mov ds, bx ; ds = cs mov ss, bx ; ss = cs push ax call dword kbdHandler ; call C handler mov al, 0x20 out 0x20, al ; send EOI (end of interrupt) pop ax mov ds, ax ; restore ds mov ss, ax ; restore ss popad sti iret
// Distributed under the MIT License. // See LICENSE.txt for details. #include "NumericalAlgorithms/Interpolation/CubicSpanInterpolator.hpp" #include "Parallel/CharmPupable.hpp" #include "Utilities/ForceInline.hpp" #include "Utilities/Gsl.hpp" namespace intrp { namespace { template <typename ValueType> SPECTRE_ALWAYS_INLINE ValueType interpolate_impl( const gsl::span<const double>& source_points, const gsl::span<const ValueType>& values, const double target_point) { const double t0 = source_points[0]; const double t1 = source_points[1]; const double t2 = source_points[2]; const double t3 = source_points[3]; const auto d0 = values[0]; const auto d1 = values[1]; const auto d2 = values[2]; const auto d3 = values[3]; return (-((target_point - t2) * (d3 * (target_point - t0) * (target_point - t1) * (t0 - t1) * (t0 - t2) * (t1 - t2) + (d1 * (target_point - t0) * (t0 - t2) * (t0 - t3) - d0 * (target_point - t1) * (t1 - t2) * (t1 - t3)) * (target_point - t3) * (t2 - t3))) + d2 * (target_point - t0) * (target_point - t1) * (t0 - t1) * (target_point - t3) * (t0 - t3) * (t1 - t3)) / ((t0 - t1) * (t0 - t2) * (t1 - t2) * (t0 - t3) * (t1 - t3) * (t2 - t3)); } } // namespace double CubicSpanInterpolator::interpolate( const gsl::span<const double>& source_points, const gsl::span<const double>& values, double target_point) const { return interpolate_impl(source_points, values, target_point); } std::complex<double> CubicSpanInterpolator::interpolate( const gsl::span<const double>& source_points, const gsl::span<const std::complex<double>>& values, double target_point) const { return interpolate_impl(source_points, values, target_point); } PUP::able::PUP_ID intrp::CubicSpanInterpolator::my_PUP_ID = 0; } // namespace intrp
; A162484: a(1) = 2, a(2) = 8; a(n) = 2 a(n - 1) + a(n - 2) - 4*(n mod 2). ; 2,8,14,36,82,200,478,1156,2786,6728,16238,39204,94642,228488,551614,1331716,3215042,7761800,18738638,45239076,109216786,263672648,636562078,1536796804,3710155682,8957108168,21624372014,52205852196,126036076402,304278005000,734592086398,1773462177796,4281516441986,10336495061768,24954506565518,60245508192804,145445522951122,351136554095048,847718631141214,2046573816377476,4940866263896162 add $0,1 cal $0,51927 ; Number of independent vertex sets in the n-prism graph Y_n = K_2 X C_n (n > 2). mov $1,$0 div $1,2 mul $1,2 add $1,2
; A088705: First differences of A000120. One minus exponent of 2 in n. ; 0,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-3,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-4,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-3,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-5,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-3,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-4,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-3,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-6,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-3,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-4,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-3,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-5,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-3,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-4,1,0,1,-1,1,0,1,-2,1,0,1,-1,1,0,1,-3,1,0,1,-1,1,0,1,-2,1 mov $1,1 mov $2,$0 mov $0,1 mov $3,4 mov $4,$2 lpb $3,2 sub $1,2 div $2,2 mov $3,$4 sub $3,$2 sub $3,$2 mul $3,7 mov $4,$2 lpe add $0,1 add $1,$0 sub $1,1 div $1,2
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing authors: Benoit Leblanc, Dave Rigby, Paul Saxe (Materials Design) Reese Jones (Sandia) ------------------------------------------------------------------------- */ #include <stdlib.h> #include <string.h> #include <unistd.h> #include "fix_ave_correlate.h" #include "update.h" #include "modify.h" #include "compute.h" #include "input.h" #include "variable.h" #include "memory.h" #include "error.h" #include "force.h" using namespace LAMMPS_NS; using namespace FixConst; enum{COMPUTE,FIX,VARIABLE}; enum{ONE,RUNNING}; enum{AUTO,UPPER,LOWER,AUTOUPPER,AUTOLOWER,FULL}; #define INVOKED_SCALAR 1 #define INVOKED_VECTOR 2 #define INVOKED_ARRAY 4 /* ---------------------------------------------------------------------- */ FixAveCorrelate::FixAveCorrelate(LAMMPS * lmp, int narg, char **arg): Fix (lmp, narg, arg), nvalues(0), which(NULL), argindex(NULL), value2index(NULL), ids(NULL), fp(NULL), count(NULL), values(NULL), corr(NULL), save_count(NULL), save_corr(NULL) { if (narg < 7) error->all(FLERR,"Illegal fix ave/correlate command"); MPI_Comm_rank(world,&me); nevery = force->inumeric(FLERR,arg[3]); nrepeat = force->inumeric(FLERR,arg[4]); nfreq = force->inumeric(FLERR,arg[5]); global_freq = nfreq; // expand args if any have wildcard character "*" int expand = 0; char **earg; int nargnew = input->expand_args(narg-6,&arg[6],0,earg); if (earg != &arg[6]) expand = 1; arg = earg; // parse values until one isn't recognized which = new int[nargnew]; argindex = new int[nargnew]; ids = new char*[nargnew]; value2index = new int[nargnew]; nvalues = 0; int iarg = 0; while (iarg < nargnew) { if (strncmp(arg[iarg],"c_",2) == 0 || strncmp(arg[iarg],"f_",2) == 0 || strncmp(arg[iarg],"v_",2) == 0) { if (arg[iarg][0] == 'c') which[nvalues] = COMPUTE; else if (arg[iarg][0] == 'f') which[nvalues] = FIX; else if (arg[iarg][0] == 'v') which[nvalues] = VARIABLE; int n = strlen(arg[iarg]); char *suffix = new char[n]; strcpy(suffix,&arg[iarg][2]); char *ptr = strchr(suffix,'['); if (ptr) { if (suffix[strlen(suffix)-1] != ']') error->all(FLERR,"Illegal fix ave/correlate command"); argindex[nvalues] = atoi(ptr+1); *ptr = '\0'; } else argindex[nvalues] = 0; n = strlen(suffix) + 1; ids[nvalues] = new char[n]; strcpy(ids[nvalues],suffix); delete [] suffix; nvalues++; iarg++; } else break; } // optional args type = AUTO; ave = ONE; startstep = 0; prefactor = 1.0; fp = NULL; overwrite = 0; char *title1 = NULL; char *title2 = NULL; char *title3 = NULL; while (iarg < nargnew) { if (strcmp(arg[iarg],"type") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix ave/correlate command"); if (strcmp(arg[iarg+1],"auto") == 0) type = AUTO; else if (strcmp(arg[iarg+1],"upper") == 0) type = UPPER; else if (strcmp(arg[iarg+1],"lower") == 0) type = LOWER; else if (strcmp(arg[iarg+1],"auto/upper") == 0) type = AUTOUPPER; else if (strcmp(arg[iarg+1],"auto/lower") == 0) type = AUTOLOWER; else if (strcmp(arg[iarg+1],"full") == 0) type = FULL; else error->all(FLERR,"Illegal fix ave/correlate command"); iarg += 2; } else if (strcmp(arg[iarg],"ave") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix ave/correlate command"); if (strcmp(arg[iarg+1],"one") == 0) ave = ONE; else if (strcmp(arg[iarg+1],"running") == 0) ave = RUNNING; else error->all(FLERR,"Illegal fix ave/correlate command"); iarg += 2; } else if (strcmp(arg[iarg],"start") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix ave/correlate command"); startstep = force->inumeric(FLERR,arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"prefactor") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix ave/correlate command"); prefactor = force->numeric(FLERR,arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"file") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix ave/correlate command"); if (me == 0) { fp = fopen(arg[iarg+1],"w"); if (fp == NULL) { char str[128]; sprintf(str,"Cannot open fix ave/correlate file %s",arg[iarg+1]); error->one(FLERR,str); } } iarg += 2; } else if (strcmp(arg[iarg],"overwrite") == 0) { overwrite = 1; iarg += 1; } else if (strcmp(arg[iarg],"title1") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix ave/correlate command"); delete [] title1; int n = strlen(arg[iarg+1]) + 1; title1 = new char[n]; strcpy(title1,arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"title2") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix ave/correlate command"); delete [] title2; int n = strlen(arg[iarg+1]) + 1; title2 = new char[n]; strcpy(title2,arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"title3") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix ave/correlate command"); delete [] title3; int n = strlen(arg[iarg+1]) + 1; title3 = new char[n]; strcpy(title3,arg[iarg+1]); iarg += 2; } else error->all(FLERR,"Illegal fix ave/correlate command"); } // setup and error check // for fix inputs, check that fix frequency is acceptable if (nevery <= 0 || nrepeat <= 0 || nfreq <= 0) error->all(FLERR,"Illegal fix ave/correlate command"); if (nfreq % nevery) error->all(FLERR,"Illegal fix ave/correlate command"); if (ave == ONE && nfreq < (nrepeat-1)*nevery) error->all(FLERR,"Illegal fix ave/correlate command"); if (ave != RUNNING && overwrite) error->all(FLERR,"Illegal fix ave/correlate command"); for (int i = 0; i < nvalues; i++) { if (which[i] == COMPUTE) { int icompute = modify->find_compute(ids[i]); if (icompute < 0) error->all(FLERR,"Compute ID for fix ave/correlate does not exist"); if (argindex[i] == 0 && modify->compute[icompute]->scalar_flag == 0) error->all(FLERR, "Fix ave/correlate compute does not calculate a scalar"); if (argindex[i] && modify->compute[icompute]->vector_flag == 0) error->all(FLERR, "Fix ave/correlate compute does not calculate a vector"); if (argindex[i] && argindex[i] > modify->compute[icompute]->size_vector) error->all(FLERR,"Fix ave/correlate compute vector " "is accessed out-of-range"); } else if (which[i] == FIX) { int ifix = modify->find_fix(ids[i]); if (ifix < 0) error->all(FLERR,"Fix ID for fix ave/correlate does not exist"); if (argindex[i] == 0 && modify->fix[ifix]->scalar_flag == 0) error->all(FLERR,"Fix ave/correlate fix does not calculate a scalar"); if (argindex[i] && modify->fix[ifix]->vector_flag == 0) error->all(FLERR,"Fix ave/correlate fix does not calculate a vector"); if (argindex[i] && argindex[i] > modify->fix[ifix]->size_vector) error->all(FLERR, "Fix ave/correlate fix vector is accessed out-of-range"); if (nevery % modify->fix[ifix]->global_freq) error->all(FLERR,"Fix for fix ave/correlate " "not computed at compatible time"); } else if (which[i] == VARIABLE) { int ivariable = input->variable->find(ids[i]); if (ivariable < 0) error->all(FLERR,"Variable name for fix ave/correlate does not exist"); if (argindex[i] == 0 && input->variable->equalstyle(ivariable) == 0) error->all(FLERR, "Fix ave/correlate variable is not equal-style variable"); if (argindex[i] && input->variable->vectorstyle(ivariable) == 0) error->all(FLERR, "Fix ave/correlate variable is not vector-style variable"); } } // npair = # of correlation pairs to calculate if (type == AUTO) npair = nvalues; if (type == UPPER || type == LOWER) npair = nvalues*(nvalues-1)/2; if (type == AUTOUPPER || type == AUTOLOWER) npair = nvalues*(nvalues+1)/2; if (type == FULL) npair = nvalues*nvalues; // print file comment lines if (fp && me == 0) { clearerr(fp); if (title1) fprintf(fp,"%s\n",title1); else fprintf(fp,"# Time-correlated data for fix %s\n",id); if (title2) fprintf(fp,"%s\n",title2); else fprintf(fp,"# Timestep Number-of-time-windows\n"); if (title3) fprintf(fp,"%s\n",title3); else { fprintf(fp,"# Index TimeDelta Ncount"); if (type == AUTO) for (int i = 0; i < nvalues; i++) fprintf(fp," %s*%s",earg[i],earg[i]); else if (type == UPPER) for (int i = 0; i < nvalues; i++) for (int j = i+1; j < nvalues; j++) fprintf(fp," %s*%s",earg[i],earg[j]); else if (type == LOWER) for (int i = 0; i < nvalues; i++) for (int j = 0; j < i-1; j++) fprintf(fp," %s*%s",earg[i],earg[j]); else if (type == AUTOUPPER) for (int i = 0; i < nvalues; i++) for (int j = i; j < nvalues; j++) fprintf(fp," %s*%s",earg[i],earg[j]); else if (type == AUTOLOWER) for (int i = 0; i < nvalues; i++) for (int j = 0; j < i; j++) fprintf(fp," %s*%s",earg[i],earg[j]); else if (type == FULL) for (int i = 0; i < nvalues; i++) for (int j = 0; j < nvalues; j++) fprintf(fp," %s*%s",earg[i],earg[j]); fprintf(fp,"\n"); } if (ferror(fp)) error->one(FLERR,"Error writing file header"); filepos = ftell(fp); } delete [] title1; delete [] title2; delete [] title3; // if wildcard expansion occurred, free earg memory from expand_args() // wait to do this until after file comment lines are printed if (expand) { for (int i = 0; i < nargnew; i++) delete [] earg[i]; memory->sfree(earg); } // allocate and initialize memory for averaging // set count and corr to zero since they accumulate // also set save versions to zero in case accessed via compute_array() memory->create(values,nrepeat,nvalues,"ave/correlate:values"); memory->create(count,nrepeat,"ave/correlate:count"); memory->create(save_count,nrepeat,"ave/correlate:save_count"); memory->create(corr,nrepeat,npair,"ave/correlate:corr"); memory->create(save_corr,nrepeat,npair,"ave/correlate:save_corr"); int i,j; for (i = 0; i < nrepeat; i++) { save_count[i] = count[i] = 0; for (j = 0; j < npair; j++) save_corr[i][j] = corr[i][j] = 0.0; } // this fix produces a global array array_flag = 1; size_array_rows = nrepeat; size_array_cols = npair+2; extarray = 0; // nvalid = next step on which end_of_step does something // add nvalid to all computes that store invocation times // since don't know a priori which are invoked by this fix // once in end_of_step() can set timestep for ones actually invoked lastindex = -1; firstindex = 0; nsample = 0; nvalid_last = -1; nvalid = nextvalid(); modify->addstep_compute_all(nvalid); } /* ---------------------------------------------------------------------- */ FixAveCorrelate::~FixAveCorrelate() { delete [] which; delete [] argindex; delete [] value2index; for (int i = 0; i < nvalues; i++) delete [] ids[i]; delete [] ids; memory->destroy(values); memory->destroy(count); memory->destroy(save_count); memory->destroy(corr); memory->destroy(save_corr); if (fp && me == 0) fclose(fp); } /* ---------------------------------------------------------------------- */ int FixAveCorrelate::setmask() { int mask = 0; mask |= END_OF_STEP; return mask; } /* ---------------------------------------------------------------------- */ void FixAveCorrelate::init() { // set current indices for all computes,fixes,variables for (int i = 0; i < nvalues; i++) { if (which[i] == COMPUTE) { int icompute = modify->find_compute(ids[i]); if (icompute < 0) error->all(FLERR,"Compute ID for fix ave/correlate does not exist"); value2index[i] = icompute; } else if (which[i] == FIX) { int ifix = modify->find_fix(ids[i]); if (ifix < 0) error->all(FLERR,"Fix ID for fix ave/correlate does not exist"); value2index[i] = ifix; } else if (which[i] == VARIABLE) { int ivariable = input->variable->find(ids[i]); if (ivariable < 0) error->all(FLERR,"Variable name for fix ave/correlate does not exist"); value2index[i] = ivariable; } } // need to reset nvalid if nvalid < ntimestep b/c minimize was performed if (nvalid < update->ntimestep) { lastindex = -1; firstindex = 0; nsample = 0; nvalid = nextvalid(); modify->addstep_compute_all(nvalid); } } /* ---------------------------------------------------------------------- only does something if nvalid = current timestep ------------------------------------------------------------------------- */ void FixAveCorrelate::setup(int vflag) { end_of_step(); } /* ---------------------------------------------------------------------- */ void FixAveCorrelate::end_of_step() { int i,j,m; double scalar; // skip if not step which requires doing something // error check if timestep was reset in an invalid manner bigint ntimestep = update->ntimestep; if (ntimestep < nvalid_last || ntimestep > nvalid) error->all(FLERR,"Invalid timestep reset for fix ave/correlate"); if (ntimestep != nvalid) return; nvalid_last = nvalid; // accumulate results of computes,fixes,variables to origin // compute/fix/variable may invoke computes so wrap with clear/add modify->clearstep_compute(); // lastindex = index in values ring of latest time sample lastindex++; if (lastindex == nrepeat) lastindex = 0; for (i = 0; i < nvalues; i++) { m = value2index[i]; // invoke compute if not previously invoked if (which[i] == COMPUTE) { Compute *compute = modify->compute[m]; if (argindex[i] == 0) { if (!(compute->invoked_flag & INVOKED_SCALAR)) { compute->compute_scalar(); compute->invoked_flag |= INVOKED_SCALAR; } scalar = compute->scalar; } else { if (!(compute->invoked_flag & INVOKED_VECTOR)) { compute->compute_vector(); compute->invoked_flag |= INVOKED_VECTOR; } scalar = compute->vector[argindex[i]-1]; } // access fix fields, guaranteed to be ready } else if (which[i] == FIX) { if (argindex[i] == 0) scalar = modify->fix[m]->compute_scalar(); else scalar = modify->fix[m]->compute_vector(argindex[i]-1); // evaluate equal-style or vector-style variable } else if (which[i] == VARIABLE) { if (argindex[i] == 0) scalar = input->variable->compute_equal(m); else { double *varvec; int nvec = input->variable->compute_vector(m,&varvec); int index = argindex[i]; if (nvec < index) scalar = 0.0; else scalar = varvec[index-1]; } } values[lastindex][i] = scalar; } // fistindex = index in values ring of earliest time sample // nsample = number of time samples in values ring if (nsample < nrepeat) nsample++; else { firstindex++; if (firstindex == nrepeat) firstindex = 0; } nvalid += nevery; modify->addstep_compute(nvalid); // calculate all Cij() enabled by latest values accumulate(); if (ntimestep % nfreq) return; // save results in save_count and save_corr for (i = 0; i < nrepeat; i++) { save_count[i] = count[i]; if (count[i]) for (j = 0; j < npair; j++) save_corr[i][j] = prefactor*corr[i][j]/count[i]; else for (j = 0; j < npair; j++) save_corr[i][j] = 0.0; } // output result to file if (fp && me == 0) { clearerr(fp); if (overwrite) fseek(fp,filepos,SEEK_SET); fprintf(fp,BIGINT_FORMAT " %d\n",ntimestep,nrepeat); for (i = 0; i < nrepeat; i++) { fprintf(fp,"%d %d %d",i+1,i*nevery,count[i]); if (count[i]) for (j = 0; j < npair; j++) fprintf(fp," %g",prefactor*corr[i][j]/count[i]); else for (j = 0; j < npair; j++) fprintf(fp," 0.0"); fprintf(fp,"\n"); } if (ferror(fp)) error->one(FLERR,"Error writing out correlation data"); fflush(fp); if (overwrite) { long fileend = ftell(fp); if (fileend > 0) ftruncate(fileno(fp),fileend); } } // zero accumulation if requested // recalculate Cij(0) if (ave == ONE) { for (i = 0; i < nrepeat; i++) { count[i] = 0; for (j = 0; j < npair; j++) corr[i][j] = 0.0; } nsample = 1; accumulate(); } } /* ---------------------------------------------------------------------- accumulate correlation data using more recently added values ------------------------------------------------------------------------- */ void FixAveCorrelate::accumulate() { int i,j,k,m,n,ipair; for (k = 0; k < nsample; k++) count[k]++; if (type == AUTO) { m = n = lastindex; for (k = 0; k < nsample; k++) { ipair = 0; for (i = 0; i < nvalues; i++) { corr[k][ipair++] += values[m][i]*values[n][i]; } m--; if (m < 0) m = nrepeat-1; } } else if (type == UPPER) { m = n = lastindex; for (k = 0; k < nsample; k++) { ipair = 0; for (i = 0; i < nvalues; i++) for (j = i+1; j < nvalues; j++) corr[k][ipair++] += values[m][i]*values[n][j]; m--; if (m < 0) m = nrepeat-1; } } else if (type == LOWER) { m = n = lastindex; for (k = 0; k < nsample; k++) { ipair = 0; for (i = 0; i < nvalues; i++) for (j = 0; j < i; j++) corr[k][ipair++] += values[m][i]*values[n][j]; m--; if (m < 0) m = nrepeat-1; } } else if (type == AUTOUPPER) { m = n = lastindex; for (k = 0; k < nsample; k++) { ipair = 0; for (i = 0; i < nvalues; i++) for (j = i; j < nvalues; j++) corr[k][ipair++] += values[m][i]*values[n][j]; m--; if (m < 0) m = nrepeat-1; } } else if (type == AUTOLOWER) { m = n = lastindex; for (k = 0; k < nsample; k++) { ipair = 0; for (i = 0; i < nvalues; i++) for (j = 0; j <= i; j++) corr[k][ipair++] += values[m][i]*values[n][j]; m--; if (m < 0) m = nrepeat-1; } } else if (type == FULL) { m = n = lastindex; for (k = 0; k < nsample; k++) { ipair = 0; for (i = 0; i < nvalues; i++) for (j = 0; j < nvalues; j++) corr[k][ipair++] += values[m][i]*values[n][j]; m--; if (m < 0) m = nrepeat-1; } } } /* ---------------------------------------------------------------------- return I,J array value ------------------------------------------------------------------------- */ double FixAveCorrelate::compute_array(int i, int j) { if (j == 0) return 1.0*i*nevery; else if (j == 1) return 1.0*save_count[i]; else if (save_count[i]) return save_corr[i][j-2]; return 0.0; } /* ---------------------------------------------------------------------- nvalid = next step on which end_of_step does something this step if multiple of nevery, else next multiple startstep is lower bound ------------------------------------------------------------------------- */ bigint FixAveCorrelate::nextvalid() { bigint nvalid = update->ntimestep; if (startstep > nvalid) nvalid = startstep; if (nvalid % nevery) nvalid = (nvalid/nevery)*nevery + nevery; return nvalid; }
cal $0,-1 mov $1,$0
//===-- lib/CodeGen/GlobalISel/CallLowering.cpp - Call lowering -----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// /// \file /// This file implements some simple delegations needed for call lowering. /// //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/CallLowering.h" #include "llvm/CodeGen/Analysis.h" #include "llvm/CodeGen/CallingConvLower.h" #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" #include "llvm/CodeGen/GlobalISel/Utils.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetLowering.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Target/TargetMachine.h" #define DEBUG_TYPE "call-lowering" using namespace llvm; void CallLowering::anchor() {} /// Helper function which updates \p Flags when \p AttrFn returns true. static void addFlagsUsingAttrFn(ISD::ArgFlagsTy &Flags, const std::function<bool(Attribute::AttrKind)> &AttrFn) { if (AttrFn(Attribute::SExt)) Flags.setSExt(); if (AttrFn(Attribute::ZExt)) Flags.setZExt(); if (AttrFn(Attribute::InReg)) Flags.setInReg(); if (AttrFn(Attribute::StructRet)) Flags.setSRet(); if (AttrFn(Attribute::Nest)) Flags.setNest(); if (AttrFn(Attribute::ByVal)) Flags.setByVal(); if (AttrFn(Attribute::Preallocated)) Flags.setPreallocated(); if (AttrFn(Attribute::InAlloca)) Flags.setInAlloca(); if (AttrFn(Attribute::Returned)) Flags.setReturned(); if (AttrFn(Attribute::SwiftSelf)) Flags.setSwiftSelf(); if (AttrFn(Attribute::SwiftAsync)) Flags.setSwiftAsync(); if (AttrFn(Attribute::SwiftError)) Flags.setSwiftError(); } ISD::ArgFlagsTy CallLowering::getAttributesForArgIdx(const CallBase &Call, unsigned ArgIdx) const { ISD::ArgFlagsTy Flags; addFlagsUsingAttrFn(Flags, [&Call, &ArgIdx](Attribute::AttrKind Attr) { return Call.paramHasAttr(ArgIdx, Attr); }); return Flags; } void CallLowering::addArgFlagsFromAttributes(ISD::ArgFlagsTy &Flags, const AttributeList &Attrs, unsigned OpIdx) const { addFlagsUsingAttrFn(Flags, [&Attrs, &OpIdx](Attribute::AttrKind Attr) { return Attrs.hasAttributeAtIndex(OpIdx, Attr); }); } bool CallLowering::lowerCall(MachineIRBuilder &MIRBuilder, const CallBase &CB, ArrayRef<Register> ResRegs, ArrayRef<ArrayRef<Register>> ArgRegs, Register SwiftErrorVReg, std::function<unsigned()> GetCalleeReg) const { CallLoweringInfo Info; const DataLayout &DL = MIRBuilder.getDataLayout(); MachineFunction &MF = MIRBuilder.getMF(); MachineRegisterInfo &MRI = MF.getRegInfo(); bool CanBeTailCalled = CB.isTailCall() && isInTailCallPosition(CB, MF.getTarget()) && (MF.getFunction() .getFnAttribute("disable-tail-calls") .getValueAsString() != "true"); CallingConv::ID CallConv = CB.getCallingConv(); Type *RetTy = CB.getType(); bool IsVarArg = CB.getFunctionType()->isVarArg(); SmallVector<BaseArgInfo, 4> SplitArgs; getReturnInfo(CallConv, RetTy, CB.getAttributes(), SplitArgs, DL); Info.CanLowerReturn = canLowerReturn(MF, CallConv, SplitArgs, IsVarArg); if (!Info.CanLowerReturn) { // Callee requires sret demotion. insertSRetOutgoingArgument(MIRBuilder, CB, Info); // The sret demotion isn't compatible with tail-calls, since the sret // argument points into the caller's stack frame. CanBeTailCalled = false; } // First step is to marshall all the function's parameters into the correct // physregs and memory locations. Gather the sequence of argument types that // we'll pass to the assigner function. unsigned i = 0; unsigned NumFixedArgs = CB.getFunctionType()->getNumParams(); for (auto &Arg : CB.args()) { ArgInfo OrigArg{ArgRegs[i], *Arg.get(), i, getAttributesForArgIdx(CB, i), i < NumFixedArgs}; setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, CB); // If we have an explicit sret argument that is an Instruction, (i.e., it // might point to function-local memory), we can't meaningfully tail-call. if (OrigArg.Flags[0].isSRet() && isa<Instruction>(&Arg)) CanBeTailCalled = false; Info.OrigArgs.push_back(OrigArg); ++i; } // Try looking through a bitcast from one function type to another. // Commonly happens with calls to objc_msgSend(). const Value *CalleeV = CB.getCalledOperand()->stripPointerCasts(); if (const Function *F = dyn_cast<Function>(CalleeV)) Info.Callee = MachineOperand::CreateGA(F, 0); else Info.Callee = MachineOperand::CreateReg(GetCalleeReg(), false); Register ReturnHintAlignReg; Align ReturnHintAlign; Info.OrigRet = ArgInfo{ResRegs, RetTy, 0, ISD::ArgFlagsTy{}}; if (!Info.OrigRet.Ty->isVoidTy()) { setArgFlags(Info.OrigRet, AttributeList::ReturnIndex, DL, CB); if (MaybeAlign Alignment = CB.getRetAlign()) { if (*Alignment > Align(1)) { ReturnHintAlignReg = MRI.cloneVirtualRegister(ResRegs[0]); Info.OrigRet.Regs[0] = ReturnHintAlignReg; ReturnHintAlign = *Alignment; } } } Info.CB = &CB; Info.KnownCallees = CB.getMetadata(LLVMContext::MD_callees); Info.CallConv = CallConv; Info.SwiftErrorVReg = SwiftErrorVReg; Info.IsMustTailCall = CB.isMustTailCall(); Info.IsTailCall = CanBeTailCalled; Info.IsVarArg = IsVarArg; if (!lowerCall(MIRBuilder, Info)) return false; if (ReturnHintAlignReg && !Info.IsTailCall) { MIRBuilder.buildAssertAlign(ResRegs[0], ReturnHintAlignReg, ReturnHintAlign); } return true; } template <typename FuncInfoTy> void CallLowering::setArgFlags(CallLowering::ArgInfo &Arg, unsigned OpIdx, const DataLayout &DL, const FuncInfoTy &FuncInfo) const { auto &Flags = Arg.Flags[0]; const AttributeList &Attrs = FuncInfo.getAttributes(); addArgFlagsFromAttributes(Flags, Attrs, OpIdx); PointerType *PtrTy = dyn_cast<PointerType>(Arg.Ty->getScalarType()); if (PtrTy) { Flags.setPointer(); Flags.setPointerAddrSpace(PtrTy->getPointerAddressSpace()); } Align MemAlign = DL.getABITypeAlign(Arg.Ty); if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) { assert(OpIdx >= AttributeList::FirstArgIndex); unsigned ParamIdx = OpIdx - AttributeList::FirstArgIndex; Type *ElementTy = FuncInfo.getParamByValType(ParamIdx); if (!ElementTy) ElementTy = FuncInfo.getParamInAllocaType(ParamIdx); if (!ElementTy) ElementTy = FuncInfo.getParamPreallocatedType(ParamIdx); assert(ElementTy && "Must have byval, inalloca or preallocated type"); Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); // For ByVal, alignment should be passed from FE. BE will guess if // this info is not there but there are cases it cannot get right. if (auto ParamAlign = FuncInfo.getParamStackAlign(ParamIdx)) MemAlign = *ParamAlign; else if ((ParamAlign = FuncInfo.getParamAlign(ParamIdx))) MemAlign = *ParamAlign; else MemAlign = Align(getTLI()->getByValTypeAlignment(ElementTy, DL)); } else if (OpIdx >= AttributeList::FirstArgIndex) { if (auto ParamAlign = FuncInfo.getParamStackAlign(OpIdx - AttributeList::FirstArgIndex)) MemAlign = *ParamAlign; } Flags.setMemAlign(MemAlign); Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty)); // Don't try to use the returned attribute if the argument is marked as // swiftself, since it won't be passed in x0. if (Flags.isSwiftSelf()) Flags.setReturned(false); } template void CallLowering::setArgFlags<Function>(CallLowering::ArgInfo &Arg, unsigned OpIdx, const DataLayout &DL, const Function &FuncInfo) const; template void CallLowering::setArgFlags<CallBase>(CallLowering::ArgInfo &Arg, unsigned OpIdx, const DataLayout &DL, const CallBase &FuncInfo) const; void CallLowering::splitToValueTypes(const ArgInfo &OrigArg, SmallVectorImpl<ArgInfo> &SplitArgs, const DataLayout &DL, CallingConv::ID CallConv, SmallVectorImpl<uint64_t> *Offsets) const { LLVMContext &Ctx = OrigArg.Ty->getContext(); SmallVector<EVT, 4> SplitVTs; ComputeValueVTs(*TLI, DL, OrigArg.Ty, SplitVTs, Offsets, 0); if (SplitVTs.size() == 0) return; if (SplitVTs.size() == 1) { // No splitting to do, but we want to replace the original type (e.g. [1 x // double] -> double). SplitArgs.emplace_back(OrigArg.Regs[0], SplitVTs[0].getTypeForEVT(Ctx), OrigArg.OrigArgIndex, OrigArg.Flags[0], OrigArg.IsFixed, OrigArg.OrigValue); return; } // Create one ArgInfo for each virtual register in the original ArgInfo. assert(OrigArg.Regs.size() == SplitVTs.size() && "Regs / types mismatch"); bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( OrigArg.Ty, CallConv, false, DL); for (unsigned i = 0, e = SplitVTs.size(); i < e; ++i) { Type *SplitTy = SplitVTs[i].getTypeForEVT(Ctx); SplitArgs.emplace_back(OrigArg.Regs[i], SplitTy, OrigArg.OrigArgIndex, OrigArg.Flags[0], OrigArg.IsFixed); if (NeedsRegBlock) SplitArgs.back().Flags[0].setInConsecutiveRegs(); } SplitArgs.back().Flags[0].setInConsecutiveRegsLast(); } /// Pack values \p SrcRegs to cover the vector type result \p DstRegs. static MachineInstrBuilder mergeVectorRegsToResultRegs(MachineIRBuilder &B, ArrayRef<Register> DstRegs, ArrayRef<Register> SrcRegs) { MachineRegisterInfo &MRI = *B.getMRI(); LLT LLTy = MRI.getType(DstRegs[0]); LLT PartLLT = MRI.getType(SrcRegs[0]); // Deal with v3s16 split into v2s16 LLT LCMTy = getCoverTy(LLTy, PartLLT); if (LCMTy == LLTy) { // Common case where no padding is needed. assert(DstRegs.size() == 1); return B.buildConcatVectors(DstRegs[0], SrcRegs); } // We need to create an unmerge to the result registers, which may require // widening the original value. Register UnmergeSrcReg; if (LCMTy != PartLLT) { assert(DstRegs.size() == 1); return B.buildDeleteTrailingVectorElements(DstRegs[0], B.buildMerge(LCMTy, SrcRegs)); } else { // We don't need to widen anything if we're extracting a scalar which was // promoted to a vector e.g. s8 -> v4s8 -> s8 assert(SrcRegs.size() == 1); UnmergeSrcReg = SrcRegs[0]; } int NumDst = LCMTy.getSizeInBits() / LLTy.getSizeInBits(); SmallVector<Register, 8> PadDstRegs(NumDst); std::copy(DstRegs.begin(), DstRegs.end(), PadDstRegs.begin()); // Create the excess dead defs for the unmerge. for (int I = DstRegs.size(); I != NumDst; ++I) PadDstRegs[I] = MRI.createGenericVirtualRegister(LLTy); if (PadDstRegs.size() == 1) return B.buildDeleteTrailingVectorElements(DstRegs[0], UnmergeSrcReg); return B.buildUnmerge(PadDstRegs, UnmergeSrcReg); } /// Create a sequence of instructions to combine pieces split into register /// typed values to the original IR value. \p OrigRegs contains the destination /// value registers of type \p LLTy, and \p Regs contains the legalized pieces /// with type \p PartLLT. This is used for incoming values (physregs to vregs). static void buildCopyFromRegs(MachineIRBuilder &B, ArrayRef<Register> OrigRegs, ArrayRef<Register> Regs, LLT LLTy, LLT PartLLT, const ISD::ArgFlagsTy Flags) { MachineRegisterInfo &MRI = *B.getMRI(); if (PartLLT == LLTy) { // We should have avoided introducing a new virtual register, and just // directly assigned here. assert(OrigRegs[0] == Regs[0]); return; } if (PartLLT.getSizeInBits() == LLTy.getSizeInBits() && OrigRegs.size() == 1 && Regs.size() == 1) { B.buildBitcast(OrigRegs[0], Regs[0]); return; } // A vector PartLLT needs extending to LLTy's element size. // E.g. <2 x s64> = G_SEXT <2 x s32>. if (PartLLT.isVector() == LLTy.isVector() && PartLLT.getScalarSizeInBits() > LLTy.getScalarSizeInBits() && (!PartLLT.isVector() || PartLLT.getNumElements() == LLTy.getNumElements()) && OrigRegs.size() == 1 && Regs.size() == 1) { Register SrcReg = Regs[0]; LLT LocTy = MRI.getType(SrcReg); if (Flags.isSExt()) { SrcReg = B.buildAssertSExt(LocTy, SrcReg, LLTy.getScalarSizeInBits()) .getReg(0); } else if (Flags.isZExt()) { SrcReg = B.buildAssertZExt(LocTy, SrcReg, LLTy.getScalarSizeInBits()) .getReg(0); } // Sometimes pointers are passed zero extended. LLT OrigTy = MRI.getType(OrigRegs[0]); if (OrigTy.isPointer()) { LLT IntPtrTy = LLT::scalar(OrigTy.getSizeInBits()); B.buildIntToPtr(OrigRegs[0], B.buildTrunc(IntPtrTy, SrcReg)); return; } B.buildTrunc(OrigRegs[0], SrcReg); return; } if (!LLTy.isVector() && !PartLLT.isVector()) { assert(OrigRegs.size() == 1); LLT OrigTy = MRI.getType(OrigRegs[0]); unsigned SrcSize = PartLLT.getSizeInBits().getFixedSize() * Regs.size(); if (SrcSize == OrigTy.getSizeInBits()) B.buildMerge(OrigRegs[0], Regs); else { auto Widened = B.buildMerge(LLT::scalar(SrcSize), Regs); B.buildTrunc(OrigRegs[0], Widened); } return; } if (PartLLT.isVector()) { assert(OrigRegs.size() == 1); SmallVector<Register> CastRegs(Regs.begin(), Regs.end()); // If PartLLT is a mismatched vector in both number of elements and element // size, e.g. PartLLT == v2s64 and LLTy is v3s32, then first coerce it to // have the same elt type, i.e. v4s32. if (PartLLT.getSizeInBits() > LLTy.getSizeInBits() && PartLLT.getScalarSizeInBits() == LLTy.getScalarSizeInBits() * 2 && Regs.size() == 1) { LLT NewTy = PartLLT.changeElementType(LLTy.getElementType()) .changeElementCount(PartLLT.getElementCount() * 2); CastRegs[0] = B.buildBitcast(NewTy, Regs[0]).getReg(0); PartLLT = NewTy; } if (LLTy.getScalarType() == PartLLT.getElementType()) { mergeVectorRegsToResultRegs(B, OrigRegs, CastRegs); } else { unsigned I = 0; LLT GCDTy = getGCDType(LLTy, PartLLT); // We are both splitting a vector, and bitcasting its element types. Cast // the source pieces into the appropriate number of pieces with the result // element type. for (Register SrcReg : CastRegs) CastRegs[I++] = B.buildBitcast(GCDTy, SrcReg).getReg(0); mergeVectorRegsToResultRegs(B, OrigRegs, CastRegs); } return; } assert(LLTy.isVector() && !PartLLT.isVector()); LLT DstEltTy = LLTy.getElementType(); // Pointer information was discarded. We'll need to coerce some register types // to avoid violating type constraints. LLT RealDstEltTy = MRI.getType(OrigRegs[0]).getElementType(); assert(DstEltTy.getSizeInBits() == RealDstEltTy.getSizeInBits()); if (DstEltTy == PartLLT) { // Vector was trivially scalarized. if (RealDstEltTy.isPointer()) { for (Register Reg : Regs) MRI.setType(Reg, RealDstEltTy); } B.buildBuildVector(OrigRegs[0], Regs); } else if (DstEltTy.getSizeInBits() > PartLLT.getSizeInBits()) { // Deal with vector with 64-bit elements decomposed to 32-bit // registers. Need to create intermediate 64-bit elements. SmallVector<Register, 8> EltMerges; int PartsPerElt = DstEltTy.getSizeInBits() / PartLLT.getSizeInBits(); assert(DstEltTy.getSizeInBits() % PartLLT.getSizeInBits() == 0); for (int I = 0, NumElts = LLTy.getNumElements(); I != NumElts; ++I) { auto Merge = B.buildMerge(RealDstEltTy, Regs.take_front(PartsPerElt)); // Fix the type in case this is really a vector of pointers. MRI.setType(Merge.getReg(0), RealDstEltTy); EltMerges.push_back(Merge.getReg(0)); Regs = Regs.drop_front(PartsPerElt); } B.buildBuildVector(OrigRegs[0], EltMerges); } else { // Vector was split, and elements promoted to a wider type. // FIXME: Should handle floating point promotions. LLT BVType = LLT::fixed_vector(LLTy.getNumElements(), PartLLT); auto BV = B.buildBuildVector(BVType, Regs); B.buildTrunc(OrigRegs[0], BV); } } /// Create a sequence of instructions to expand the value in \p SrcReg (of type /// \p SrcTy) to the types in \p DstRegs (of type \p PartTy). \p ExtendOp should /// contain the type of scalar value extension if necessary. /// /// This is used for outgoing values (vregs to physregs) static void buildCopyToRegs(MachineIRBuilder &B, ArrayRef<Register> DstRegs, Register SrcReg, LLT SrcTy, LLT PartTy, unsigned ExtendOp = TargetOpcode::G_ANYEXT) { // We could just insert a regular copy, but this is unreachable at the moment. assert(SrcTy != PartTy && "identical part types shouldn't reach here"); const unsigned PartSize = PartTy.getSizeInBits(); if (PartTy.isVector() == SrcTy.isVector() && PartTy.getScalarSizeInBits() > SrcTy.getScalarSizeInBits()) { assert(DstRegs.size() == 1); B.buildInstr(ExtendOp, {DstRegs[0]}, {SrcReg}); return; } if (SrcTy.isVector() && !PartTy.isVector() && PartSize > SrcTy.getElementType().getSizeInBits()) { // Vector was scalarized, and the elements extended. auto UnmergeToEltTy = B.buildUnmerge(SrcTy.getElementType(), SrcReg); for (int i = 0, e = DstRegs.size(); i != e; ++i) B.buildAnyExt(DstRegs[i], UnmergeToEltTy.getReg(i)); return; } LLT GCDTy = getGCDType(SrcTy, PartTy); if (GCDTy == PartTy) { // If this already evenly divisible, we can create a simple unmerge. B.buildUnmerge(DstRegs, SrcReg); return; } MachineRegisterInfo &MRI = *B.getMRI(); LLT DstTy = MRI.getType(DstRegs[0]); LLT LCMTy = getCoverTy(SrcTy, PartTy); const unsigned DstSize = DstTy.getSizeInBits(); const unsigned SrcSize = SrcTy.getSizeInBits(); unsigned CoveringSize = LCMTy.getSizeInBits(); Register UnmergeSrc = SrcReg; if (!LCMTy.isVector() && CoveringSize != SrcSize) { // For scalars, it's common to be able to use a simple extension. if (SrcTy.isScalar() && DstTy.isScalar()) { CoveringSize = alignTo(SrcSize, DstSize); LLT CoverTy = LLT::scalar(CoveringSize); UnmergeSrc = B.buildInstr(ExtendOp, {CoverTy}, {SrcReg}).getReg(0); } else { // Widen to the common type. // FIXME: This should respect the extend type Register Undef = B.buildUndef(SrcTy).getReg(0); SmallVector<Register, 8> MergeParts(1, SrcReg); for (unsigned Size = SrcSize; Size != CoveringSize; Size += SrcSize) MergeParts.push_back(Undef); UnmergeSrc = B.buildMerge(LCMTy, MergeParts).getReg(0); } } if (LCMTy.isVector() && CoveringSize != SrcSize) UnmergeSrc = B.buildPadVectorWithUndefElements(LCMTy, SrcReg).getReg(0); B.buildUnmerge(DstRegs, UnmergeSrc); } bool CallLowering::determineAndHandleAssignments( ValueHandler &Handler, ValueAssigner &Assigner, SmallVectorImpl<ArgInfo> &Args, MachineIRBuilder &MIRBuilder, CallingConv::ID CallConv, bool IsVarArg, ArrayRef<Register> ThisReturnRegs) const { MachineFunction &MF = MIRBuilder.getMF(); const Function &F = MF.getFunction(); SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, F.getContext()); if (!determineAssignments(Assigner, Args, CCInfo)) return false; return handleAssignments(Handler, Args, CCInfo, ArgLocs, MIRBuilder, ThisReturnRegs); } static unsigned extendOpFromFlags(llvm::ISD::ArgFlagsTy Flags) { if (Flags.isSExt()) return TargetOpcode::G_SEXT; if (Flags.isZExt()) return TargetOpcode::G_ZEXT; return TargetOpcode::G_ANYEXT; } bool CallLowering::determineAssignments(ValueAssigner &Assigner, SmallVectorImpl<ArgInfo> &Args, CCState &CCInfo) const { LLVMContext &Ctx = CCInfo.getContext(); const CallingConv::ID CallConv = CCInfo.getCallingConv(); unsigned NumArgs = Args.size(); for (unsigned i = 0; i != NumArgs; ++i) { EVT CurVT = EVT::getEVT(Args[i].Ty); MVT NewVT = TLI->getRegisterTypeForCallingConv(Ctx, CallConv, CurVT); // If we need to split the type over multiple regs, check it's a scenario // we currently support. unsigned NumParts = TLI->getNumRegistersForCallingConv(Ctx, CallConv, CurVT); if (NumParts == 1) { // Try to use the register type if we couldn't assign the VT. if (Assigner.assignArg(i, CurVT, NewVT, NewVT, CCValAssign::Full, Args[i], Args[i].Flags[0], CCInfo)) return false; continue; } // For incoming arguments (physregs to vregs), we could have values in // physregs (or memlocs) which we want to extract and copy to vregs. // During this, we might have to deal with the LLT being split across // multiple regs, so we have to record this information for later. // // If we have outgoing args, then we have the opposite case. We have a // vreg with an LLT which we want to assign to a physical location, and // we might have to record that the value has to be split later. // We're handling an incoming arg which is split over multiple regs. // E.g. passing an s128 on AArch64. ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0]; Args[i].Flags.clear(); for (unsigned Part = 0; Part < NumParts; ++Part) { ISD::ArgFlagsTy Flags = OrigFlags; if (Part == 0) { Flags.setSplit(); } else { Flags.setOrigAlign(Align(1)); if (Part == NumParts - 1) Flags.setSplitEnd(); } Args[i].Flags.push_back(Flags); if (Assigner.assignArg(i, CurVT, NewVT, NewVT, CCValAssign::Full, Args[i], Args[i].Flags[Part], CCInfo)) { // Still couldn't assign this smaller part type for some reason. return false; } } } return true; } bool CallLowering::handleAssignments(ValueHandler &Handler, SmallVectorImpl<ArgInfo> &Args, CCState &CCInfo, SmallVectorImpl<CCValAssign> &ArgLocs, MachineIRBuilder &MIRBuilder, ArrayRef<Register> ThisReturnRegs) const { MachineFunction &MF = MIRBuilder.getMF(); MachineRegisterInfo &MRI = MF.getRegInfo(); const Function &F = MF.getFunction(); const DataLayout &DL = F.getParent()->getDataLayout(); const unsigned NumArgs = Args.size(); // Stores thunks for outgoing register assignments. This is used so we delay // generating register copies until mem loc assignments are done. We do this // so that if the target is using the delayed stack protector feature, we can // find the split point of the block accurately. E.g. if we have: // G_STORE %val, %memloc // $x0 = COPY %foo // $x1 = COPY %bar // CALL func // ... then the split point for the block will correctly be at, and including, // the copy to $x0. If instead the G_STORE instruction immediately precedes // the CALL, then we'd prematurely choose the CALL as the split point, thus // generating a split block with a CALL that uses undefined physregs. SmallVector<std::function<void()>> DelayedOutgoingRegAssignments; for (unsigned i = 0, j = 0; i != NumArgs; ++i, ++j) { assert(j < ArgLocs.size() && "Skipped too many arg locs"); CCValAssign &VA = ArgLocs[j]; assert(VA.getValNo() == i && "Location doesn't correspond to current arg"); if (VA.needsCustom()) { std::function<void()> Thunk; unsigned NumArgRegs = Handler.assignCustomValue( Args[i], makeArrayRef(ArgLocs).slice(j), &Thunk); if (Thunk) DelayedOutgoingRegAssignments.emplace_back(Thunk); if (!NumArgRegs) return false; j += NumArgRegs; continue; } const MVT ValVT = VA.getValVT(); const MVT LocVT = VA.getLocVT(); const LLT LocTy(LocVT); const LLT ValTy(ValVT); const LLT NewLLT = Handler.isIncomingArgumentHandler() ? LocTy : ValTy; const EVT OrigVT = EVT::getEVT(Args[i].Ty); const LLT OrigTy = getLLTForType(*Args[i].Ty, DL); // Expected to be multiple regs for a single incoming arg. // There should be Regs.size() ArgLocs per argument. // This should be the same as getNumRegistersForCallingConv const unsigned NumParts = Args[i].Flags.size(); // Now split the registers into the assigned types. Args[i].OrigRegs.assign(Args[i].Regs.begin(), Args[i].Regs.end()); if (NumParts != 1 || NewLLT != OrigTy) { // If we can't directly assign the register, we need one or more // intermediate values. Args[i].Regs.resize(NumParts); // For each split register, create and assign a vreg that will store // the incoming component of the larger value. These will later be // merged to form the final vreg. for (unsigned Part = 0; Part < NumParts; ++Part) Args[i].Regs[Part] = MRI.createGenericVirtualRegister(NewLLT); } assert((j + (NumParts - 1)) < ArgLocs.size() && "Too many regs for number of args"); // Coerce into outgoing value types before register assignment. if (!Handler.isIncomingArgumentHandler() && OrigTy != ValTy) { assert(Args[i].OrigRegs.size() == 1); buildCopyToRegs(MIRBuilder, Args[i].Regs, Args[i].OrigRegs[0], OrigTy, ValTy, extendOpFromFlags(Args[i].Flags[0])); } bool BigEndianPartOrdering = TLI->hasBigEndianPartOrdering(OrigVT, DL); for (unsigned Part = 0; Part < NumParts; ++Part) { Register ArgReg = Args[i].Regs[Part]; // There should be Regs.size() ArgLocs per argument. unsigned Idx = BigEndianPartOrdering ? NumParts - 1 - Part : Part; CCValAssign &VA = ArgLocs[j + Idx]; const ISD::ArgFlagsTy Flags = Args[i].Flags[Part]; if (VA.isMemLoc() && !Flags.isByVal()) { // Individual pieces may have been spilled to the stack and others // passed in registers. // TODO: The memory size may be larger than the value we need to // store. We may need to adjust the offset for big endian targets. LLT MemTy = Handler.getStackValueStoreType(DL, VA, Flags); MachinePointerInfo MPO; Register StackAddr = Handler.getStackAddress( MemTy.getSizeInBytes(), VA.getLocMemOffset(), MPO, Flags); Handler.assignValueToAddress(Args[i], Part, StackAddr, MemTy, MPO, VA); continue; } if (VA.isMemLoc() && Flags.isByVal()) { assert(Args[i].Regs.size() == 1 && "didn't expect split byval pointer"); if (Handler.isIncomingArgumentHandler()) { // We just need to copy the frame index value to the pointer. MachinePointerInfo MPO; Register StackAddr = Handler.getStackAddress( Flags.getByValSize(), VA.getLocMemOffset(), MPO, Flags); MIRBuilder.buildCopy(Args[i].Regs[0], StackAddr); } else { // For outgoing byval arguments, insert the implicit copy byval // implies, such that writes in the callee do not modify the caller's // value. uint64_t MemSize = Flags.getByValSize(); int64_t Offset = VA.getLocMemOffset(); MachinePointerInfo DstMPO; Register StackAddr = Handler.getStackAddress(MemSize, Offset, DstMPO, Flags); MachinePointerInfo SrcMPO(Args[i].OrigValue); if (!Args[i].OrigValue) { // We still need to accurately track the stack address space if we // don't know the underlying value. const LLT PtrTy = MRI.getType(StackAddr); SrcMPO = MachinePointerInfo(PtrTy.getAddressSpace()); } Align DstAlign = std::max(Flags.getNonZeroByValAlign(), inferAlignFromPtrInfo(MF, DstMPO)); Align SrcAlign = std::max(Flags.getNonZeroByValAlign(), inferAlignFromPtrInfo(MF, SrcMPO)); Handler.copyArgumentMemory(Args[i], StackAddr, Args[i].Regs[0], DstMPO, DstAlign, SrcMPO, SrcAlign, MemSize, VA); } continue; } assert(!VA.needsCustom() && "custom loc should have been handled already"); if (i == 0 && !ThisReturnRegs.empty() && Handler.isIncomingArgumentHandler() && isTypeIsValidForThisReturn(ValVT)) { Handler.assignValueToReg(ArgReg, ThisReturnRegs[Part], VA); continue; } if (Handler.isIncomingArgumentHandler()) Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA); else { DelayedOutgoingRegAssignments.emplace_back([=, &Handler]() { Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA); }); } } // Now that all pieces have been assigned, re-pack the register typed values // into the original value typed registers. if (Handler.isIncomingArgumentHandler() && OrigVT != LocVT) { // Merge the split registers into the expected larger result vregs of // the original call. buildCopyFromRegs(MIRBuilder, Args[i].OrigRegs, Args[i].Regs, OrigTy, LocTy, Args[i].Flags[0]); } j += NumParts - 1; } for (auto &Fn : DelayedOutgoingRegAssignments) Fn(); return true; } void CallLowering::insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef<Register> VRegs, Register DemoteReg, int FI) const { MachineFunction &MF = MIRBuilder.getMF(); MachineRegisterInfo &MRI = MF.getRegInfo(); const DataLayout &DL = MF.getDataLayout(); SmallVector<EVT, 4> SplitVTs; SmallVector<uint64_t, 4> Offsets; ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0); assert(VRegs.size() == SplitVTs.size()); unsigned NumValues = SplitVTs.size(); Align BaseAlign = DL.getPrefTypeAlign(RetTy); Type *RetPtrTy = RetTy->getPointerTo(DL.getAllocaAddrSpace()); LLT OffsetLLTy = getLLTForType(*DL.getIntPtrType(RetPtrTy), DL); MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI); for (unsigned I = 0; I < NumValues; ++I) { Register Addr; MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]); auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad, MRI.getType(VRegs[I]), commonAlignment(BaseAlign, Offsets[I])); MIRBuilder.buildLoad(VRegs[I], Addr, *MMO); } } void CallLowering::insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef<Register> VRegs, Register DemoteReg) const { MachineFunction &MF = MIRBuilder.getMF(); MachineRegisterInfo &MRI = MF.getRegInfo(); const DataLayout &DL = MF.getDataLayout(); SmallVector<EVT, 4> SplitVTs; SmallVector<uint64_t, 4> Offsets; ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0); assert(VRegs.size() == SplitVTs.size()); unsigned NumValues = SplitVTs.size(); Align BaseAlign = DL.getPrefTypeAlign(RetTy); unsigned AS = DL.getAllocaAddrSpace(); LLT OffsetLLTy = getLLTForType(*DL.getIntPtrType(RetTy->getPointerTo(AS)), DL); MachinePointerInfo PtrInfo(AS); for (unsigned I = 0; I < NumValues; ++I) { Register Addr; MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]); auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore, MRI.getType(VRegs[I]), commonAlignment(BaseAlign, Offsets[I])); MIRBuilder.buildStore(VRegs[I], Addr, *MMO); } } void CallLowering::insertSRetIncomingArgument( const Function &F, SmallVectorImpl<ArgInfo> &SplitArgs, Register &DemoteReg, MachineRegisterInfo &MRI, const DataLayout &DL) const { unsigned AS = DL.getAllocaAddrSpace(); DemoteReg = MRI.createGenericVirtualRegister( LLT::pointer(AS, DL.getPointerSizeInBits(AS))); Type *PtrTy = PointerType::get(F.getReturnType(), AS); SmallVector<EVT, 1> ValueVTs; ComputeValueVTs(*TLI, DL, PtrTy, ValueVTs); // NOTE: Assume that a pointer won't get split into more than one VT. assert(ValueVTs.size() == 1); ArgInfo DemoteArg(DemoteReg, ValueVTs[0].getTypeForEVT(PtrTy->getContext()), ArgInfo::NoArgIndex); setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, F); DemoteArg.Flags[0].setSRet(); SplitArgs.insert(SplitArgs.begin(), DemoteArg); } void CallLowering::insertSRetOutgoingArgument(MachineIRBuilder &MIRBuilder, const CallBase &CB, CallLoweringInfo &Info) const { const DataLayout &DL = MIRBuilder.getDataLayout(); Type *RetTy = CB.getType(); unsigned AS = DL.getAllocaAddrSpace(); LLT FramePtrTy = LLT::pointer(AS, DL.getPointerSizeInBits(AS)); int FI = MIRBuilder.getMF().getFrameInfo().CreateStackObject( DL.getTypeAllocSize(RetTy), DL.getPrefTypeAlign(RetTy), false); Register DemoteReg = MIRBuilder.buildFrameIndex(FramePtrTy, FI).getReg(0); ArgInfo DemoteArg(DemoteReg, PointerType::get(RetTy, AS), ArgInfo::NoArgIndex); setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, CB); DemoteArg.Flags[0].setSRet(); Info.OrigArgs.insert(Info.OrigArgs.begin(), DemoteArg); Info.DemoteStackIndex = FI; Info.DemoteRegister = DemoteReg; } bool CallLowering::checkReturn(CCState &CCInfo, SmallVectorImpl<BaseArgInfo> &Outs, CCAssignFn *Fn) const { for (unsigned I = 0, E = Outs.size(); I < E; ++I) { MVT VT = MVT::getVT(Outs[I].Ty); if (Fn(I, VT, VT, CCValAssign::Full, Outs[I].Flags[0], CCInfo)) return false; } return true; } void CallLowering::getReturnInfo(CallingConv::ID CallConv, Type *RetTy, AttributeList Attrs, SmallVectorImpl<BaseArgInfo> &Outs, const DataLayout &DL) const { LLVMContext &Context = RetTy->getContext(); ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); SmallVector<EVT, 4> SplitVTs; ComputeValueVTs(*TLI, DL, RetTy, SplitVTs); addArgFlagsFromAttributes(Flags, Attrs, AttributeList::ReturnIndex); for (EVT VT : SplitVTs) { unsigned NumParts = TLI->getNumRegistersForCallingConv(Context, CallConv, VT); MVT RegVT = TLI->getRegisterTypeForCallingConv(Context, CallConv, VT); Type *PartTy = EVT(RegVT).getTypeForEVT(Context); for (unsigned I = 0; I < NumParts; ++I) { Outs.emplace_back(PartTy, Flags); } } } bool CallLowering::checkReturnTypeForCallConv(MachineFunction &MF) const { const auto &F = MF.getFunction(); Type *ReturnType = F.getReturnType(); CallingConv::ID CallConv = F.getCallingConv(); SmallVector<BaseArgInfo, 4> SplitArgs; getReturnInfo(CallConv, ReturnType, F.getAttributes(), SplitArgs, MF.getDataLayout()); return canLowerReturn(MF, CallConv, SplitArgs, F.isVarArg()); } bool CallLowering::parametersInCSRMatch( const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl<CCValAssign> &OutLocs, const SmallVectorImpl<ArgInfo> &OutArgs) const { for (unsigned i = 0; i < OutLocs.size(); ++i) { auto &ArgLoc = OutLocs[i]; // If it's not a register, it's fine. if (!ArgLoc.isRegLoc()) continue; MCRegister PhysReg = ArgLoc.getLocReg(); // Only look at callee-saved registers. if (MachineOperand::clobbersPhysReg(CallerPreservedMask, PhysReg)) continue; LLVM_DEBUG( dbgs() << "... Call has an argument passed in a callee-saved register.\n"); // Check if it was copied from. const ArgInfo &OutInfo = OutArgs[i]; if (OutInfo.Regs.size() > 1) { LLVM_DEBUG( dbgs() << "... Cannot handle arguments in multiple registers.\n"); return false; } // Check if we copy the register, walking through copies from virtual // registers. Note that getDefIgnoringCopies does not ignore copies from // physical registers. MachineInstr *RegDef = getDefIgnoringCopies(OutInfo.Regs[0], MRI); if (!RegDef || RegDef->getOpcode() != TargetOpcode::COPY) { LLVM_DEBUG( dbgs() << "... Parameter was not copied into a VReg, cannot tail call.\n"); return false; } // Got a copy. Verify that it's the same as the register we want. Register CopyRHS = RegDef->getOperand(1).getReg(); if (CopyRHS != PhysReg) { LLVM_DEBUG(dbgs() << "... Callee-saved register was not copied into " "VReg, cannot tail call.\n"); return false; } } return true; } bool CallLowering::resultsCompatible(CallLoweringInfo &Info, MachineFunction &MF, SmallVectorImpl<ArgInfo> &InArgs, ValueAssigner &CalleeAssigner, ValueAssigner &CallerAssigner) const { const Function &F = MF.getFunction(); CallingConv::ID CalleeCC = Info.CallConv; CallingConv::ID CallerCC = F.getCallingConv(); if (CallerCC == CalleeCC) return true; SmallVector<CCValAssign, 16> ArgLocs1; CCState CCInfo1(CalleeCC, Info.IsVarArg, MF, ArgLocs1, F.getContext()); if (!determineAssignments(CalleeAssigner, InArgs, CCInfo1)) return false; SmallVector<CCValAssign, 16> ArgLocs2; CCState CCInfo2(CallerCC, F.isVarArg(), MF, ArgLocs2, F.getContext()); if (!determineAssignments(CallerAssigner, InArgs, CCInfo2)) return false; // We need the argument locations to match up exactly. If there's more in // one than the other, then we are done. if (ArgLocs1.size() != ArgLocs2.size()) return false; // Make sure that each location is passed in exactly the same way. for (unsigned i = 0, e = ArgLocs1.size(); i < e; ++i) { const CCValAssign &Loc1 = ArgLocs1[i]; const CCValAssign &Loc2 = ArgLocs2[i]; // We need both of them to be the same. So if one is a register and one // isn't, we're done. if (Loc1.isRegLoc() != Loc2.isRegLoc()) return false; if (Loc1.isRegLoc()) { // If they don't have the same register location, we're done. if (Loc1.getLocReg() != Loc2.getLocReg()) return false; // They matched, so we can move to the next ArgLoc. continue; } // Loc1 wasn't a RegLoc, so they both must be MemLocs. Check if they match. if (Loc1.getLocMemOffset() != Loc2.getLocMemOffset()) return false; } return true; } LLT CallLowering::ValueHandler::getStackValueStoreType( const DataLayout &DL, const CCValAssign &VA, ISD::ArgFlagsTy Flags) const { const MVT ValVT = VA.getValVT(); if (ValVT != MVT::iPTR) { LLT ValTy(ValVT); // We lost the pointeriness going through CCValAssign, so try to restore it // based on the flags. if (Flags.isPointer()) { LLT PtrTy = LLT::pointer(Flags.getPointerAddrSpace(), ValTy.getScalarSizeInBits()); if (ValVT.isVector()) return LLT::vector(ValTy.getElementCount(), PtrTy); return PtrTy; } return ValTy; } unsigned AddrSpace = Flags.getPointerAddrSpace(); return LLT::pointer(AddrSpace, DL.getPointerSize(AddrSpace)); } void CallLowering::ValueHandler::copyArgumentMemory( const ArgInfo &Arg, Register DstPtr, Register SrcPtr, const MachinePointerInfo &DstPtrInfo, Align DstAlign, const MachinePointerInfo &SrcPtrInfo, Align SrcAlign, uint64_t MemSize, CCValAssign &VA) const { MachineFunction &MF = MIRBuilder.getMF(); MachineMemOperand *SrcMMO = MF.getMachineMemOperand( SrcPtrInfo, MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable, MemSize, SrcAlign); MachineMemOperand *DstMMO = MF.getMachineMemOperand( DstPtrInfo, MachineMemOperand::MOStore | MachineMemOperand::MODereferenceable, MemSize, DstAlign); const LLT PtrTy = MRI.getType(DstPtr); const LLT SizeTy = LLT::scalar(PtrTy.getSizeInBits()); auto SizeConst = MIRBuilder.buildConstant(SizeTy, MemSize); MIRBuilder.buildMemCpy(DstPtr, SrcPtr, SizeConst, *DstMMO, *SrcMMO); } Register CallLowering::ValueHandler::extendRegister(Register ValReg, CCValAssign &VA, unsigned MaxSizeBits) { LLT LocTy{VA.getLocVT()}; LLT ValTy{VA.getValVT()}; if (LocTy.getSizeInBits() == ValTy.getSizeInBits()) return ValReg; if (LocTy.isScalar() && MaxSizeBits && MaxSizeBits < LocTy.getSizeInBits()) { if (MaxSizeBits <= ValTy.getSizeInBits()) return ValReg; LocTy = LLT::scalar(MaxSizeBits); } const LLT ValRegTy = MRI.getType(ValReg); if (ValRegTy.isPointer()) { // The x32 ABI wants to zero extend 32-bit pointers to 64-bit registers, so // we have to cast to do the extension. LLT IntPtrTy = LLT::scalar(ValRegTy.getSizeInBits()); ValReg = MIRBuilder.buildPtrToInt(IntPtrTy, ValReg).getReg(0); } switch (VA.getLocInfo()) { default: break; case CCValAssign::Full: case CCValAssign::BCvt: // FIXME: bitconverting between vector types may or may not be a // nop in big-endian situations. return ValReg; case CCValAssign::AExt: { auto MIB = MIRBuilder.buildAnyExt(LocTy, ValReg); return MIB.getReg(0); } case CCValAssign::SExt: { Register NewReg = MRI.createGenericVirtualRegister(LocTy); MIRBuilder.buildSExt(NewReg, ValReg); return NewReg; } case CCValAssign::ZExt: { Register NewReg = MRI.createGenericVirtualRegister(LocTy); MIRBuilder.buildZExt(NewReg, ValReg); return NewReg; } } llvm_unreachable("unable to extend register"); } void CallLowering::ValueAssigner::anchor() {} Register CallLowering::IncomingValueHandler::buildExtensionHint(CCValAssign &VA, Register SrcReg, LLT NarrowTy) { switch (VA.getLocInfo()) { case CCValAssign::LocInfo::ZExt: { return MIRBuilder .buildAssertZExt(MRI.cloneVirtualRegister(SrcReg), SrcReg, NarrowTy.getScalarSizeInBits()) .getReg(0); } case CCValAssign::LocInfo::SExt: { return MIRBuilder .buildAssertSExt(MRI.cloneVirtualRegister(SrcReg), SrcReg, NarrowTy.getScalarSizeInBits()) .getReg(0); break; } default: return SrcReg; } } /// Check if we can use a basic COPY instruction between the two types. /// /// We're currently building on top of the infrastructure using MVT, which loses /// pointer information in the CCValAssign. We accept copies from physical /// registers that have been reported as integers if it's to an equivalent sized /// pointer LLT. static bool isCopyCompatibleType(LLT SrcTy, LLT DstTy) { if (SrcTy == DstTy) return true; if (SrcTy.getSizeInBits() != DstTy.getSizeInBits()) return false; SrcTy = SrcTy.getScalarType(); DstTy = DstTy.getScalarType(); return (SrcTy.isPointer() && DstTy.isScalar()) || (DstTy.isScalar() && SrcTy.isPointer()); } void CallLowering::IncomingValueHandler::assignValueToReg(Register ValVReg, Register PhysReg, CCValAssign VA) { const MVT LocVT = VA.getLocVT(); const LLT LocTy(LocVT); const LLT RegTy = MRI.getType(ValVReg); if (isCopyCompatibleType(RegTy, LocTy)) { MIRBuilder.buildCopy(ValVReg, PhysReg); return; } auto Copy = MIRBuilder.buildCopy(LocTy, PhysReg); auto Hint = buildExtensionHint(VA, Copy.getReg(0), RegTy); MIRBuilder.buildTrunc(ValVReg, Hint); }
;******************************************************************* ; sort3a.asm ; Sorting Networks ; ; Author: Kareem Omar ; kareem.omar@uah.edu ; https//github.com/komrad36 ; ; Last updated Feb 15, 2017 ;******************************************************************* ; ; SUMMARY: I present novel and state-of-the-art sorting of 4 int32_t ; and sorting of 6 int8_t, as examples, using SSE4, and some thoughts ; and notes on fast sorting of small fixed-size arrays. ; ; These are the fastest known approaches on modern CPUs. ; They are completely branchless and extremely fast. ; For example, 4 int32_t can be sorted in ~18 cycles on Skylake. ; ; These examples can be modified to sort signed or unsigned data as long ; as the total size of the data is <= 128 bits (16 bytes). Note that ; trying to use AVX2 to push that to 256 bits will NOT HELP ; because of the 3 cycle interlane latency that makes shuffling ; across the 128-bit lane boundary too expensive to be useful. ; ; In that case, or in the case that you can't support SSE4, ; efficient scalar code can also be generated that isn't too much ; slower, but it's not immediately evident what the optimal approach ; is in assembly, nor how to coerce C/C++ compilers to produce that ; assembly from C/C++ code. (I discuss the approach at the end of this ; documentation.) ; ; Not all compilers correctly generate optimal assembly for either the ; SSE or scalar code, so I provide assembly versions too. In fact, this ; is not a strong enough statement; many compilers FAIL MISERABLY ; at both the SSE and scalar cases for n >= 3. CL in particular ; (Microsoft Visual C++) just dies horribly in a fire, so the assembly ; snippets may not be a bad idea. Profile and/or check your disassembly. ; ; Note that these assembly snippets use the Windows x64 calling convention, ; but then proceed to clobber a bunch of registers they shouldn't. Normally ; they'd be inlined. Feel free to callee-save registers that your ; application cannot safely clobber. ; ; These code snippets work on the principle of sorting networks. ; Conventional sorting algorithms like quicksort and mergesort ; are not great at small array sizes. One notices in profiling that ; simpler sorts like insertion and selection tend to win. However, ; even these are not NEARLY as fast as they could be for ; fixed-size, small arrays. ; ; Available sorts and their function names: ; ; >>> SSE Assembly (fast as hell. FASTEST option on modern CPUs. ; these are written in MASM for Win64; ; but it's Intel syntax and you can make the small ; modifications required for other assemblers.) ; Sorting 4 int32_t | simdsort4a() ; Sorting 4 int32_t | simdsort4a_noconstants() ; Sorting 4 int32_t | simdsort4a_nofloat() ; ; >>> SSE C++ (make sure generated assembly matches): ; Sorting 4 int32_t | simdsort4() ; Sorting 6 int8_t | simdsort6() ; ; >>> Scalar Assembly (these are written in MASM for Win64; ; but it's Intel syntax and you can make the small ; modifications required for other assemblers.) ; Sorting 2 int32_t | sort2a() ; Sorting 3 int32_t | sort3a() ; Sorting 4 int32_t | sort4a() ; Sorting 5 int32_t | sort5a() ; Sorting 6 int32_t | sort6a() ; ; >>> Scalar C++ (make sure generated assembly matches) ; Sorting 2 int32_t | sort2() ; Sorting 6 int32_t | sort6() ; ; ; Okay, if you've made it this far, let's discuss ; fast conditional swap operations. Conditional swaps ; if the lower element is greater are the heart of sorting ; networks. Given two values, ; 'a', and 'b', leave them as they are if 'a' is less ; than 'b', i.e. if they are in sorted order. However, ; swap them if 'a' is greater than or equal to 'b'. ; Thus after such a conditional swap operation 'a' and 'b' are in sorted ; order no matter what order they came in as. ; ; A series of such operations can deterministically sort ; a fixed-size array. Typically one can optimize for depth ; (minimum number of operations given infinite parallel ; processing) or for size (minimum number of operations given ; no parallel processing). For n == 4 these two optimal solutions ; are actually given by the same network, with depth 3 and ; size 5. ; ; Scalar first: how do you efficiently conditional swap? Again, note that ; lots of compilers don't produce optimal assembly no matter ; what C++ you give them. But what is the optimal assembly? ; Well, on modern processors, the answer is conditional moves: ; ; ; inputs: eax, r9d ; ; scratch register: edx ; cmp eax, r9d ; mov edx, eax ; cmovg eax, r9d ; cmovg r9d, edx ; ; eax and r9d have been swapped if necessary such that eax is now <= r9d ; ; See the function 'sort6' in 'sorts.cpp' for an attempt at some C++ code ; that has a decent chance of compiling into conditional swaps that look like that. ; Again, they OFTEN DON'T, especially the CL compiler and g++. Use the assembly ; snippets instead, or at least profile and inspect your disassembly to be sure. ; ; The SSE sorts are rather more sophisticated, but the basic principle ; is to branchlessly generate shuffle index masks at runtime and then ; use them to permute the order of the data in parallel, performing ; one complete level of the sorting network at a time. ; ; I provide 3 versions of the assembly for sorting 4 int32_t. The fastest ; should be the plain 'simdsort4a'. It performs float reinterpretation ; and relies on some constant loads, but both of these are USUALLY ; better than the alternatives. However: ; ; Older CPUs may incur too much latency from the reinterpretation to be ; worth it. For such CPUs, try 'simdsort4a_nofloat.asm'. ; ; Applications that cannot afford to have these constants occupying L1 ; may wish to try 'simdsort4a_noconstants.asm', which does not eat ; up any cache space with constants - everything is done with immediates ; and some fairly nasty bit twiddling. ; .CODE sort3a PROC mov r8d, [rcx] mov eax, r8d mov edx, [rcx+4] cmp r8d, edx mov r9d, [rcx+8] cmovg r8d, edx cmovg edx, eax cmp edx, r9d mov eax, r9d cmovg r9d, edx mov [rcx+8], r9d cmovg edx, eax cmp r8d, edx mov eax, r8d cmovg r8d, edx mov [rcx], r8d cmovg edx, eax mov [rcx+4], edx ret sort3a ENDP END
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %r14 push %r9 push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x7eb9, %rsi nop nop nop nop add $43262, %rdx movw $0x6162, (%rsi) nop nop sub $12629, %r9 lea addresses_normal_ht+0xa07f, %r9 nop nop nop cmp $36730, %r14 mov (%r9), %r12d nop nop dec %r14 lea addresses_UC_ht+0xb85f, %r14 nop nop nop nop nop and %r11, %r11 mov (%r14), %r13 nop nop nop nop nop and $15340, %r11 lea addresses_D_ht+0xbcef, %rsi lea addresses_A_ht+0xde1f, %rdi nop nop nop nop nop xor %r9, %r9 mov $100, %rcx rep movsl nop nop nop dec %r13 lea addresses_D_ht+0x1285f, %r9 nop sub %r14, %r14 vmovups (%r9), %ymm1 vextracti128 $1, %ymm1, %xmm1 vpextrq $1, %xmm1, %rcx nop nop nop nop sub $44534, %rcx lea addresses_A_ht+0x1b77f, %rsi lea addresses_WT_ht+0x2c5f, %rdi clflush (%rdi) nop dec %r13 mov $57, %rcx rep movsb nop nop inc %rsi lea addresses_normal_ht+0x68df, %rsi lea addresses_A_ht+0x1682f, %rdi nop nop dec %r14 mov $27, %rcx rep movsw add $54940, %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %r9 pop %r14 pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r14 push %r15 push %rbx push %rdi push %rsi // Store lea addresses_D+0x563a, %rsi nop nop cmp $2280, %rdi mov $0x5152535455565758, %r11 movq %r11, %xmm1 vmovups %ymm1, (%rsi) nop nop cmp %r14, %r14 // Store lea addresses_UC+0x5f, %r11 nop nop nop nop nop cmp $29156, %r12 movw $0x5152, (%r11) nop nop nop nop nop sub %rbx, %rbx // Store mov $0x1349330000000e3f, %rbx nop nop nop nop and %r15, %r15 movw $0x5152, (%rbx) nop nop nop nop sub %r12, %r12 // Faulty Load lea addresses_A+0xe85f, %rbx nop cmp %rsi, %rsi mov (%rbx), %r12 lea oracles, %r11 and $0xff, %r12 shlq $12, %r12 mov (%r11,%r12,1), %r12 pop %rsi pop %rdi pop %rbx pop %r15 pop %r14 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_UC', 'same': False, 'size': 2, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_NC', 'same': False, 'size': 2, 'congruent': 4, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_A', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 6, 'same': True}, 'OP': 'REPM'} {'src': {'type': 'addresses_D_ht', 'same': False, 'size': 32, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 5, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'} {'00': 159} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; size_t w_vector_capacity(w_vector_t *v) SECTION code_clib SECTION code_adt_w_vector PUBLIC w_vector_capacity EXTERN asm_w_vector_capacity defc w_vector_capacity = asm_w_vector_capacity ; SDCC bridge for Classic IF __CLASSIC PUBLIC _w_vector_capacity defc _w_vector_capacity = w_vector_capacity ENDIF
;-------------------------------------------------------- ; Category 8 Function 65H Verify Track - not supported for DOS 2.X and DOS 3.X. ;-------------------------------------------------------- ; ; ; IODVERIFYTRACK PROC NEAR RET IODVERIFYTRACK ENDP
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/indexed_db_dispatcher_host.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/process/process.h" #include "base/strings/utf_string_conversions.h" #include "content/browser/indexed_db/indexed_db_callbacks.h" #include "content/browser/indexed_db/indexed_db_connection.h" #include "content/browser/indexed_db/indexed_db_context_impl.h" #include "content/browser/indexed_db/indexed_db_cursor.h" #include "content/browser/indexed_db/indexed_db_database_callbacks.h" #include "content/browser/indexed_db/indexed_db_metadata.h" #include "content/browser/renderer_host/render_message_filter.h" #include "content/common/indexed_db/indexed_db_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/user_metrics.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "third_party/WebKit/public/platform/WebIDBDatabaseException.h" #include "url/gurl.h" #include "webkit/browser/database/database_util.h" #include "webkit/common/database/database_identifier.h" using webkit_database::DatabaseUtil; using blink::WebIDBKey; namespace content { IndexedDBDispatcherHost::IndexedDBDispatcherHost( IndexedDBContextImpl* indexed_db_context) : indexed_db_context_(indexed_db_context), database_dispatcher_host_(new DatabaseDispatcherHost(this)), cursor_dispatcher_host_(new CursorDispatcherHost(this)) { DCHECK(indexed_db_context_); } IndexedDBDispatcherHost::~IndexedDBDispatcherHost() {} void IndexedDBDispatcherHost::OnChannelClosing() { bool success = indexed_db_context_->TaskRunner()->PostTask( FROM_HERE, base::Bind(&IndexedDBDispatcherHost::ResetDispatcherHosts, this)); if (!success) ResetDispatcherHosts(); } void IndexedDBDispatcherHost::OnDestruct() const { // The last reference to the dispatcher may be a posted task, which would // be destructed on the IndexedDB thread. Without this override, that would // take the dispatcher with it. Since the dispatcher may be keeping the // IndexedDBContext alive, it might be destructed to on its own thread, // which is not supported. Ensure destruction runs on the IO thread instead. BrowserThread::DeleteOnIOThread::Destruct(this); } void IndexedDBDispatcherHost::ResetDispatcherHosts() { // It is important that the various *_dispatcher_host_ members are reset // on the IndexedDB thread, since there might be incoming messages on that // thread, and we must not reset the dispatcher hosts until after those // messages are processed. DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); // Note that we explicitly separate CloseAll() from destruction of the // DatabaseDispatcherHost, since CloseAll() can invoke callbacks which need to // be dispatched through database_dispatcher_host_. database_dispatcher_host_->CloseAll(); database_dispatcher_host_.reset(); cursor_dispatcher_host_.reset(); } base::TaskRunner* IndexedDBDispatcherHost::OverrideTaskRunnerForMessage( const IPC::Message& message) { if (IPC_MESSAGE_CLASS(message) == IndexedDBMsgStart) return indexed_db_context_->TaskRunner(); return NULL; } bool IndexedDBDispatcherHost::OnMessageReceived(const IPC::Message& message, bool* message_was_ok) { if (IPC_MESSAGE_CLASS(message) != IndexedDBMsgStart) return false; DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); bool handled = database_dispatcher_host_->OnMessageReceived(message, message_was_ok) || cursor_dispatcher_host_->OnMessageReceived(message, message_was_ok); if (!handled) { handled = true; IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost, message, *message_was_ok) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryGetDatabaseNames, OnIDBFactoryGetDatabaseNames) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryOpen, OnIDBFactoryOpen) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryDeleteDatabase, OnIDBFactoryDeleteDatabase) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() } return handled; } int32 IndexedDBDispatcherHost::Add(IndexedDBCursor* cursor) { if (!cursor_dispatcher_host_) { return 0; } return cursor_dispatcher_host_->map_.Add(cursor); } int32 IndexedDBDispatcherHost::Add(IndexedDBConnection* connection, int32 ipc_thread_id, const GURL& origin_url) { if (!database_dispatcher_host_) { connection->Close(); delete connection; return -1; } int32 ipc_database_id = database_dispatcher_host_->map_.Add(connection); Context()->ConnectionOpened(origin_url, connection); database_dispatcher_host_->database_url_map_[ipc_database_id] = origin_url; return ipc_database_id; } void IndexedDBDispatcherHost::RegisterTransactionId(int64 host_transaction_id, const GURL& url) { if (!database_dispatcher_host_) return; database_dispatcher_host_->transaction_url_map_[host_transaction_id] = url; } int64 IndexedDBDispatcherHost::HostTransactionId(int64 transaction_id) { // Inject the renderer process id into the transaction id, to // uniquely identify this transaction, and effectively bind it to // the renderer that initiated it. The lower 32 bits of // transaction_id are guaranteed to be unique within that renderer. base::ProcessId pid = peer_pid(); DCHECK(!(transaction_id >> 32)) << "Transaction ids can only be 32 bits"; COMPILE_ASSERT(sizeof(base::ProcessId) <= sizeof(int32), Process_ID_must_fit_in_32_bits); return transaction_id | (static_cast<uint64>(pid) << 32); } int64 IndexedDBDispatcherHost::RendererTransactionId( int64 host_transaction_id) { DCHECK(host_transaction_id >> 32 == peer_pid()) << "Invalid renderer target for transaction id"; return host_transaction_id & 0xffffffff; } // static uint32 IndexedDBDispatcherHost::TransactionIdToRendererTransactionId( int64 host_transaction_id) { return host_transaction_id & 0xffffffff; } // static uint32 IndexedDBDispatcherHost::TransactionIdToProcessId( int64 host_transaction_id) { return (host_transaction_id >> 32) & 0xffffffff; } IndexedDBCursor* IndexedDBDispatcherHost::GetCursorFromId(int32 ipc_cursor_id) { DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); return cursor_dispatcher_host_->map_.Lookup(ipc_cursor_id); } ::IndexedDBDatabaseMetadata IndexedDBDispatcherHost::ConvertMetadata( const content::IndexedDBDatabaseMetadata& web_metadata) { ::IndexedDBDatabaseMetadata metadata; metadata.id = web_metadata.id; metadata.name = web_metadata.name; metadata.version = web_metadata.version; metadata.int_version = web_metadata.int_version; metadata.max_object_store_id = web_metadata.max_object_store_id; for (content::IndexedDBDatabaseMetadata::ObjectStoreMap::const_iterator iter = web_metadata.object_stores.begin(); iter != web_metadata.object_stores.end(); ++iter) { const content::IndexedDBObjectStoreMetadata& web_store_metadata = iter->second; ::IndexedDBObjectStoreMetadata idb_store_metadata; idb_store_metadata.id = web_store_metadata.id; idb_store_metadata.name = web_store_metadata.name; idb_store_metadata.keyPath = web_store_metadata.key_path; idb_store_metadata.autoIncrement = web_store_metadata.auto_increment; idb_store_metadata.max_index_id = web_store_metadata.max_index_id; for (content::IndexedDBObjectStoreMetadata::IndexMap::const_iterator index_iter = web_store_metadata.indexes.begin(); index_iter != web_store_metadata.indexes.end(); ++index_iter) { const content::IndexedDBIndexMetadata& web_index_metadata = index_iter->second; ::IndexedDBIndexMetadata idb_index_metadata; idb_index_metadata.id = web_index_metadata.id; idb_index_metadata.name = web_index_metadata.name; idb_index_metadata.keyPath = web_index_metadata.key_path; idb_index_metadata.unique = web_index_metadata.unique; idb_index_metadata.multiEntry = web_index_metadata.multi_entry; idb_store_metadata.indexes.push_back(idb_index_metadata); } metadata.object_stores.push_back(idb_store_metadata); } return metadata; } void IndexedDBDispatcherHost::OnIDBFactoryGetDatabaseNames( const IndexedDBHostMsg_FactoryGetDatabaseNames_Params& params) { DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); base::FilePath indexed_db_path = indexed_db_context_->data_path(); GURL origin_url = webkit_database::GetOriginFromIdentifier(params.database_identifier); Context()->GetIDBFactory()->GetDatabaseNames( new IndexedDBCallbacks( this, params.ipc_thread_id, params.ipc_callbacks_id), origin_url, indexed_db_path); } void IndexedDBDispatcherHost::OnIDBFactoryOpen( const IndexedDBHostMsg_FactoryOpen_Params& params) { DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); base::FilePath indexed_db_path = indexed_db_context_->data_path(); GURL origin_url = webkit_database::GetOriginFromIdentifier(params.database_identifier); int64 host_transaction_id = HostTransactionId(params.transaction_id); // TODO(dgrogan): Don't let a non-existing database be opened (and therefore // created) if this origin is already over quota. scoped_refptr<IndexedDBCallbacks> callbacks = new IndexedDBCallbacks(this, params.ipc_thread_id, params.ipc_callbacks_id, params.ipc_database_callbacks_id, host_transaction_id, origin_url); scoped_refptr<IndexedDBDatabaseCallbacks> database_callbacks = new IndexedDBDatabaseCallbacks( this, params.ipc_thread_id, params.ipc_database_callbacks_id); Context()->GetIDBFactory()->Open(params.name, params.version, host_transaction_id, callbacks, database_callbacks, origin_url, indexed_db_path); } void IndexedDBDispatcherHost::OnIDBFactoryDeleteDatabase( const IndexedDBHostMsg_FactoryDeleteDatabase_Params& params) { DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); GURL origin_url = webkit_database::GetOriginFromIdentifier(params.database_identifier); base::FilePath indexed_db_path = indexed_db_context_->data_path(); Context()->GetIDBFactory()->DeleteDatabase( params.name, new IndexedDBCallbacks( this, params.ipc_thread_id, params.ipc_callbacks_id), origin_url, indexed_db_path); } void IndexedDBDispatcherHost::FinishTransaction(int64 host_transaction_id, bool committed) { DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); if (!database_dispatcher_host_) return; TransactionIDToURLMap& transaction_url_map = database_dispatcher_host_->transaction_url_map_; TransactionIDToSizeMap& transaction_size_map = database_dispatcher_host_->transaction_size_map_; TransactionIDToDatabaseIDMap& transaction_database_map = database_dispatcher_host_->transaction_database_map_; if (committed) Context()->TransactionComplete(transaction_url_map[host_transaction_id]); transaction_url_map.erase(host_transaction_id); transaction_size_map.erase(host_transaction_id); transaction_database_map.erase(host_transaction_id); } ////////////////////////////////////////////////////////////////////// // Helper templates. // template <typename ObjectType> ObjectType* IndexedDBDispatcherHost::GetOrTerminateProcess( IDMap<ObjectType, IDMapOwnPointer>* map, int32 ipc_return_object_id) { DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); ObjectType* return_object = map->Lookup(ipc_return_object_id); if (!return_object) { NOTREACHED() << "Uh oh, couldn't find object with id " << ipc_return_object_id; RecordAction(base::UserMetricsAction("BadMessageTerminate_IDBMF")); BadMessageReceived(); } return return_object; } template <typename ObjectType> ObjectType* IndexedDBDispatcherHost::GetOrTerminateProcess( RefIDMap<ObjectType>* map, int32 ipc_return_object_id) { DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); ObjectType* return_object = map->Lookup(ipc_return_object_id); if (!return_object) { NOTREACHED() << "Uh oh, couldn't find object with id " << ipc_return_object_id; RecordAction(base::UserMetricsAction("BadMessageTerminate_IDBMF")); BadMessageReceived(); } return return_object; } template <typename MapType> void IndexedDBDispatcherHost::DestroyObject(MapType* map, int32 ipc_object_id) { GetOrTerminateProcess(map, ipc_object_id); map->Remove(ipc_object_id); } ////////////////////////////////////////////////////////////////////// // IndexedDBDispatcherHost::DatabaseDispatcherHost // IndexedDBDispatcherHost::DatabaseDispatcherHost::DatabaseDispatcherHost( IndexedDBDispatcherHost* parent) : parent_(parent) { map_.set_check_on_null_data(true); } IndexedDBDispatcherHost::DatabaseDispatcherHost::~DatabaseDispatcherHost() { // TODO(alecflett): uncomment these when we find the source of these leaks. // DCHECK(transaction_size_map_.empty()); // DCHECK(transaction_url_map_.empty()); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::CloseAll() { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); // Abort outstanding transactions started by connections in the associated // front-end to unblock later transactions. This should only occur on unclean // (crash) or abrupt (process-kill) shutdowns. for (TransactionIDToDatabaseIDMap::iterator iter = transaction_database_map_.begin(); iter != transaction_database_map_.end();) { int64 transaction_id = iter->first; int32 ipc_database_id = iter->second; ++iter; IndexedDBConnection* connection = map_.Lookup(ipc_database_id); if (connection && connection->IsConnected()) { connection->database()->Abort( transaction_id, IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionUnknownError)); } } DCHECK(transaction_database_map_.empty()); for (WebIDBObjectIDToURLMap::iterator iter = database_url_map_.begin(); iter != database_url_map_.end(); iter++) { IndexedDBConnection* connection = map_.Lookup(iter->first); if (connection && connection->IsConnected()) { connection->Close(); parent_->Context()->ConnectionClosed(iter->second, connection); } } } bool IndexedDBDispatcherHost::DatabaseDispatcherHost::OnMessageReceived( const IPC::Message& message, bool* msg_is_ok) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX( IndexedDBDispatcherHost::DatabaseDispatcherHost, message, *msg_is_ok) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCreateObjectStore, OnCreateObjectStore) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDeleteObjectStore, OnDeleteObjectStore) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCreateTransaction, OnCreateTransaction) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseClose, OnClose) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDestroyed, OnDestroyed) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseGet, OnGet) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabasePut, OnPut) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseSetIndexKeys, OnSetIndexKeys) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseSetIndexesReady, OnSetIndexesReady) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseOpenCursor, OnOpenCursor) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCount, OnCount) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDeleteRange, OnDeleteRange) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseClear, OnClear) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCreateIndex, OnCreateIndex) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDeleteIndex, OnDeleteIndex) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseAbort, OnAbort) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCommit, OnCommit) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCreateObjectStore( const IndexedDBHostMsg_DatabaseCreateObjectStore_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id); connection->database()->CreateObjectStore(host_transaction_id, params.object_store_id, params.name, params.key_path, params.auto_increment); if (parent_->Context()->IsOverQuota( database_url_map_[params.ipc_database_id])) { connection->database()->Abort( host_transaction_id, IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionQuotaError)); } } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDeleteObjectStore( int32 ipc_database_id, int64 transaction_id, int64 object_store_id) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, ipc_database_id); if (!connection || !connection->IsConnected()) return; connection->database()->DeleteObjectStore( parent_->HostTransactionId(transaction_id), object_store_id); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCreateTransaction( const IndexedDBHostMsg_DatabaseCreateTransaction_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id); if (transaction_database_map_.find(host_transaction_id) != transaction_database_map_.end()) { DLOG(ERROR) << "Duplicate host_transaction_id."; return; } connection->database()->CreateTransaction( host_transaction_id, connection, params.object_store_ids, params.mode); transaction_database_map_[host_transaction_id] = params.ipc_database_id; parent_->RegisterTransactionId(host_transaction_id, database_url_map_[params.ipc_database_id]); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnClose( int32 ipc_database_id) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, ipc_database_id); if (!connection || !connection->IsConnected()) return; connection->Close(); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDestroyed( int32 ipc_object_id) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = map_.Lookup(ipc_object_id); parent_->Context() ->ConnectionClosed(database_url_map_[ipc_object_id], connection); database_url_map_.erase(ipc_object_id); parent_->DestroyObject(&map_, ipc_object_id); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnGet( const IndexedDBHostMsg_DatabaseGet_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( parent_, params.ipc_thread_id, params.ipc_callbacks_id)); connection->database()->Get( parent_->HostTransactionId(params.transaction_id), params.object_store_id, params.index_id, make_scoped_ptr(new IndexedDBKeyRange(params.key_range)), params.key_only, callbacks); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnPut( const IndexedDBHostMsg_DatabasePut_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( parent_, params.ipc_thread_id, params.ipc_callbacks_id)); int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id); // TODO(alecflett): Avoid a copy here. std::string value_copy(params.value); connection->database()->Put( host_transaction_id, params.object_store_id, &value_copy, make_scoped_ptr(new IndexedDBKey(params.key)), static_cast<IndexedDBDatabase::PutMode>(params.put_mode), callbacks, params.index_keys); TransactionIDToSizeMap* map = &parent_->database_dispatcher_host_->transaction_size_map_; // Size can't be big enough to overflow because it represents the // actual bytes passed through IPC. (*map)[host_transaction_id] += params.value.size(); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnSetIndexKeys( const IndexedDBHostMsg_DatabaseSetIndexKeys_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id); connection->database()->SetIndexKeys( host_transaction_id, params.object_store_id, make_scoped_ptr(new IndexedDBKey(params.primary_key)), params.index_keys); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnSetIndexesReady( int32 ipc_database_id, int64 transaction_id, int64 object_store_id, const std::vector<int64>& index_ids) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, ipc_database_id); if (!connection || !connection->IsConnected()) return; connection->database()->SetIndexesReady( parent_->HostTransactionId(transaction_id), object_store_id, index_ids); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnOpenCursor( const IndexedDBHostMsg_DatabaseOpenCursor_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( parent_, params.ipc_thread_id, params.ipc_callbacks_id, -1)); connection->database()->OpenCursor( parent_->HostTransactionId(params.transaction_id), params.object_store_id, params.index_id, make_scoped_ptr(new IndexedDBKeyRange(params.key_range)), static_cast<indexed_db::CursorDirection>(params.direction), params.key_only, static_cast<IndexedDBDatabase::TaskType>(params.task_type), callbacks); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCount( const IndexedDBHostMsg_DatabaseCount_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( parent_, params.ipc_thread_id, params.ipc_callbacks_id)); connection->database()->Count( parent_->HostTransactionId(params.transaction_id), params.object_store_id, params.index_id, make_scoped_ptr(new IndexedDBKeyRange(params.key_range)), callbacks); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDeleteRange( const IndexedDBHostMsg_DatabaseDeleteRange_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( parent_, params.ipc_thread_id, params.ipc_callbacks_id)); connection->database()->DeleteRange( parent_->HostTransactionId(params.transaction_id), params.object_store_id, make_scoped_ptr(new IndexedDBKeyRange(params.key_range)), callbacks); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnClear( int32 ipc_thread_id, int32 ipc_callbacks_id, int32 ipc_database_id, int64 transaction_id, int64 object_store_id) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, ipc_database_id); if (!connection || !connection->IsConnected()) return; scoped_refptr<IndexedDBCallbacks> callbacks( new IndexedDBCallbacks(parent_, ipc_thread_id, ipc_callbacks_id)); connection->database()->Clear( parent_->HostTransactionId(transaction_id), object_store_id, callbacks); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnAbort( int32 ipc_database_id, int64 transaction_id) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, ipc_database_id); if (!connection || !connection->IsConnected()) return; connection->database()->Abort(parent_->HostTransactionId(transaction_id)); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCommit( int32 ipc_database_id, int64 transaction_id) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, ipc_database_id); if (!connection || !connection->IsConnected()) return; int64 host_transaction_id = parent_->HostTransactionId(transaction_id); int64 transaction_size = transaction_size_map_[host_transaction_id]; if (transaction_size && parent_->Context()->WouldBeOverQuota( transaction_url_map_[host_transaction_id], transaction_size)) { connection->database()->Abort( host_transaction_id, IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionQuotaError)); return; } connection->database()->Commit(host_transaction_id); } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCreateIndex( const IndexedDBHostMsg_DatabaseCreateIndex_Params& params) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, params.ipc_database_id); if (!connection || !connection->IsConnected()) return; int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id); connection->database()->CreateIndex(host_transaction_id, params.object_store_id, params.index_id, params.name, params.key_path, params.unique, params.multi_entry); if (parent_->Context()->IsOverQuota( database_url_map_[params.ipc_database_id])) { connection->database()->Abort( host_transaction_id, IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionQuotaError)); } } void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDeleteIndex( int32 ipc_database_id, int64 transaction_id, int64 object_store_id, int64 index_id) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBConnection* connection = parent_->GetOrTerminateProcess(&map_, ipc_database_id); if (!connection || !connection->IsConnected()) return; connection->database()->DeleteIndex( parent_->HostTransactionId(transaction_id), object_store_id, index_id); } ////////////////////////////////////////////////////////////////////// // IndexedDBDispatcherHost::CursorDispatcherHost // IndexedDBDispatcherHost::CursorDispatcherHost::CursorDispatcherHost( IndexedDBDispatcherHost* parent) : parent_(parent) { map_.set_check_on_null_data(true); } IndexedDBDispatcherHost::CursorDispatcherHost::~CursorDispatcherHost() {} bool IndexedDBDispatcherHost::CursorDispatcherHost::OnMessageReceived( const IPC::Message& message, bool* msg_is_ok) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX( IndexedDBDispatcherHost::CursorDispatcherHost, message, *msg_is_ok) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorAdvance, OnAdvance) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorContinue, OnContinue) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorPrefetch, OnPrefetch) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorPrefetchReset, OnPrefetchReset) IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorDestroyed, OnDestroyed) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void IndexedDBDispatcherHost::CursorDispatcherHost::OnAdvance( int32 ipc_cursor_id, int32 ipc_thread_id, int32 ipc_callbacks_id, unsigned long count) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, ipc_cursor_id); if (!idb_cursor) return; idb_cursor->Advance( count, new IndexedDBCallbacks( parent_, ipc_thread_id, ipc_callbacks_id, ipc_cursor_id)); } void IndexedDBDispatcherHost::CursorDispatcherHost::OnContinue( int32 ipc_cursor_id, int32 ipc_thread_id, int32 ipc_callbacks_id, const IndexedDBKey& key, const IndexedDBKey& primary_key) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, ipc_cursor_id); if (!idb_cursor) return; idb_cursor->Continue( key.IsValid() ? make_scoped_ptr(new IndexedDBKey(key)) : scoped_ptr<IndexedDBKey>(), primary_key.IsValid() ? make_scoped_ptr(new IndexedDBKey(primary_key)) : scoped_ptr<IndexedDBKey>(), new IndexedDBCallbacks( parent_, ipc_thread_id, ipc_callbacks_id, ipc_cursor_id)); } void IndexedDBDispatcherHost::CursorDispatcherHost::OnPrefetch( int32 ipc_cursor_id, int32 ipc_thread_id, int32 ipc_callbacks_id, int n) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, ipc_cursor_id); if (!idb_cursor) return; idb_cursor->PrefetchContinue( n, new IndexedDBCallbacks( parent_, ipc_thread_id, ipc_callbacks_id, ipc_cursor_id)); } void IndexedDBDispatcherHost::CursorDispatcherHost::OnPrefetchReset( int32 ipc_cursor_id, int used_prefetches, int unused_prefetches) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); IndexedDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, ipc_cursor_id); if (!idb_cursor) return; idb_cursor->PrefetchReset(used_prefetches, unused_prefetches); } void IndexedDBDispatcherHost::CursorDispatcherHost::OnDestroyed( int32 ipc_object_id) { DCHECK( parent_->indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); parent_->DestroyObject(&map_, ipc_object_id); } } // namespace content
ORG 00H MAIN:MOV A,#00h ;Move ‘00’ to A register. MOV P1,A ;Content of register A is moved to Port1 ACALL DELAY ;Call delay routine CPL A ;Complement the contents of register A and store it in AMOV P1,A ;Move the contents of A to Port1 ACALL DELAY ;Call delay routine SJMP MAIN DELAY: MOV R2,#0FFH ;Delay routine UP1: MOV R3,#0FFH HERE: DJNZ R2,UP1 RET END
/** * Copyright (C) 2015-2017 Virgil Security Inc. * * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * (1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * (3) Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <cli/argument/ArgumentIO.h> #include <cli/api/api.h> #include <cli/api/Configurations.h> #include <cli/command/Command.h> #include <cli/error/ArgumentError.h> #include <cli/io/Logger.h> #include <cli/io/Path.h> #include <cli/model/EncryptCredentials.h> #include <cli/model/DecryptCredentials.h> #include <cli/model/PasswordEncryptCredentials.h> #include <cli/model/PasswordDecryptCredentials.h> #include <cli/model/KeyEncryptCredentials.h> #include <cli/model/KeyDecryptCredentials.h> #include <cli/command/KeygenCommand.h> #include <cli/command/KeyToPubCommand.h> #include <cli/command/EncryptCommand.h> #include <cli/command/DecryptCommand.h> #include <cli/argument/validation/ArgumentValidationHub.h> #include <cli/memory.h> #include <istream> #include <ostream> #include <fstream> #include <iostream> #include <algorithm> #include <iterator> using namespace cli; using namespace cli::argument; using namespace cli::argument::validation; using namespace cli::command; using namespace cli::model; #undef IN #undef OUT ArgumentIO::ArgumentIO(std::unique_ptr<ArgumentSource> argumentSource, std::unique_ptr<ArgumentValueSource> argumentValueSource) : argumentSource_(std::move(argumentSource)), argumentValueSource_(std::move(argumentValueSource)) { DCHECK(argumentSource_); DCHECK(argumentValueSource_); } void ArgumentIO::configureUsage(const char* usage, const ArgumentParseOptions& parseOptions) { argumentSource_->init(usage, parseOptions); argumentValueSource_->init(*argumentSource_); } bool ArgumentIO::hasContentInfo() const { auto argument = argumentSource_->read(opt::CONTENT_INFO, ArgumentImportance::Optional); return !argument.isEmpty(); } bool ArgumentIO::hasNoPassword() const { ULOG2(INFO) << "Check if password should be omitted."; auto argument = argumentSource_->read(opt::NO_PASSWORD, ArgumentImportance::Optional); ArgumentValidationHub::isNumber()->validate(argument, ArgumentImportance::Optional); return argument.asValue().asOptionalBool(); } bool ArgumentIO::isInteractive() const { ULOG2(INFO) << "Check if interactive mode is on."; auto argument = argumentSource_->read(opt::INTERACTIVE, ArgumentImportance::Optional); ArgumentValidationHub::isNumber()->validate(argument, ArgumentImportance::Optional); return argument.asValue().asOptionalBool(); } bool ArgumentIO::isPublicKey() const { ULOG2(INFO) << "Check if given Public Key as input."; auto argument = argumentSource_->read(opt::PUBLIC, ArgumentImportance::Optional); ArgumentValidationHub::isNumber()->validate(argument, ArgumentImportance::Optional); return argument.asValue().asOptionalBool(); } bool ArgumentIO::isPrivateKey() const { ULOG2(INFO) << "Check if given Private Key as input."; auto argument = argumentSource_->read(opt::PRIVATE, ArgumentImportance::Optional); ArgumentValidationHub::isNumber()->validate(argument, ArgumentImportance::Optional); return argument.asValue().asOptionalBool(); } bool ArgumentIO::isNoFormat() const { ULOG2(INFO) << "Check if output should not be formatted."; auto argument = argumentSource_->read(opt::NO_FORMAT, ArgumentImportance::Optional); ArgumentValidationHub::isNumber()->validate(argument, ArgumentImportance::Optional); return argument.asValue().asOptionalBool(); } bool ArgumentIO::isAll() const { ULOG2(INFO) << "Check if --all flag is given."; auto argument = argumentSource_->read(opt::ALL, ArgumentImportance::Optional); ArgumentValidationHub::isNumber()->validate(argument, ArgumentImportance::Optional); return argument.asValue().asOptionalBool(); } SecureValue ArgumentIO::getInput(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read input value."; auto argument = argumentSource_->read(opt::IN, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return argumentValueSource_->readPassword(argument.asValue()); } SecureValue ArgumentIO::getOutput(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read output value."; auto argument = argumentSource_->read(opt::OUT, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return SecureValue(argument.asValue().value()); } FileDataSource ArgumentIO::getInputSource(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read input source."; auto argument = argumentSource_->read(opt::IN, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return getSource(argument.asValue()); } FileDataSink ArgumentIO::getOutputSink(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read output destination."; auto argument = argumentSource_->read(opt::OUT, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return getSink(argument.asValue()); } FileDataSource ArgumentIO::getContentInfoSource(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read content info source."; auto argument = argumentSource_->read(opt::CONTENT_INFO, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return getSource(argument.asValue()); } FileDataSink ArgumentIO::getContentInfoSink(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read content info destination."; auto argument = argumentSource_->read(opt::CONTENT_INFO, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return getSink(argument.asValue()); } std::vector<std::unique_ptr<EncryptCredentials>> ArgumentIO::getEncryptCredentials(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read recipients for encryption."; auto argument = argumentSource_->read(arg::RECIPIENT_ID, argumentImportance); argument.parse(); auto validation = ArgumentValidationHub::isKeyValue(); validation->setKeyValidation(ArgumentValidationHub::isEnum(arg::value::VIRGIL_ENCRYPT_RECIPIENT_ID_VALUES)); validation->setValueValidation(ArgumentValidationHub::isNotEmpty()); validation->validateList(argument, argumentImportance); std::vector<std::unique_ptr<EncryptCredentials>> result; for (const auto& argumentValue : argument.asList()) { auto credentials = readEncryptCredentials(argumentValue); result.insert(result.end(), std::make_move_iterator(credentials.begin()), std::make_move_iterator(credentials.end())); } if (result.empty()) { LOG(WARNING) << "Credentials for encryption was not found."; } return result; } std::vector<std::unique_ptr<DecryptCredentials>> ArgumentIO::getDecryptCredentials(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read decryption credentials."; auto argument = argumentSource_->read(arg::KEYPASS, argumentImportance); argument.parse(); auto validation = ArgumentValidationHub::isKeyValue(); validation->setKeyValidation(ArgumentValidationHub::isEnum(arg::value::VIRGIL_DECRYPT_KEYPASS_VALUES)); validation->setValueValidation(ArgumentValidationHub::isNotEmpty()); validation->validateList(argument, argumentImportance); std::vector<std::unique_ptr<DecryptCredentials>> result; for (const auto& argumentValue : argument.asList()) { auto decryptCredentials = readDecryptCredentials(argumentValue); result.insert(result.end(), std::make_move_iterator(decryptCredentials.begin()), std::make_move_iterator(decryptCredentials.end())); } return result; } KeyAlgorithm ArgumentIO::getKeyAlgorithm(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read private key algorithm."; auto argument = argumentSource_->read(opt::ALGORITHM, argumentImportance); ArgumentValidationHub::isEnum(arg::value::VIRGIL_KEYGEN_ALG_VALUES)->validate(argument, argumentImportance); return argumentValueSource_->readKeyAlgorithm(argument.asValue()); } PrivateKey ArgumentIO::getPrivateKey(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read private key."; auto argument = argumentSource_->read(opt::PRIVATE_KEY, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); auto privateKey = argumentValueSource_->readPrivateKey(argument.asValue()); readPrivateKeyPassword(privateKey, argument.asValue(), opt::PRIVATE_KEY_PASSWORD); return std::move(privateKey); } PrivateKey ArgumentIO::getPrivateKeyFromInput(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read private key."; auto argument = argumentSource_->read(opt::IN, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); auto source = getSource(argument.asValue()); PrivateKey privateKey(source.readAll(), Crypto::Bytes()); readPrivateKeyPassword(privateKey, argument.asValue(), opt::PRIVATE_KEY_PASSWORD); return std::move(privateKey); } Password ArgumentIO::getKeyPassword(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read private key password."; auto argument = argumentSource_->readSecure(opt::PRIVATE_KEY_PASSWORD, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return argumentValueSource_->readPassword(argument.asValue()); } PublicKey ArgumentIO::getSenderKey(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Sender's public key."; auto argument = argumentSource_->read(arg::RECIPIENT_ID, argumentImportance); argument.parse(); auto validation = ArgumentValidationHub::isKeyValue(); validation->setKeyValidation(ArgumentValidationHub::isEnum(arg::value::VIRGIL_VERIFY_RECIPIENT_ID_VALUES)); validation->setValueValidation(ArgumentValidationHub::isNotEmpty()); validation->validate(argument, argumentImportance); return readSenderKey(argument.asValue()); } FileDataSource ArgumentIO::getSignatureSource(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read signature source."; auto argument = argumentSource_->read(opt::SIGN, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return getSource(argument.asValue()); } Crypto::Text ArgumentIO::getCommand(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read command."; auto argument = argumentSource_->read(arg::COMMAND, argumentImportance); ArgumentValidationHub::isEnum(arg::value::VIRGIL_COMMAND_VALUES)->validate(argument, argumentImportance); return Crypto::Text(argument.asValue().value()); } CardIdentity ArgumentIO::getCardIdentity(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card identity."; auto argument = argumentSource_->read(arg::IDENTITY, argumentImportance); argument.parse(); auto validation = ArgumentValidationHub::isKeyValue(); validation->setKeyValidation(ArgumentValidationHub::isAny()); validation->setValueValidation(ArgumentValidationHub::isNotEmpty()); validation->validate(argument, argumentImportance); return CardIdentity(argument.asValue().value(), argument.asValue().key()); } CardIdentityGroup ArgumentIO::getCardIdentityGroup(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card identities."; auto argument = argumentSource_->read(arg::IDENTITY, argumentImportance); argument.parse(); ArgumentValidationHub::isNotEmpty()->validateList(argument, argumentImportance); CardIdentityGroup identityGroup; for (const auto argumentValue : argument.asList()) { identityGroup.append(argumentValue.value(), argumentValue.key()); } return identityGroup; } Crypto::Text ArgumentIO::getCardScope(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card scope."; auto argument = argumentSource_->read(opt::SCOPE, argumentImportance); ArgumentValidationHub::isEnum(arg::value::VIRGIL_CARD_CREATE_SCOPE_VALUES)->validate(argument, argumentImportance); return argument.asValue().asString(); } CardData ArgumentIO::getCardData(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card data."; auto argument = argumentSource_->read(opt::DATA, argumentImportance); argument.parse(); auto validation = ArgumentValidationHub::isKeyValue(); validation->setKeyValidation(ArgumentValidationHub::isNotEmpty()); validation->setValueValidation(ArgumentValidationHub::isNotEmpty()); validation->validateList(argument, argumentImportance); CardData cardData; for (const auto& argumentValue : argument.asList()) { cardData[argumentValue.key()] = argumentValue.value(); } return cardData; } CardInfo ArgumentIO::getCardInfo(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card info."; auto argument = argumentSource_->read(opt::INFO, argumentImportance); argument.parse(); auto validation = ArgumentValidationHub::isKeyValue(); validation->setKeyValidation(ArgumentValidationHub::isEnum(arg::value::VIRGIL_CARD_CREATE_INFO_KEY_VALUES)); validation->setValueValidation(ArgumentValidationHub::isNotEmpty()); validation->validateList(argument, argumentImportance); std::string device; std::string deviceName; for (const auto& argumentValue : argument.asList()) { auto infoKey = argumentValue.key(); if (infoKey == arg::value::VIRGIL_CARD_CREATE_INFO_KEY_DEVICE) { device = argumentValue.value(); } else if (infoKey == arg::value::VIRGIL_CARD_CREATE_INFO_KEY_DEVICE_NAME) { deviceName = argumentValue.value(); } else { throw error::ArgumentLogicError("Undefined key of the Virgil Card Info. Validation must fail first."); } } return CardInfo(device, deviceName); } std::vector<std::string> ArgumentIO::getCardOutputFormat(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card output format."; auto argument = argumentSource_->read(opt::FORMAT, argumentImportance); ArgumentValidationHub::isEnum(arg::value::VIRGIL_CARD_INFO_OUTPUT_FORMAT_VALUES) ->validateList(argument, argumentImportance); return argument.asStringList(); } SecureValue ArgumentIO::getAppAccessToken(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Application Access Token."; auto argument = argumentSource_->readSecure(arg::value::VIRGIL_CONFIG_APP_ACCESS_TOKEN, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return argumentValueSource_->readPassword(argument.asValue()); } ApplicationCredentials ArgumentIO::getAppCredentials(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Application Credentials (identifier, private key, private key password)."; auto argumentAppKeyId = argumentSource_->readSecure(arg::value::VIRGIL_CONFIG_APP_KEY_ID, argumentImportance); auto argumentAppKeyData = argumentSource_->readSecure(arg::value::VIRGIL_CONFIG_APP_KEY, argumentImportance); ArgumentValidationHub::isText()->validate(argumentAppKeyId, argumentImportance); ArgumentValidationHub::isText()->validate(argumentAppKeyData, argumentImportance); auto appId = argumentValueSource_->readPassword(argumentAppKeyId.asValue()); auto appKey = argumentValueSource_->readPrivateKey(argumentAppKeyData.asValue()); readPrivateKeyPassword(appKey, argumentAppKeyData.asValue(), arg::value::VIRGIL_CONFIG_APP_KEY_PASSWORD); return ApplicationCredentials(std::move(appId), std::move(appKey)); } Card ArgumentIO::getCardFromInput(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card from input."; auto argument = argumentSource_->read(opt::IN, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return argumentValueSource_->readCard(argument.asValue()); } std::vector<Card> ArgumentIO::getCardListFromInput(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card(s) from input."; auto argument = argumentSource_->read(opt::IN, argumentImportance); ArgumentValidationHub::isText()->validateList(argument, argumentImportance); std::vector<Card> result; if (argument.isList()) { // If arguments are given, then the source is files. argumentValueSource_->resetFilter({ ArgumentSourceType::File }); for (auto argumentValue : argument.asList()) { if (!io::Path::existsFile(argumentValue.value())) { ULOG(WARNING) << tfm::format("File '%s' does not exist.", argumentValue.value()); continue; } result.push_back(argumentValueSource_->readCard(argumentValue)); } } else { // Source is standard input so it should be parsed. argumentValueSource_->resetFilter({ ArgumentSourceType::Parser }); for (auto cardString : FileDataSource().readMultiLine()) { result.push_back(argumentValueSource_->readCard(ArgumentValue(cardString))); } } argumentValueSource_->resetFilter({ ArgumentSourceType::Any }); return result; } CardRevocationReason ArgumentIO::getCardRevokeReason(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read Virgil Card revocation reason."; auto argument = argumentSource_->read(opt::REVOCATION_REASON, argumentImportance); ArgumentValidationHub::isEnum(arg::value::VIRGIL_CARD_REVOKE_REASON_VALUES)->validate(argument, argumentImportance); return card_revocation_reason_from(argument.asValue().asString()); } HashAlgorithm ArgumentIO::getHashAlgorithm(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read hash algorithm."; auto argument = argumentSource_->read(opt::HASH_ALGORITHM, argumentImportance); ArgumentValidationHub::isEnum(arg::value::VIRGIL_SIGN_HASH_ALG_VALUES)->validate(argument, argumentImportance); return argumentValueSource_->readHashAlgorithm(argument.asValue()); } FileDataSource ArgumentIO::getSaltSource(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read salt source."; auto argument = argumentSource_->read(opt::SALT, argumentImportance); ArgumentValidationHub::isText()->validate(argument, argumentImportance); return getSource(argument.asValue()); } size_t ArgumentIO::getIterationCount(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read iteration count (iterations)."; auto argument = argumentSource_->read(opt::ITERATIONS, argumentImportance); argument.parse(); ArgumentValidationHub::isRange( arg::value::VIRGIL_SECRET_ALIAS_ITERATION_COUNT_MIN, arg::value::VIRGIL_SECRET_ALIAS_ITERATION_COUNT_MAX)->validate(argument, argumentImportance); return argument.asValue().asNumber(); } Crypto::Text ArgumentIO::getKeyFormat(ArgumentImportance argumentImportance) const { ULOG2(INFO) << "Read key format."; auto argument = argumentSource_->read(arg::KEY_FORMAT, argumentImportance); ArgumentValidationHub::isEnum( arg::value::VIRGIL_KEY_FORMAT_KEY_FORMAT_VALUES)->validate(argument, argumentImportance); return argument.asValue().asString(); } FileDataSource ArgumentIO::getSource(const ArgumentValue& argumentValue) const { if (argumentValue.isEmpty()) { ULOG3(INFO) << tfm::format("Read source is standard input."); return FileDataSource(); } else { ULOG3(INFO) << tfm::format("Read source is file: '%s'.", argumentValue.value()); return FileDataSource(argumentValue.value()); } } FileDataSink ArgumentIO::getSink(const ArgumentValue& argumentValue) const { if (argumentValue.isEmpty()) { ULOG3(INFO) << tfm::format("Write destination is standard output."); return FileDataSink(); } else { ULOG3(INFO) << tfm::format("Write destination is file: '%s'.", argumentValue.value()); return FileDataSink(argumentValue.value()); } } void ArgumentIO::readPrivateKeyPassword( PrivateKey& privateKey, const ArgumentValue& argumentValue, const char* passwordArgumentKey) const { ULOG2(INFO) << "Read private key password."; if (!privateKey.isEncrypted()) { return; } std::string passwordOption = passwordArgumentKey; do { DLOG(INFO) << tfm::format("Read password for the private key: '%s'.", std::to_string(argumentValue)); auto argument = argumentSource_->readSecure(passwordOption.c_str(), ArgumentImportance::Required); auto password = argumentValueSource_->readPassword(argument.asValue()); if (privateKey.checkPassword(password)) { privateKey.setPassword(std::move(password)); return; } passwordOption = argumentValue.value(); } while (isInteractive()); throw error::ArgumentRuntimeError( tfm::format("Wrong password for the private key '%s'.", std::to_string(argumentValue))); } std::vector<std::unique_ptr<EncryptCredentials>> ArgumentIO::readEncryptCredentials(const ArgumentValue& argumentValue) const { DLOG(INFO) << tfm::format("Read recipient(s) from the value: '%s'.", std::to_string(argumentValue)); auto recipientType = argumentValue.key(); std::vector<std::unique_ptr<EncryptCredentials>> result; if (recipientType == arg::value::VIRGIL_ENCRYPT_RECIPIENT_ID_PASSWORD) { result.push_back(std::make_unique<PasswordEncryptCredentials>( argumentValueSource_->readPassword(argumentValue) )); } else if (recipientType == arg::value::VIRGIL_ENCRYPT_RECIPIENT_ID_PUBKEY) { result.push_back(std::make_unique<KeyEncryptCredentials>( argumentValueSource_->readPublicKey(argumentValue) )); } else if (recipientType == arg::value::VIRGIL_ENCRYPT_RECIPIENT_ID_EMAIL) { auto cards = argumentValueSource_->readCards(argumentValue); for (auto&& card : cards) { result.push_back(std::make_unique<KeyEncryptCredentials>(std::move(card))); } if (cards.empty()) { ULOG(WARNING) << tfm::format( "Recipient with identity '%s:%s' is ignored, because it does not have any registered Virgil Card.", argumentValue.key(), argumentValue.value()); } } else if (recipientType == arg::value::VIRGIL_ENCRYPT_RECIPIENT_ID_VCARD) { auto card = argumentValueSource_->readCard(argumentValue); result.push_back(std::make_unique<KeyEncryptCredentials>(std::move(card))); } else { throw error::ArgumentLogicError( tfm::format("Undefined key of the <%s>. Validation must fail first.", arg::RECIPIENT_ID)); } return result; } std::vector<std::unique_ptr<DecryptCredentials>> ArgumentIO::readDecryptCredentials(const ArgumentValue& argumentValue) const { DLOG(INFO) << tfm::format("Read recipient(s) from the value: '%s'.", std::to_string(argumentValue)); auto recipientType = argumentValue.key(); std::vector<std::unique_ptr<DecryptCredentials>> result; if (recipientType == arg::value::VIRGIL_DECRYPT_KEYPASS_PASSWORD) { result.push_back(std::make_unique<PasswordDecryptCredentials>( argumentValueSource_->readPassword(argumentValue) )); } else if (recipientType == arg::value::VIRGIL_DECRYPT_KEYPASS_PRIVKEY) { auto privateKey = argumentValueSource_->readPrivateKey(argumentValue); readPrivateKeyPassword(privateKey, argumentValue, opt::PRIVATE_KEY_PASSWORD); result.push_back(std::make_unique<KeyDecryptCredentials>(std::move(privateKey))); } else { throw error::ArgumentLogicError( tfm::format("Undefined key of the <%s>. Validation must fail first.", arg::KEYPASS)); } return result; } PublicKey ArgumentIO::readSenderKey(const ArgumentValue& argumentValue) const { DLOG(INFO) << tfm::format("Read Sender's key from the value: '%s'.", std::to_string(argumentValue)); if (argumentValue.key() == arg::value::VIRGIL_VERIFY_RECIPIENT_ID_PUBKEY) { return argumentValueSource_->readPublicKey(argumentValue); } else if (argumentValue.key() == arg::value::VIRGIL_VERIFY_RECIPIENT_ID_VCARD) { auto card = argumentValueSource_->readCard(argumentValue); return PublicKey(card.publicKeyData(), card.identifier()); } throw error::ArgumentLogicError( tfm::format("Undefined key of the <%s>. Validation must fail first.", arg::RECIPIENT_ID)); }
;; Virtual File System ;; TODO. This is but a dummy. class vfs ;! Read from a file descriptor into memory. ;: Int fd -> *Mem buf -> Int size -> Int read_size ;= read ; TODO: Should not be in the vfs. proc 0, read read = vfs.read assert rdi, na, 0, "The current VFS is dumb and only works on fd 0" cmp rdx, file_init.size jb .over mov rdx, file_init.size .over: mov rdi, rsi lea rsi, [file_init] tailcall memcpy endproc ;! Open a file ;: *Char filename -> Int flags -> Int fd ;= open proc 0, open open = vfs.open mov eax, 0 ret endproc endclass file_init: file 'initramfs/sbin/init' file_init.size = $ - file_init
#include "while.h" #include "../expr/const.h" ///////////////////// // While statement // ///////////////////// void WhileNode::semant( Environ *e ){ expr=expr->semant( e ); expr=expr->castTo( Type::int_type,e ); string brk=e->setBreak( sem_brk=genLabel() ); stmts->semant( e ); e->setBreak( brk ); } void WhileNode::translate( Codegen *g ){ string loop=genLabel(); if( ConstNode *c=expr->constNode() ){ if( !c->intValue() ) return; g->label( loop ); stmts->translate( g ); g->code( jump( loop ) ); }else{ string cond=genLabel(); g->code( jump( cond ) ); g->label( loop ); stmts->translate( g ); debug( wendPos,g ); g->label( cond ); g->code( jumpt( expr->translate( g ),loop ) ); } g->label( sem_brk ); } #ifdef USE_LLVM void WhileNode::translate2( Codegen_LLVM *g ){ ConstNode *c=expr->constNode(); if( c && !c->intValue() ) return; auto current_block = g->builder->GetInsertBlock(); auto func=g->builder->GetInsertBlock()->getParent(); auto loop=llvm::BasicBlock::Create( g->context,"while",func ); auto next=llvm::BasicBlock::Create( g->context,"wend" ); g->builder->CreateBr( loop ); g->builder->SetInsertPoint( loop ); if( !c ) { auto body=llvm::BasicBlock::Create( g->context,"body" ); auto v=expr->translate2( g ); g->builder->CreateCondBr( v,body,next ); func->getBasicBlockList().push_back( body ); g->builder->SetInsertPoint( body ); } auto oldBreakBlock=g->breakBlock; g->breakBlock=next; stmts->translate2( g ); g->breakBlock=oldBreakBlock; g->builder->CreateBr( loop ); func->getBasicBlockList().push_back( next ); g->builder->SetInsertPoint( next ); } #endif json WhileNode::toJSON( Environ *e ){ json tree;tree["@class"]="WhileNode"; tree["pos"]=pos; tree["wendPos"]=wendPos; tree["expr"]=expr->toJSON( e ); tree["stmts"]=stmts->toJSON( e ); tree["sem_brk"]=sem_brk; return tree; }
.data texto: .asciiz "A Universidade Federal do ABC (UFABC) é uma instituição pública federal de ensino superior no ABC paulista." disciplina: .ascii "Arquitetura de Computadores." .text main: la $t0, imprime la $t1, disciplina srl $t1, $t1, 2 sll $t1, $t1, 2 addi $t1, $t1, 4 lw $t2, 0($t0) sw $t2, 0($t1) lw $t2, 4($t0) sw $t2, 4($t1) lw $t2, 8($t0) sw $t2, 8($t1) lw $t2, 12($t0) sw $t2, 12($t1) lw $t2, 16($t0) sw $t2, 16($t1) lw $t2, 20($t0) sw $t2, 20($t1) jalr $t1 nop addi $v0, $zero, 10 # exit syscall code = 10 syscall imprime: # Imprime texto la $a0, texto # coloca em a0 o parâmetro da chamada a syscall li $v0, 4 # 4 é o código para imprimir uma string syscall jr $ra nop
#include "ImwStatusBar.h" #include "ImwWindowManager.h" namespace ImWindow { //SFF_BEGIN ImwStatusBar::ImwStatusBar(int iHorizontalPriority, bool bAutoDeleted) { m_iHorizontalPriority = iHorizontalPriority; m_bAutoDeleted = bAutoDeleted; ImwWindowManager::GetInstance()->AddStatusBar(this); } ImwStatusBar::ImwStatusBar(const ImwStatusBar& oStatusBar) { m_iHorizontalPriority = oStatusBar.m_iHorizontalPriority; } ImwStatusBar::~ImwStatusBar() { ImwWindowManager::GetInstance()->RemoveStatusBar(this); } void ImwStatusBar::OnStatusBar() { } int ImwStatusBar::GetHorizontalPriority() const { return m_iHorizontalPriority; } bool ImwStatusBar::IsAutoDeleted() { return m_bAutoDeleted; } //SFF_END }
;;;------------------------------------------------- ;; Configure the system clock & flash timing ;; ;; Code for F303x8, clock set to 48 MHz from HSI ;; ;; Different speed can be achieved by changing the value ;; of PLL_MUL in RCC_CFGR. ;; Cfg_RCC PROC PUSH {R0, R1, R2, LR} ; --- Flash timing config --- ; Frefetch, Latency LDR R2, =FLASH_ACR LDR R1, =(FLASH_ACR_PRFTBE :OR: (1 << FLASH_ACR_LATENCY_ofs)) STR R1, [R2] ; --- Internal High-speed Oscillator --- ; Power on HSI (runs from MSI on start) LDR R2, =RCC_CR LDR R1, [R2] ORR R1, #RCC_CR_HSION STR R1, [R2] ; Wait for HSIRDY LDR R0, =RCC_CR HsyWait LDR R1, [R0] TST R1, #RCC_CR_HSIRDY BEQ HsyWait ; --- PLL to get higher frequency --- ; Set up PLL LDR R2, =RCC_CFGR LDR R1, =0 ORR R1, #(2_100 << RCC_CFGR_PPRE1_ofs) ; APB1 divided by 2 (AHB, APB2 not divided - 0b000 in register) ORR R1, #(2_00 << RCC_CFGR_PLLSRC_ofs) ; PPLSRC = HSI - 0b00 = HSI/2 ORR R1, #(2_1010 << RCC_CFGR_PLLMUL_ofs) ; PLL_MUL -> (8MHz / 2) x12 = 48MHz -- built-in PREDIV2 in k8 STR R1, [R2] ; Power on PLL LDR R2, =RCC_CR LDR R1, [R2] ORR R1, #RCC_CR_PLLON STR R1, [R2] ; Wait for PLLRDY LDR R0, =RCC_CR PllWait LDR R1, [R0] TST R1, #RCC_CR_PLLRDY BEQ PllWait ; --- Select PLL as source --- ; write 0b10 to RCC_CFGR_SW ; Select PLL as the core clock source LDR R2, =RCC_CFGR LDR R1, [R2] ; clear field LDR R0, =RCC_CFGR_SW BIC R1, R0 ; select PLL LDR R0, =(2_10 << RCC_CFGR_SW_ofs) ORR R1, R0 ; save STR R1, [R2] ; TODO: should now wait for the switch (SWS == SW) POP {R0, R1, R2, PC} ENDP ;; ;;;------------------------------------------------- END
IFNDEF INCLUDED_ONCE DEFINE INCLUDED_ONCE INCLUDE "struct_misc.asm" ; instance defined structures (those which exist, which includes notEndedOne?!) i1 name1 imod1 @mod1.name1 i2 name2 ie notEndedOne ELSE STRUCT name1 x BYTE 100 ENDS MODULE mod1 STRUCT name1 x BYTE 101 ENDS STRUCT @name2 x BYTE 102 ENDS ENDMODULE STRUCT 1llegal name ENDS STRUCT @. ENDS STRUCT name3, & ENDS STRUCT notEndedOne x BYTE 103 ENDIF
# demonstrates multiple return values # ======================================== # function with 5 return values .fun multi NORMAL [F64 F64 F64 F64] = [F64 F64] .bbl start poparg a:F64 poparg b:F64 add add:F64 = a b sub sub:F64 = a b mul mul:F64 = a b div div:F64 = a b # rem mod:F64 = a b # pusharg mod pusharg div pusharg mul pusharg sub pusharg add ret # ======================================== .fun main NORMAL [S32] = [] .reg F64 [a s m d M x y] .reg A64 [f] .bbl start mov xi:S32 = 70 mov yi:S32 = 6 conv x xi conv y yi pusharg y pusharg x bsr multi poparg a poparg s poparg m poparg d # poparg M conv a2:U32 a pusharg a2 bsr print_u_ln conv s2:U32 s pusharg s2 bsr print_u_ln conv m2:U32 m pusharg m2 bsr print_u_ln conv d2:U32 d pusharg d2 bsr print_u_ln # conv M2:U32 M # pusharg M2 # bsr print_num_ln pusharg 0:S32 ret
; SPIR-V ; Version: 1.0 ; Generator: Khronos Glslang Reference Front End; 10 ; Bound: 159 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" %30 OpExecutionMode %4 OriginUpperLeft OpSource ESSL 320 OpName %4 "main" OpName %11 "A" OpName %14 "buf0" OpMemberName %14 0 "_GLF_uniform_float_values" OpName %16 "" OpName %30 "_GLF_color" OpName %42 "i" OpName %50 "buf2" OpMemberName %50 0 "injectionSwitch" OpName %52 "" OpName %62 "j" OpName %82 "buf1" OpMemberName %82 0 "_GLF_uniform_int_values" OpName %84 "" OpName %101 "indexable" OpDecorate %13 ArrayStride 16 OpMemberDecorate %14 0 Offset 0 OpDecorate %14 Block OpDecorate %16 DescriptorSet 0 OpDecorate %16 Binding 0 OpDecorate %30 Location 0 OpMemberDecorate %50 0 Offset 0 OpDecorate %50 Block OpDecorate %52 DescriptorSet 0 OpDecorate %52 Binding 2 OpDecorate %81 ArrayStride 16 OpMemberDecorate %82 0 Offset 0 OpDecorate %82 Block OpDecorate %84 DescriptorSet 0 OpDecorate %84 Binding 1 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeFloat 32 %7 = OpTypeInt 32 0 %8 = OpConstant %7 3 %9 = OpTypeArray %6 %8 %10 = OpTypePointer Function %9 %12 = OpConstant %7 4 %13 = OpTypeArray %6 %12 %14 = OpTypeStruct %13 %15 = OpTypePointer Uniform %14 %16 = OpVariable %15 Uniform %17 = OpTypeInt 32 1 %18 = OpConstant %17 0 %19 = OpConstant %17 1 %20 = OpTypePointer Uniform %6 %28 = OpTypeVector %6 4 %29 = OpTypePointer Output %28 %30 = OpVariable %29 Output %31 = OpConstant %17 2 %41 = OpTypePointer Function %17 %43 = OpConstant %17 -1 %49 = OpTypeVector %6 2 %50 = OpTypeStruct %49 %51 = OpTypePointer Uniform %50 %52 = OpVariable %51 Uniform %53 = OpConstant %7 0 %57 = OpTypeBool %63 = OpConstant %7 1 %81 = OpTypeArray %17 %12 %82 = OpTypeStruct %81 %83 = OpTypePointer Uniform %82 %84 = OpVariable %83 Uniform %85 = OpTypePointer Uniform %17 %102 = OpTypePointer Function %6 %114 = OpConstant %17 50 %120 = OpConstant %17 3 %4 = OpFunction %2 None %3 %5 = OpLabel %11 = OpVariable %10 Function %42 = OpVariable %41 Function %62 = OpVariable %41 Function %101 = OpVariable %10 Function %21 = OpAccessChain %20 %16 %18 %19 %22 = OpLoad %6 %21 %23 = OpAccessChain %20 %16 %18 %19 %24 = OpLoad %6 %23 %25 = OpAccessChain %20 %16 %18 %19 %26 = OpLoad %6 %25 %27 = OpCompositeConstruct %9 %22 %24 %26 OpStore %11 %27 %32 = OpAccessChain %20 %16 %18 %31 %33 = OpLoad %6 %32 %34 = OpAccessChain %20 %16 %18 %19 %35 = OpLoad %6 %34 %36 = OpAccessChain %20 %16 %18 %19 %37 = OpLoad %6 %36 %38 = OpAccessChain %20 %16 %18 %19 %39 = OpLoad %6 %38 %40 = OpCompositeConstruct %28 %33 %35 %37 %39 OpStore %30 %40 OpStore %42 %43 OpBranch %44 %44 = OpLabel OpLoopMerge %46 %47 None OpBranch %45 %45 = OpLabel %48 = OpLoad %17 %42 %54 = OpAccessChain %20 %52 %18 %53 %55 = OpLoad %6 %54 %56 = OpConvertFToS %17 %55 %58 = OpSGreaterThan %57 %48 %56 OpSelectionMerge %60 None OpBranchConditional %58 %59 %60 %59 = OpLabel OpBranch %46 %60 = OpLabel %64 = OpAccessChain %20 %52 %18 %63 %65 = OpLoad %6 %64 %66 = OpConvertFToS %17 %65 OpStore %62 %66 OpBranch %67 %67 = OpLabel OpLoopMerge %69 %70 None OpBranch %71 %71 = OpLabel %72 = OpLoad %17 %62 %73 = OpSGreaterThan %57 %72 %18 OpBranchConditional %73 %68 %69 %68 = OpLabel %74 = OpAccessChain %20 %52 %18 %63 %75 = OpLoad %6 %74 %76 = OpAccessChain %20 %16 %18 %18 %77 = OpLoad %6 %76 %78 = OpFOrdGreaterThan %57 %75 %77 OpSelectionMerge %80 None OpBranchConditional %78 %79 %80 %79 = OpLabel %86 = OpAccessChain %85 %84 %18 %18 %87 = OpLoad %17 %86 %88 = OpConvertSToF %6 %87 %89 = OpCompositeConstruct %28 %88 %88 %88 %88 OpStore %30 %89 OpBranch %80 %80 = OpLabel %90 = OpLoad %17 %42 %91 = OpExtInst %17 %1 SClamp %90 %18 %31 %92 = OpAccessChain %20 %16 %18 %19 %93 = OpLoad %6 %92 %94 = OpAccessChain %20 %16 %18 %19 %95 = OpLoad %6 %94 %96 = OpAccessChain %20 %16 %18 %19 %97 = OpLoad %6 %96 %98 = OpCompositeConstruct %9 %93 %95 %97 %99 = OpLoad %17 %42 %100 = OpExtInst %17 %1 SClamp %99 %18 %31 OpStore %101 %98 %103 = OpAccessChain %102 %101 %100 %104 = OpLoad %6 %103 %105 = OpAccessChain %102 %11 %91 %106 = OpLoad %6 %105 %107 = OpFAdd %6 %106 %104 %108 = OpAccessChain %102 %11 %91 OpStore %108 %107 OpBranch %70 %70 = OpLabel %109 = OpLoad %17 %62 %110 = OpISub %17 %109 %19 OpStore %62 %110 OpBranch %67 %69 = OpLabel %111 = OpLoad %17 %42 %112 = OpIAdd %17 %111 %19 OpStore %42 %112 OpBranch %47 %47 = OpLabel %113 = OpLoad %17 %42 %115 = OpSLessThan %57 %113 %114 OpBranchConditional %115 %44 %46 %46 = OpLabel %116 = OpAccessChain %85 %84 %18 %18 %117 = OpLoad %17 %116 %118 = OpAccessChain %102 %11 %117 %119 = OpLoad %6 %118 %121 = OpAccessChain %20 %16 %18 %120 %122 = OpLoad %6 %121 %123 = OpFOrdEqual %57 %119 %122 OpSelectionMerge %125 None OpBranchConditional %123 %124 %125 %124 = OpLabel %126 = OpAccessChain %85 %84 %18 %19 %127 = OpLoad %17 %126 %128 = OpAccessChain %102 %11 %127 %129 = OpLoad %6 %128 %130 = OpAccessChain %20 %16 %18 %19 %131 = OpLoad %6 %130 %132 = OpFOrdEqual %57 %129 %131 OpBranch %125 %125 = OpLabel %133 = OpPhi %57 %123 %46 %132 %124 OpSelectionMerge %135 None OpBranchConditional %133 %134 %135 %134 = OpLabel %136 = OpAccessChain %85 %84 %18 %120 %137 = OpLoad %17 %136 %138 = OpAccessChain %102 %11 %137 %139 = OpLoad %6 %138 %140 = OpAccessChain %20 %16 %18 %19 %141 = OpLoad %6 %140 %142 = OpFOrdEqual %57 %139 %141 OpBranch %135 %135 = OpLabel %143 = OpPhi %57 %133 %125 %142 %134 OpSelectionMerge %145 None OpBranchConditional %143 %144 %145 %144 = OpLabel %146 = OpAccessChain %85 %84 %18 %19 %147 = OpLoad %17 %146 %148 = OpConvertSToF %6 %147 %149 = OpAccessChain %85 %84 %18 %18 %150 = OpLoad %17 %149 %151 = OpConvertSToF %6 %150 %152 = OpAccessChain %85 %84 %18 %18 %153 = OpLoad %17 %152 %154 = OpConvertSToF %6 %153 %155 = OpAccessChain %85 %84 %18 %19 %156 = OpLoad %17 %155 %157 = OpConvertSToF %6 %156 %158 = OpCompositeConstruct %28 %148 %151 %154 %157 OpStore %30 %158 OpBranch %145 %145 = OpLabel OpReturn OpFunctionEnd
;***************************************************** ; ; Video Technology library for small C compiler ; ; Juergen Buchmueller ; ;***************************************************** ; ----- void __FASTCALL__ vz_mode(int n) XLIB vz_mode .vz_mode ld a,h or l ld hl,$783b ld a,(hl) jr nz, mode1 .mode0 and $f7 ; res 3,a ld (hl),a ld ($6800),a ld ($783b),a jp $01c9 ; cls .mode1 or $08 ; set 3,a ld (hl),a ld ($6800),a ld ($783b),a ld hl,$7000 ld de,$7001 ld bc,$7ff ld (hl),0 ldir ret
; A158689: a(n) = 66*n^2 + 1. ; 1,67,265,595,1057,1651,2377,3235,4225,5347,6601,7987,9505,11155,12937,14851,16897,19075,21385,23827,26401,29107,31945,34915,38017,41251,44617,48115,51745,55507,59401,63427,67585,71875,76297,80851,85537,90355,95305,100387,105601,110947,116425,122035,127777,133651,139657,145795,152065,158467,165001,171667,178465,185395,192457,199651,206977,214435,222025,229747,237601,245587,253705,261955,270337,278851,287497,296275,305185,314227,323401,332707,342145,351715,361417,371251,381217,391315,401545 pow $0,2 mul $0,66 add $0,1
; A171479: a(n) = 6*a(n-1)-8*a(n-2)+3 for n > 1; a(0) = 1, a(1) = 8. ; 1,8,43,197,841,3473,14113,56897,228481,915713,3666433,14672897,58705921,234852353,939466753,3757981697,15032156161,60129083393,240517251073,962070839297,3848287027201,15393155448833,61572636475393,246290575261697,985162359767041,3940649556508673,15762598460915713,63050394313424897,252201578193223681,1008806314651942913,4035225262365868033,16140901056979664897,64563604242951045121,258254417001868951553,1033017668067605348353,4132070672390680477697,16528282689803240079361,66113130759693996654593 mov $1,2 pow $1,$0 bin $1,2 mul $1,7 add $1,1 mov $0,$1
; A083593: Expansion of 1/((1-2*x)*(1-x^4)). ; 1,2,4,8,17,34,68,136,273,546,1092,2184,4369,8738,17476,34952,69905,139810,279620,559240,1118481,2236962,4473924,8947848,17895697,35791394,71582788,143165576,286331153,572662306,1145324612,2290649224,4581298449,9162596898,18325193796,36650387592,73300775185,146601550370,293203100740,586406201480,1172812402961,2345624805922,4691249611844,9382499223688,18764998447377,37529996894754,75059993789508,150119987579016,300239975158033,600479950316066,1200959900632132,2401919801264264,4803839602528529 mov $1,2 pow $1,$0 mul $1,32 div $1,30
#include "../csg/csg.hpp"
/*! * \copy * Copyright (c) 2009-2013, Cisco Systems * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * \file WelsThreadLib.c * * \brief Interfaces introduced in thread programming * * \date 11/17/2009 Created * ************************************************************************************* */ #ifdef __linux__ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <sched.h> #elif !defined(_WIN32) #include <sys/types.h> #include <sys/sysctl.h> #include <sys/param.h> #include <unistd.h> #ifdef __APPLE__ #define HW_NCPU_NAME "hw.logicalcpu" #else #define HW_NCPU_NAME "hw.ncpu" #endif #endif #ifdef ANDROID_NDK #include <cpu-features.h> #endif #include "WelsThreadLib.h" #include <stdio.h> #include <stdlib.h> #ifdef _WIN32 #ifdef WINAPI_FAMILY #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) using namespace Platform; using namespace Windows::Foundation; using namespace Windows::System::Threading; #define USE_THREADPOOL #define InitializeCriticalSection(x) InitializeCriticalSectionEx(x, 0, 0) #define GetSystemInfo(x) GetNativeSystemInfo(x) #define CreateEvent(attr, reset, init, name) CreateEventEx(attr, name, ((reset) ? CREATE_EVENT_MANUAL_RESET : 0) | ((init) ? CREATE_EVENT_INITIAL_SET : 0), EVENT_ALL_ACCESS) #define WaitForSingleObject(a, b) WaitForSingleObjectEx(a, b, FALSE) #define WaitForMultipleObjects(a, b, c, d) WaitForMultipleObjectsEx(a, b, c, d, FALSE) #endif #endif WELS_THREAD_ERROR_CODE WelsMutexInit (WELS_MUTEX* mutex) { InitializeCriticalSection (mutex); return WELS_THREAD_ERROR_OK; } WELS_THREAD_ERROR_CODE WelsMutexLock (WELS_MUTEX* mutex) { EnterCriticalSection (mutex); return WELS_THREAD_ERROR_OK; } WELS_THREAD_ERROR_CODE WelsMutexUnlock (WELS_MUTEX* mutex) { LeaveCriticalSection (mutex); return WELS_THREAD_ERROR_OK; } WELS_THREAD_ERROR_CODE WelsMutexDestroy (WELS_MUTEX* mutex) { DeleteCriticalSection (mutex); return WELS_THREAD_ERROR_OK; } #else /* _WIN32 */ WELS_THREAD_ERROR_CODE WelsMutexInit (WELS_MUTEX* mutex) { return pthread_mutex_init (mutex, NULL); } WELS_THREAD_ERROR_CODE WelsMutexLock (WELS_MUTEX* mutex) { return pthread_mutex_lock (mutex); } WELS_THREAD_ERROR_CODE WelsMutexUnlock (WELS_MUTEX* mutex) { return pthread_mutex_unlock (mutex); } WELS_THREAD_ERROR_CODE WelsMutexDestroy (WELS_MUTEX* mutex) { return pthread_mutex_destroy (mutex); } #endif /* !_WIN32 */ #ifdef _WIN32 WELS_THREAD_ERROR_CODE WelsEventOpen (WELS_EVENT* event, const char* event_name) { WELS_EVENT h = CreateEvent (NULL, FALSE, FALSE, NULL); if (h == NULL) { return WELS_THREAD_ERROR_GENERAL; } *event = h; return WELS_THREAD_ERROR_OK; } WELS_THREAD_ERROR_CODE WelsEventSignal (WELS_EVENT* event) { if (SetEvent (*event)) { return WELS_THREAD_ERROR_OK; } return WELS_THREAD_ERROR_GENERAL; } WELS_THREAD_ERROR_CODE WelsEventWait (WELS_EVENT* event) { return WaitForSingleObject (*event, INFINITE); } WELS_THREAD_ERROR_CODE WelsEventWaitWithTimeOut (WELS_EVENT* event, uint32_t dwMilliseconds) { return WaitForSingleObject (*event, dwMilliseconds); } WELS_THREAD_ERROR_CODE WelsMultipleEventsWaitSingleBlocking (uint32_t nCount, WELS_EVENT* event_list, WELS_EVENT* master_event) { // Don't need/use the master event for anything, since windows has got WaitForMultipleObjects return WaitForMultipleObjects (nCount, event_list, FALSE, INFINITE); } WELS_THREAD_ERROR_CODE WelsMultipleEventsWaitAllBlocking (uint32_t nCount, WELS_EVENT* event_list, WELS_EVENT* master_event) { // Don't need/use the master event for anything, since windows has got WaitForMultipleObjects return WaitForMultipleObjects (nCount, event_list, TRUE, INFINITE); } WELS_THREAD_ERROR_CODE WelsEventClose (WELS_EVENT* event, const char* event_name) { CloseHandle (*event); *event = NULL; return WELS_THREAD_ERROR_OK; } WELS_THREAD_ERROR_CODE WelsThreadCreate (WELS_THREAD_HANDLE* thread, LPWELS_THREAD_ROUTINE routine, void* arg, WELS_THREAD_ATTR attr) { #ifdef USE_THREADPOOL HANDLE h = CreateEvent (NULL, FALSE, FALSE, NULL); HANDLE h2; DuplicateHandle (GetCurrentProcess(), h, GetCurrentProcess(), &h2, 0, FALSE, DUPLICATE_SAME_ACCESS); ThreadPool::RunAsync (ref new WorkItemHandler ([ = ] (IAsyncAction^) { routine (arg); SetEvent (h2); CloseHandle (h2); }, CallbackContext::Any), WorkItemPriority::Normal, WorkItemOptions::TimeSliced); #else WELS_THREAD_HANDLE h = CreateThread (NULL, 0, routine, arg, 0, NULL); #endif if (h == NULL) { return WELS_THREAD_ERROR_GENERAL; } * thread = h; return WELS_THREAD_ERROR_OK; } WELS_THREAD_ERROR_CODE WelsThreadJoin (WELS_THREAD_HANDLE thread) { WaitForSingleObject (thread, INFINITE); CloseHandle (thread); return WELS_THREAD_ERROR_OK; } WELS_THREAD_HANDLE WelsThreadSelf() { return GetCurrentThread(); } WELS_THREAD_ERROR_CODE WelsQueryLogicalProcessInfo (WelsLogicalProcessInfo* pInfo) { SYSTEM_INFO si; GetSystemInfo (&si); pInfo->ProcessorCount = si.dwNumberOfProcessors; return WELS_THREAD_ERROR_OK; } #else WELS_THREAD_ERROR_CODE WelsThreadCreate (WELS_THREAD_HANDLE* thread, LPWELS_THREAD_ROUTINE routine, void* arg, WELS_THREAD_ATTR attr) { WELS_THREAD_ERROR_CODE err = 0; pthread_attr_t at; err = pthread_attr_init (&at); if (err) return err; #ifndef __ANDROID__ err = pthread_attr_setscope (&at, PTHREAD_SCOPE_SYSTEM); if (err) return err; err = pthread_attr_setschedpolicy (&at, SCHED_FIFO); if (err) return err; #endif err = pthread_create (thread, &at, routine, arg); pthread_attr_destroy (&at); return err; } WELS_THREAD_ERROR_CODE WelsThreadJoin (WELS_THREAD_HANDLE thread) { return pthread_join (thread, NULL); } WELS_THREAD_HANDLE WelsThreadSelf() { return pthread_self(); } // unnamed semaphores aren't supported on OS X WELS_THREAD_ERROR_CODE WelsEventOpen (WELS_EVENT* p_event, const char* event_name) { #ifdef __APPLE__ if (p_event == NULL || event_name == NULL) return WELS_THREAD_ERROR_GENERAL; *p_event = sem_open (event_name, O_CREAT, (S_IRUSR | S_IWUSR)/*0600*/, 0); if (*p_event == (sem_t*)SEM_FAILED) { sem_unlink (event_name); *p_event = NULL; return WELS_THREAD_ERROR_GENERAL; } else { return WELS_THREAD_ERROR_OK; } #else WELS_EVENT event = (WELS_EVENT) malloc (sizeof (*event)); if (event == NULL) return WELS_THREAD_ERROR_GENERAL; WELS_THREAD_ERROR_CODE err = sem_init (event, 0, 0); if (!err) { *p_event = event; return err; } free (event); return err; #endif } WELS_THREAD_ERROR_CODE WelsEventClose (WELS_EVENT* event, const char* event_name) { #ifdef __APPLE__ WELS_THREAD_ERROR_CODE err = sem_close (*event); // match with sem_open if (event_name) sem_unlink (event_name); return err; #else WELS_THREAD_ERROR_CODE err = sem_destroy (*event); // match with sem_init free (*event); return err; #endif } WELS_THREAD_ERROR_CODE WelsEventSignal (WELS_EVENT* event) { WELS_THREAD_ERROR_CODE err = 0; // int32_t val = 0; // sem_getvalue(event, &val); // fprintf( stderr, "before signal it, val= %d..\n",val ); err = sem_post (*event); // sem_getvalue(event, &val); // fprintf( stderr, "after signal it, val= %d..\n",val ); return err; } WELS_THREAD_ERROR_CODE WelsEventWait (WELS_EVENT* event) { return sem_wait (*event); // blocking until signaled } WELS_THREAD_ERROR_CODE WelsEventWaitWithTimeOut (WELS_EVENT* event, uint32_t dwMilliseconds) { if (dwMilliseconds != (uint32_t) - 1) { return sem_wait (*event); } else { #if defined(__APPLE__) int32_t err = 0; int32_t wait_count = 0; do { err = sem_trywait (*event); if (WELS_THREAD_ERROR_OK == err) break;// WELS_THREAD_ERROR_OK; else if (wait_count > 0) break; usleep (dwMilliseconds * 1000); ++ wait_count; } while (1); return err; #else struct timespec ts; struct timeval tv; gettimeofday (&tv, 0); ts.tv_nsec = tv.tv_usec * 1000 + dwMilliseconds * 1000000; ts.tv_sec = tv.tv_sec + ts.tv_nsec / 1000000000; ts.tv_nsec %= 1000000000; return sem_timedwait (*event, &ts); #endif//__APPLE__ } } WELS_THREAD_ERROR_CODE WelsMultipleEventsWaitSingleBlocking (uint32_t nCount, WELS_EVENT* event_list, WELS_EVENT* master_event) { uint32_t nIdx = 0; uint32_t uiAccessTime = 2; // 2 us once if (nCount == 0) return WELS_THREAD_ERROR_WAIT_FAILED; if (master_event != NULL) { // This design relies on the events actually being semaphores; // if multiple events in the list have been signalled, the master // event should have a similar count (events in windows can't keep // track of the actual count, but the master event isn't needed there // since it uses WaitForMultipleObjects). int32_t err = sem_wait (*master_event); if (err != WELS_THREAD_ERROR_OK) return err; uiAccessTime = 0; // no blocking, just quickly loop through all to find the one that was signalled } while (1) { nIdx = 0; // access each event by order while (nIdx < nCount) { int32_t err = 0; int32_t wait_count = 0; /* * although such interface is not used in __GNUC__ like platform, to use * pthread_cond_timedwait() might be better choice if need */ do { err = sem_trywait (event_list[nIdx]); if (WELS_THREAD_ERROR_OK == err) return WELS_THREAD_ERROR_WAIT_OBJECT_0 + nIdx; else if (wait_count > 0 || uiAccessTime == 0) break; usleep (uiAccessTime); ++ wait_count; } while (1); // we do need access next event next time ++ nIdx; } usleep (1); // switch to working threads if (master_event != NULL) { // A master event was used and was signalled, but none of the events in the // list was found to be signalled, thus wait a little more when rechecking // the list to avoid busylooping here. // If we ever hit this codepath it's mostly a bug in the code that signals // the events. uiAccessTime = 2; } } return WELS_THREAD_ERROR_WAIT_FAILED; } WELS_THREAD_ERROR_CODE WelsMultipleEventsWaitAllBlocking (uint32_t nCount, WELS_EVENT* event_list, WELS_EVENT* master_event) { uint32_t nIdx = 0; uint32_t uiCountSignals = 0; uint32_t uiSignalFlag = 0; // UGLY: suppose maximal event number up to 32 if (nCount == 0 || nCount > (sizeof (uint32_t) << 3)) return WELS_THREAD_ERROR_WAIT_FAILED; while (1) { nIdx = 0; // access each event by order while (nIdx < nCount) { const uint32_t kuiBitwiseFlag = (1 << nIdx); if ((uiSignalFlag & kuiBitwiseFlag) != kuiBitwiseFlag) { // non-blocking mode int32_t err = 0; // fprintf( stderr, "sem_wait(): start to wait event %d..\n", nIdx ); if (master_event == NULL) { err = sem_wait (event_list[nIdx]); } else { err = sem_wait (*master_event); if (err == WELS_THREAD_ERROR_OK) { err = sem_wait (event_list[nIdx]); if (err != WELS_THREAD_ERROR_OK) { // We successfully waited for the master event, // but waiting for the individual event failed (e.g. EINTR?). // Increase the master event count so that the next retry will // work as intended. sem_post (*master_event); } } } // fprintf( stderr, "sem_wait(): wait event %d result %d errno %d..\n", nIdx, err, errno ); if (WELS_THREAD_ERROR_OK == err) { // int32_t val = 0; // sem_getvalue(&event_list[nIdx], &val); // fprintf( stderr, "after sem_timedwait(), event_list[%d] semaphore value= %d..\n", nIdx, val); uiSignalFlag |= kuiBitwiseFlag; ++ uiCountSignals; if (uiCountSignals >= nCount) { return WELS_THREAD_ERROR_OK; } } } // we do need access next event next time ++ nIdx; } } return WELS_THREAD_ERROR_WAIT_FAILED; } WELS_THREAD_ERROR_CODE WelsQueryLogicalProcessInfo (WelsLogicalProcessInfo* pInfo) { #ifdef ANDROID_NDK pInfo->ProcessorCount = android_getCpuCount(); return WELS_THREAD_ERROR_OK; #elif defined(__linux__) cpu_set_t cpuset; CPU_ZERO (&cpuset); if (!sched_getaffinity (0, sizeof (cpuset), &cpuset)) pInfo->ProcessorCount = CPU_COUNT (&cpuset); else pInfo->ProcessorCount = 1; return WELS_THREAD_ERROR_OK; #else size_t len = sizeof (pInfo->ProcessorCount); if (sysctlbyname (HW_NCPU_NAME, &pInfo->ProcessorCount, &len, NULL, 0) == -1) pInfo->ProcessorCount = 1; return WELS_THREAD_ERROR_OK; #endif//__linux__ } #endif
; A033898: Sort then Add!. ; Submitted by Jon Maiga ; 15,30,33,66,132,255,510,525,780,858,1446,2892,5181,6339,9708,10497,11976,23655,47211,58458,104046,105492,117951,229530,251889,377778,755556,1311123,2422356,4645812,5890380,5926269,8182968,9451857,10907646 mov $1,15 lpb $0 sub $0,1 seq $1,70196 ; a(n)=n plus the sorted version of the base-10 digits of n. lpe mov $0,$1
DATA SEGMENT ;LCD DATA ;variables to keep track of port data LCD_PORTA_VAL DB 0 LCD_PORTB_VAL DB 0 LCD_PORTC_VAL DB 0 ;port addresses LCD_PORTA equ 00001000B LCD_PORTB equ 00001010B LCD_PORTC equ 00001100B LCD_PORTR equ 00001110B ;END LCD DATA ;keypad define KeypadPortA equ 00000000B KeypadPortB equ 00000010B KeypadPortR equ 00000110B CountA equ 5 CountB equ 8 KeypadA DB 00010000B DB 00100000B DB 01000000B DB 00001000B KeypadB DB 00100000B DB 00000001B DB 01000000B DB 00010000B DB 00001000B DB 00000010B DB 00000100B NumA DB 3 DB 6 DB 9 DB 0FH NumB DB 1 DB 2 DB 4 DB 5 DB 7 DB 8 DB 0 ;Password Password equ 1234 StringPasswordInput DB "Enter Password$" StringPasswordCorrect DB "Access Granted$" StringPasswordCorrect2 DB "Lock = 1$" StringPasswordInCorrect DB "Acess Denied$" StringPasswordInCorrect2 DB "Press 1$" PasswordInCorrectCounter DB 0 ;to save number of fault PasswordMAXInCorrect equ 2D ;MAX number of incorrect ;Alarm AlarmPort equ 00000100B StringAlarm DB "LOOK DOWN!$" ENDS STACK SEGMENT DW 128 DUP(0) ENDS ;/////////////////////////////////////////////MAIN Code CODE SEGMENT START: ; set segment registers: MOV AX, DATA MOV DS, AX MOV ES, AX CALL LCD_INIT CALL KeypadInit MainLoop: CALL LCD_CLEAR LEA SI,StringPasswordInput CALL LCD_PRINTSTR CALL KeypadRead ;(AX) CMP AX,Password JE T JMP F T: CALL PasswordCorrect JMP PasswordExit F: CALL PasswordInCorrect CALL AlarmCheck ;(AL) PasswordExit: MOV CX,0FFFFH ;CALL DELAY MOV CX,0FFFFH LOOP MainLoop ExitMain: HLT ;end of main procedure ;/////////////////////////////////////////////END MAIN Code ;//////////////////////////////////////////Password ;handle correct password PasswordCorrect PROC Near PUSH AX PUSH DX PUSH SI MOV PasswordInCorrectCounter, 00H ;set zero incorrect counter CALL LCD_CLEAR LEA SI,StringPasswordCorrect CALL LCD_PRINTSTR MOV DL,2 MOV DH,1 CALL LCD_SET_CUR LEA SI,StringPasswordCorrect2 CALL LCD_PRINTSTR LL: CALL KeypadWaitPress CALL KeypadInput ;(AL) CALL KeypadWaitRelease CMP AL,01D ;wait until press 1 JNE LL POP SI POP DX POP AX RET PasswordCorrect ENDP ;handle incorrect password PasswordInCorrect PROC Near PUSH AX PUSH DX PUSH SI INC PasswordInCorrectCounter ;increase incorrect counter CALL LCD_CLEAR LEA SI,StringPasswordInCorrect CALL LCD_PRINTSTR MOV DL,2 MOV DH,1 CALL LCD_SET_CUR ;in row2 LEA SI,StringPasswordInCorrect2 CALL LCD_PRINTSTR KK: CALL KeypadWaitPress CALL KeypadInput ;(AL) CALL KeypadWaitRelease CMP AL,01D ;wait until press 1 JNE KK POP SI POP DX POP AX RET PasswordInCorrect ENDP ;//////////////////////////////////////////Alarm ;return (AL=1,AL=0):::(1:Alarm Active> AlarmCheck PROC Near PUSH AX CMP PasswordInCorrectCounter,PasswordMAXInCorrect JB AlarmExit CALL LCD_CLEAR LEA SI,StringAlarm CALL LCD_PRINTSTR MOV AL,01H AlarmLoop: OUT AlarmPort,AL NOT AL MOV CX,10000D CALL DELAY JMP AlarmLoop RET ;return with AL=1 AlarmExit: POP AX MOV AL,00H ;return AL=0 RET AlarmCheck ENDP ;//////////////////////////////////////////Keypad KeypadInit PROC Near PUSH AX PUSH DX MOV AL,10010010B MOV DX,KeypadPortR OUT DX,AL POP DX POP AX RET KeypadInit ENDP ;for read a complete number ;stop reading with enter(0X0F) ;return AX KeypadRead PROC Near PUSH BX PUSH CX PUSH DX MOV AX,0000H ;save temp MOV DL,1 MOV DH,5 CALL LCD_SET_CUR LoopRead: PUSH AX ;save number CALL KeypadWaitPress CALL KeypadInput ;AL CALL KeypadWaitRelease CMP AL,0FH JE KeypadReadExit MOV CX,0000H MOV CL,AL ;CL=input POP AX ;reload number MOV BX,10D MUL BX ;in (DX,AX) ;MOV AX,DX ;in AX MOV DH,00H ADD AX,CX ;add input in main CALL LCD_CLEAR CALL PrintBin JMP LoopRead KeypadReadExit: POP AX ;reload number POP DX POP CX POP BX RET KeypadRead ENDP ;find press key and return ;<AL> unless return (AL=0XFF) KeypadInput PROC Near PUSH AX PUSH BX IN AL,KeypadPortB ;Read B MOV AH,AL ;AH=B,AL=A IN AL,KeypadPortA ;Read A CMP AL,0FFH ;check key in A JNE CheckA ;go find in A CMP AH,0FFH ;check key in B JNE CheckB ;go find in B JMP NotFind ;no key not press CheckA: MOV CX,CountA MOV SI,00H LoopA: MOV BL,KeypadA[SI] ;check in array TEST AL,BL JZ FindKeyA INC SI ;not find go next LOOP LoopA JMP NotFind ;not find CheckB: MOV CX,CountB MOV SI,00H LoopB: MOV BL,KeypadB[SI] TEST AH,BL JZ FindKeyB INC SI LOOP LoopB JMP NotFind ;not find FindKeyA: POP AX MOV AL,NumA[SI] JMP ReadKeypadExit FindKeyB: POP AX MOV AL,NumB[SI] JMP ReadKeypadExit NotFind: POP AX MOV AL,0FFH JMP ReadKeypadExit ReadKeypadExit: POP BX RET KeypadInput ENDP ;wait until press a key of keypad KeypadWaitPress PROC Near PUSH AX CC: IN AL,KeypadPortB ;read portB MOV AH,AL ;AH=PortB, AL=PortA IN AL,KeypadPortA ;read portA AND AL,AH CMP AL,0FFH JE CC POP AX RET KeypadWaitPress ENDP ; wait until press key release KeypadWaitRelease PROC Near PUSH AX AA: IN AL,KeypadPortA CMP AL,0FFH JNE AA BB: IN AL,KeypadPortB CMP AL,0FFH JNE BB POP AX RET KeypadWaitRelease ENDP ;//////////////////////////////////////////Print ;AX as input(max 16bit) ;note: save the CX,SI,DX,AX PrintBin proc PUSH AX PUSH CX PUSH DX PUSH SI mov cx,5 mov si,10D DivTo10: mov dx,0000H div si ;remain in dx push dx ;push to save digits loop DivTo10 mov cx,5 ;print counter Print: POP AX ;pop to load digits add AX,30H ;change to ASCII MOV AH,AL PUSH CX CALL LCD_WRITE_CHAR POP CX LOOP Print ;loop until end counter(cx) ;pop POP SI POP DX POP CX POP AX Ret PrintBin ENDP ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; ; LCD function library.(CORE) ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PROC DELAY ;input: CX, this value controls the delay. CX=50 means 1ms ;output: none JCXZ @DELAY_END @DEL_LOOP: LOOP @DEL_LOOP @DELAY_END: RET ENDP DELAY ; LCD initialization PROC LCD_INIT ;input: none ;output: none PUSH AX PUSH CX PUSH DX MOV DX,LCD_PORTR MOV AL,80H OUT DX,AL ;make RS=En=RW=0 MOV AL,0 CALL OUT_B ;delay 20ms MOV CX,1000 CALL DELAY ;reset sequence MOV AH,30H CALL LCD_CMD MOV CX,250 CALL DELAY MOV AH,30H CALL LCD_CMD MOV CX,50 CALL DELAY MOV AH,30H CALL LCD_CMD MOV CX,500 CALL DELAY ;function set MOV AH,38H CALL LCD_CMD MOV AH,0CH CALL LCD_CMD MOV AH,01H CALL LCD_CMD MOV AH,06H CALL LCD_CMD POP DX POP CX POP AX RET ENDP LCD_INIT ;sends commands to LCD PROC LCD_CMD ;input: AH = command code ;output: none ;save registers PUSH CX PUSH AX ;make rs=0 MOV AL,LCD_PORTB_VAL AND AL,0FDH ;En-RS-RW CALL OUT_B ;set out data pins MOV AL,AH CALL OUT_A ;make En=1 MOV AL,LCD_PORTB_VAL OR AL,100B ;En-RS-RW CALL OUT_B ;delay 1ms MOV CX,50 CALL DELAY ;make En=0 MOV AL,LCD_PORTB_VAL AND AL,0FBH ;En-RS-RW CALL OUT_B ;delay 1ms MOV CX,50 CALL DELAY ;restore registers POP AX POP CX RET ENDP LCD_CMD PROC LCD_CLEAR PUSH AX MOV AH,1 CALL LCD_CMD POP AX RET ENDP LCD_CLEAR ;writes a character on current cursor position PROC LCD_WRITE_CHAR ;input: AH ;output: none ;save registers PUSH AX PUSH CX ;set RS=1 MOV AL,LCD_PORTB_VAL OR AL,10B ;EN-RS-RW CALL OUT_B ;set out the data pins MOV AL,AH CALL OUT_A ;set En=1 MOV AL,LCD_PORTB_VAL OR AL,100B ;EN-RS-RW CALL OUT_B ;delay 1ms MOV CX,50 CALL DELAY ;set En=0 MOV AL,LCD_PORTB_VAL AND AL,0FBH ;EN-RS-RW CALL OUT_B ;return POP CX POP AX RET ENDP LCD_WRITE_CHAR ;prints a string on current cursor position PROC LCD_PRINTSTR ;input: SI=string address, string should end with '$' ;output: none ;save registers PUSH SI PUSH AX ;read and write character @LCD_PRINTSTR_LT: LODSB CMP AL,'$' JE @LCD_PRINTSTR_EXIT MOV AH,AL CALL LCD_WRITE_CHAR JMP @LCD_PRINTSTR_LT ;return @LCD_PRINTSTR_EXIT: POP AX POP SI RET ENDP LCD_PRINTSTR ;sets the cursor PROC LCD_SET_CUR ;input: DL=ROW, DH=COL ; DL = 1, means upper row ; DL = 2, means lower row ; DH = 1-8, 1st column is 1 ;output: none ;save registers PUSH AX PUSH DX ;LCD uses 0 based column index DEC DH ;select case CMP DL,1 JE @ROW1 CMP DL,2 JE @ROW2 JMP @LCD_SET_CUR_END ;if DL==1 then @ROW1: MOV AH,80H JMP @LCD_SET_CUR_ENDCASE ;if DL==2 then @ROW2: MOV AH,0C0H JMP @LCD_SET_CUR_ENDCASE ;execute the command @LCD_SET_CUR_ENDCASE: ADD AH,DH CALL LCD_CMD ;exit from procedure @LCD_SET_CUR_END: POP DX POP AX RET ENDP LCD_SET_CUR PROC LCD_SHOW_CUR ;input: none ;output: none PUSH AX MOV AH,0FH CALL LCD_CMD POP AX RET ENDP LCD_SHOW_CUR PROC LCD_HIDE_CUR ;input: none ;output: none PUSH AX MOV AH,0CH CALL LCD_CMD POP AX RET ENDP LCD_HIDE_CUR ;sends data to output port and saves them in a variable PROC OUT_A ;input: AL ;output: LCD_LCD_PORTA_VAL PUSH DX MOV DX,LCD_PORTA OUT DX,AL MOV LCD_PORTA_VAL,AL POP DX RET ENDP OUT_A PROC OUT_B ;input: AL ;output: LCD_PORTB_VAL PUSH DX MOV DX,LCD_PORTB OUT DX,AL MOV LCD_PORTB_VAL,AL POP DX RET ENDP OUT_B PROC OUT_C ;input: AL ;output: LCD_LCD_PORTC_VAL PUSH DX MOV DX,LCD_PORTC OUT DX,AL MOV LCD_PORTC_VAL,AL POP DX RET ENDP OUT_C CODE ENDS ;end of CODE segment END START ; set entry point and stop the assembler.
Route4Script: call EnableAutoTextBoxDrawing ld hl, Route4TrainerHeader0 ld de, Route4ScriptPointers ld a, [wRoute4CurScript] call ExecuteCurMapScriptInTable ld [wRoute4CurScript], a ret Route4ScriptPointers: dw CheckFightingMapTrainers dw DisplayEnemyTrainerTextAndStartBattle dw EndTrainerBattle Route4TextPointers: dw Route4Text1 dw Route4Text2 dw PickUpItemText dw PokeCenterSignText dw Route4Text5 dw Route4Text6 Route4TrainerHeader0: dbEventFlagBit EVENT_BEAT_ROUTE_4_TRAINER_0 db ($3 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_ROUTE_4_TRAINER_0 dw Route4BattleText1 ; TextBeforeBattle dw Route4AfterBattleText1 ; TextAfterBattle dw Route4EndBattleText1 ; TextEndBattle dw Route4EndBattleText1 ; TextEndBattle db $ff Route4Text1: TX_FAR _Route4Text1 db "@" Route4Text2: TX_ASM ld hl, Route4TrainerHeader0 call TalkToTrainer jp TextScriptEnd Route4BattleText1: TX_FAR _Route4BattleText1 db "@" Route4EndBattleText1: TX_FAR _Route4EndBattleText1 db "@" Route4AfterBattleText1: TX_FAR _Route4AfterBattleText1 db "@" Route4Text5: TX_FAR _Route4Text5 db "@" Route4Text6: TX_FAR _Route4Text6 db "@"
#include <bits/stdc++.h> #define INF 999999999 using namespace std; inline long long read() { long long x = 0; int f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * f; } void write(const long long &x) { if (!x) { putchar('0'); return; } char f[100]; long long tmp = x; if (tmp < 0) { tmp = -tmp; putchar('-'); } long long s = 0; while (tmp > 0) { f[s++] = tmp % 10 + '0'; tmp /= 10; } while (s > 0) { putchar(f[--s]); } } inline double dread() { double r; double x = 0, t = 0; int s = 0, f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') { f = -1; } if (c == '.') { goto readt; } } for (; isdigit(c) && c != '.'; c = getchar()) { x = x * 10 + c - '0'; } readt: for (; c == '.'; c = getchar()) ; for (; isdigit(c); c = getchar()) { t = t * 10 + c - '0'; ++s; } r = (x + t / pow(10, s)) * f; return r; } inline void dwrite(long long x) { if (x == 0) { putchar(48); return; } int bit[20], p = 0, i; for (; x; x /= 10) bit[++p] = x % 10; for (i = p; i > 0; --i) putchar(bit[i] + 48); } inline void write(double x, int k) { static int n = pow(10, k); if (x == 0) { putchar('0'); putchar('.'); for (int i = 1; i <= k; ++i) putchar('0'); return; } if (x < 0) putchar('-'), x = -x; long long y = (long long)(x * n) % n; x = (long long)x; dwrite(x), putchar('.'); int bit[10], p = 0, i; for (; p < k; y /= 10) bit[++p] = y % 10; for (i = p; i > 0; i--) putchar(bit[i] + 48); } int totN; int nums[1090]; int as[1090], bs[1090], cs[1090]; string str01, str02, str03; int charID(char x) { return x - 'A'; } bool check() { int A, B, C; for (int i = totN - 1, x = 0; i >= 1; i--) { A = nums[as[i]]; B = nums[bs[i]]; C = nums[cs[i]]; if ((A + B + x) % totN != C) { return false; } x=(A + B + x) / totN; } } bool Prune() { if(nums[as[0]]+nums[bs[0]]>totN) { return true; } } void DFS() { } int main() { totN = read(); for (int i = 1; i <= totN; ++i) { as[i] = charID(getchar()); } for (int i = 1; i <= totN; ++i) { bs[i] = charID(getchar()); } for (int i = 1; i <= totN; ++i) { cs[i] = charID(getchar()); } return 0; } //Thomitics Code
;BUNNY MAP FIX (J) ; ;This is a repair so that the bunny is on the correct palette when going ; to and from the world map (otherwise, it goes to Link's mail palette, ; and the flesh colors replace some of the pink) ;This bug is much more noticable with custom player sprites, and so this ; fix should address the issues that sprite artists have been having in ; this regard ;This fix will not work for non-J versions. For some reason, the relevant ; subroutine seems much different in the other ROMs. ; ;Written by Artheau ; while sitting in an uncomfortable chair ; on Jul. 1, 2019 ; ;THE PROBLEM ; ;This is a snippet of the relevant code that is causing the problem ; ;;;; starting at $02:fdf0 (main subroutine begins at $02:fd6d) ; .loop ; lda [$00] ; sta $7ec300, x <-- this is the problem ; sta $7ec500, x ; inc $00 ; inc $00 ; inx ; inx ; dey ; bpl .loop ; rts ;THE FIX ; ;$7ec300 is supposed to be the palette cache. The bug is that instead ; of caching the correct palette, the bugged code is just overwriting ; the cache. So, we need to make it actually caches the palette. ;There is code already present elsewhere which pulls the palettes from ; the cache afterwards, so we do not need to concern ourselves with ; such matters. CachePalettesBeforeMapLoad: .loop lda $7ec500,x ;load up current palette sta $7ec300,X ;cache the palette correctly lda [$00] ;load the map palette sta $7ec500,x ;store the map palette inc $00 inc $00 ;next color in memory inx inx ;next color index dey ;decrease loop counter bpl .loop ;loop over all the colors rtl ;GET OUT ;================================================================================ ; THIS BLOCK WAS PLACED IN HOOKS.ASM: Bunny Palette/Overworld Map Bugfix ;-------------------------------------------------------------------------------- ;org $02fdf0 ; <- Not present in (U) disassembly. Consult bunnymapfix.asm for details ;JSL CachePalettesBeforeMapLoad ;RTS ;================================================================================
; Verifies ASL .segment "VECTORS" .word $eaea .word init .word $eaea .segment "ZEROPAGE" zp: .byte %00100000 .byte %00100000 .code init: asl ; A will be %00100000 asl ; A will be %01000000 from last instruction asl ; A will be %10000000 from last instruction asl zp asl zp,x ; X will be $01 asl data asl data,x ; X will be $01 .segment "DATA" data: .byte %00100000 .byte %00100000
_rm: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 57 push %edi e: 56 push %esi f: 53 push %ebx 10: 51 push %ecx 11: bf 01 00 00 00 mov $0x1,%edi 16: 83 ec 08 sub $0x8,%esp 19: 8b 31 mov (%ecx),%esi 1b: 8b 59 04 mov 0x4(%ecx),%ebx 1e: 83 c3 04 add $0x4,%ebx int i; if(argc < 2){ 21: 83 fe 01 cmp $0x1,%esi 24: 7e 43 jle 69 <main+0x69> 26: 8d 76 00 lea 0x0(%esi),%esi 29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi printf(2, "Usage: rm files...\n"); exit(0); } for(i = 1; i < argc; i++){ if(unlink(argv[i]) < 0){ 30: 83 ec 0c sub $0xc,%esp 33: ff 33 pushl (%ebx) 35: e8 f8 02 00 00 call 332 <unlink> 3a: 83 c4 10 add $0x10,%esp 3d: 85 c0 test %eax,%eax 3f: 78 14 js 55 <main+0x55> for(i = 1; i < argc; i++){ 41: 83 c7 01 add $0x1,%edi 44: 83 c3 04 add $0x4,%ebx 47: 39 fe cmp %edi,%esi 49: 75 e5 jne 30 <main+0x30> printf(2, "rm: %s failed to delete\n", argv[i]); break; } } exit(0); 4b: 83 ec 0c sub $0xc,%esp 4e: 6a 00 push $0x0 50: e8 8d 02 00 00 call 2e2 <exit> printf(2, "rm: %s failed to delete\n", argv[i]); 55: 50 push %eax 56: ff 33 pushl (%ebx) 58: 68 bc 07 00 00 push $0x7bc 5d: 6a 02 push $0x2 5f: e8 ec 03 00 00 call 450 <printf> break; 64: 83 c4 10 add $0x10,%esp 67: eb e2 jmp 4b <main+0x4b> printf(2, "Usage: rm files...\n"); 69: 52 push %edx 6a: 52 push %edx 6b: 68 a8 07 00 00 push $0x7a8 70: 6a 02 push $0x2 72: e8 d9 03 00 00 call 450 <printf> exit(0); 77: c7 04 24 00 00 00 00 movl $0x0,(%esp) 7e: e8 5f 02 00 00 call 2e2 <exit> 83: 66 90 xchg %ax,%ax 85: 66 90 xchg %ax,%ax 87: 66 90 xchg %ax,%ax 89: 66 90 xchg %ax,%ax 8b: 66 90 xchg %ax,%ax 8d: 66 90 xchg %ax,%ax 8f: 90 nop 00000090 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 90: 55 push %ebp 91: 89 e5 mov %esp,%ebp 93: 53 push %ebx 94: 8b 45 08 mov 0x8(%ebp),%eax 97: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 9a: 89 c2 mov %eax,%edx 9c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi a0: 83 c1 01 add $0x1,%ecx a3: 0f b6 59 ff movzbl -0x1(%ecx),%ebx a7: 83 c2 01 add $0x1,%edx aa: 84 db test %bl,%bl ac: 88 5a ff mov %bl,-0x1(%edx) af: 75 ef jne a0 <strcpy+0x10> ; return os; } b1: 5b pop %ebx b2: 5d pop %ebp b3: c3 ret b4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi ba: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000c0 <strcmp>: int strcmp(const char *p, const char *q) { c0: 55 push %ebp c1: 89 e5 mov %esp,%ebp c3: 53 push %ebx c4: 8b 55 08 mov 0x8(%ebp),%edx c7: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) ca: 0f b6 02 movzbl (%edx),%eax cd: 0f b6 19 movzbl (%ecx),%ebx d0: 84 c0 test %al,%al d2: 75 1c jne f0 <strcmp+0x30> d4: eb 2a jmp 100 <strcmp+0x40> d6: 8d 76 00 lea 0x0(%esi),%esi d9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; e0: 83 c2 01 add $0x1,%edx while(*p && *p == *q) e3: 0f b6 02 movzbl (%edx),%eax p++, q++; e6: 83 c1 01 add $0x1,%ecx e9: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) ec: 84 c0 test %al,%al ee: 74 10 je 100 <strcmp+0x40> f0: 38 d8 cmp %bl,%al f2: 74 ec je e0 <strcmp+0x20> return (uchar)*p - (uchar)*q; f4: 29 d8 sub %ebx,%eax } f6: 5b pop %ebx f7: 5d pop %ebp f8: c3 ret f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 100: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 102: 29 d8 sub %ebx,%eax } 104: 5b pop %ebx 105: 5d pop %ebp 106: c3 ret 107: 89 f6 mov %esi,%esi 109: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000110 <strlen>: uint strlen(const char *s) { 110: 55 push %ebp 111: 89 e5 mov %esp,%ebp 113: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 116: 80 39 00 cmpb $0x0,(%ecx) 119: 74 15 je 130 <strlen+0x20> 11b: 31 d2 xor %edx,%edx 11d: 8d 76 00 lea 0x0(%esi),%esi 120: 83 c2 01 add $0x1,%edx 123: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 127: 89 d0 mov %edx,%eax 129: 75 f5 jne 120 <strlen+0x10> ; return n; } 12b: 5d pop %ebp 12c: c3 ret 12d: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) 130: 31 c0 xor %eax,%eax } 132: 5d pop %ebp 133: c3 ret 134: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 13a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000140 <memset>: void* memset(void *dst, int c, uint n) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 57 push %edi 144: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 147: 8b 4d 10 mov 0x10(%ebp),%ecx 14a: 8b 45 0c mov 0xc(%ebp),%eax 14d: 89 d7 mov %edx,%edi 14f: fc cld 150: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 152: 89 d0 mov %edx,%eax 154: 5f pop %edi 155: 5d pop %ebp 156: c3 ret 157: 89 f6 mov %esi,%esi 159: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000160 <strchr>: char* strchr(const char *s, char c) { 160: 55 push %ebp 161: 89 e5 mov %esp,%ebp 163: 53 push %ebx 164: 8b 45 08 mov 0x8(%ebp),%eax 167: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 16a: 0f b6 10 movzbl (%eax),%edx 16d: 84 d2 test %dl,%dl 16f: 74 1d je 18e <strchr+0x2e> if(*s == c) 171: 38 d3 cmp %dl,%bl 173: 89 d9 mov %ebx,%ecx 175: 75 0d jne 184 <strchr+0x24> 177: eb 17 jmp 190 <strchr+0x30> 179: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 180: 38 ca cmp %cl,%dl 182: 74 0c je 190 <strchr+0x30> for(; *s; s++) 184: 83 c0 01 add $0x1,%eax 187: 0f b6 10 movzbl (%eax),%edx 18a: 84 d2 test %dl,%dl 18c: 75 f2 jne 180 <strchr+0x20> return (char*)s; return 0; 18e: 31 c0 xor %eax,%eax } 190: 5b pop %ebx 191: 5d pop %ebp 192: c3 ret 193: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 199: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001a0 <gets>: char* gets(char *buf, int max) { 1a0: 55 push %ebp 1a1: 89 e5 mov %esp,%ebp 1a3: 57 push %edi 1a4: 56 push %esi 1a5: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 1a6: 31 f6 xor %esi,%esi 1a8: 89 f3 mov %esi,%ebx { 1aa: 83 ec 1c sub $0x1c,%esp 1ad: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 1b0: eb 2f jmp 1e1 <gets+0x41> 1b2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 1b8: 8d 45 e7 lea -0x19(%ebp),%eax 1bb: 83 ec 04 sub $0x4,%esp 1be: 6a 01 push $0x1 1c0: 50 push %eax 1c1: 6a 00 push $0x0 1c3: e8 32 01 00 00 call 2fa <read> if(cc < 1) 1c8: 83 c4 10 add $0x10,%esp 1cb: 85 c0 test %eax,%eax 1cd: 7e 1c jle 1eb <gets+0x4b> break; buf[i++] = c; 1cf: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 1d3: 83 c7 01 add $0x1,%edi 1d6: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 1d9: 3c 0a cmp $0xa,%al 1db: 74 23 je 200 <gets+0x60> 1dd: 3c 0d cmp $0xd,%al 1df: 74 1f je 200 <gets+0x60> for(i=0; i+1 < max; ){ 1e1: 83 c3 01 add $0x1,%ebx 1e4: 3b 5d 0c cmp 0xc(%ebp),%ebx 1e7: 89 fe mov %edi,%esi 1e9: 7c cd jl 1b8 <gets+0x18> 1eb: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 1ed: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 1f0: c6 03 00 movb $0x0,(%ebx) } 1f3: 8d 65 f4 lea -0xc(%ebp),%esp 1f6: 5b pop %ebx 1f7: 5e pop %esi 1f8: 5f pop %edi 1f9: 5d pop %ebp 1fa: c3 ret 1fb: 90 nop 1fc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 200: 8b 75 08 mov 0x8(%ebp),%esi 203: 8b 45 08 mov 0x8(%ebp),%eax 206: 01 de add %ebx,%esi 208: 89 f3 mov %esi,%ebx buf[i] = '\0'; 20a: c6 03 00 movb $0x0,(%ebx) } 20d: 8d 65 f4 lea -0xc(%ebp),%esp 210: 5b pop %ebx 211: 5e pop %esi 212: 5f pop %edi 213: 5d pop %ebp 214: c3 ret 215: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 219: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000220 <stat>: int stat(const char *n, struct stat *st) { 220: 55 push %ebp 221: 89 e5 mov %esp,%ebp 223: 56 push %esi 224: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 225: 83 ec 08 sub $0x8,%esp 228: 6a 00 push $0x0 22a: ff 75 08 pushl 0x8(%ebp) 22d: e8 f0 00 00 00 call 322 <open> if(fd < 0) 232: 83 c4 10 add $0x10,%esp 235: 85 c0 test %eax,%eax 237: 78 27 js 260 <stat+0x40> return -1; r = fstat(fd, st); 239: 83 ec 08 sub $0x8,%esp 23c: ff 75 0c pushl 0xc(%ebp) 23f: 89 c3 mov %eax,%ebx 241: 50 push %eax 242: e8 f3 00 00 00 call 33a <fstat> close(fd); 247: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 24a: 89 c6 mov %eax,%esi close(fd); 24c: e8 b9 00 00 00 call 30a <close> return r; 251: 83 c4 10 add $0x10,%esp } 254: 8d 65 f8 lea -0x8(%ebp),%esp 257: 89 f0 mov %esi,%eax 259: 5b pop %ebx 25a: 5e pop %esi 25b: 5d pop %ebp 25c: c3 ret 25d: 8d 76 00 lea 0x0(%esi),%esi return -1; 260: be ff ff ff ff mov $0xffffffff,%esi 265: eb ed jmp 254 <stat+0x34> 267: 89 f6 mov %esi,%esi 269: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000270 <atoi>: int atoi(const char *s) { 270: 55 push %ebp 271: 89 e5 mov %esp,%ebp 273: 53 push %ebx 274: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 277: 0f be 11 movsbl (%ecx),%edx 27a: 8d 42 d0 lea -0x30(%edx),%eax 27d: 3c 09 cmp $0x9,%al n = 0; 27f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 284: 77 1f ja 2a5 <atoi+0x35> 286: 8d 76 00 lea 0x0(%esi),%esi 289: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 290: 8d 04 80 lea (%eax,%eax,4),%eax 293: 83 c1 01 add $0x1,%ecx 296: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 29a: 0f be 11 movsbl (%ecx),%edx 29d: 8d 5a d0 lea -0x30(%edx),%ebx 2a0: 80 fb 09 cmp $0x9,%bl 2a3: 76 eb jbe 290 <atoi+0x20> return n; } 2a5: 5b pop %ebx 2a6: 5d pop %ebp 2a7: c3 ret 2a8: 90 nop 2a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000002b0 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 2b0: 55 push %ebp 2b1: 89 e5 mov %esp,%ebp 2b3: 56 push %esi 2b4: 53 push %ebx 2b5: 8b 5d 10 mov 0x10(%ebp),%ebx 2b8: 8b 45 08 mov 0x8(%ebp),%eax 2bb: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 2be: 85 db test %ebx,%ebx 2c0: 7e 14 jle 2d6 <memmove+0x26> 2c2: 31 d2 xor %edx,%edx 2c4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 2c8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 2cc: 88 0c 10 mov %cl,(%eax,%edx,1) 2cf: 83 c2 01 add $0x1,%edx while(n-- > 0) 2d2: 39 d3 cmp %edx,%ebx 2d4: 75 f2 jne 2c8 <memmove+0x18> return vdst; } 2d6: 5b pop %ebx 2d7: 5e pop %esi 2d8: 5d pop %ebp 2d9: c3 ret 000002da <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2da: b8 01 00 00 00 mov $0x1,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <exit>: SYSCALL(exit) 2e2: b8 02 00 00 00 mov $0x2,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <wait>: SYSCALL(wait) 2ea: b8 03 00 00 00 mov $0x3,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <pipe>: SYSCALL(pipe) 2f2: b8 04 00 00 00 mov $0x4,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <read>: SYSCALL(read) 2fa: b8 05 00 00 00 mov $0x5,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <write>: SYSCALL(write) 302: b8 10 00 00 00 mov $0x10,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <close>: SYSCALL(close) 30a: b8 15 00 00 00 mov $0x15,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <kill>: SYSCALL(kill) 312: b8 06 00 00 00 mov $0x6,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <exec>: SYSCALL(exec) 31a: b8 07 00 00 00 mov $0x7,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <open>: SYSCALL(open) 322: b8 0f 00 00 00 mov $0xf,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <mknod>: SYSCALL(mknod) 32a: b8 11 00 00 00 mov $0x11,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <unlink>: SYSCALL(unlink) 332: b8 12 00 00 00 mov $0x12,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <fstat>: SYSCALL(fstat) 33a: b8 08 00 00 00 mov $0x8,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <link>: SYSCALL(link) 342: b8 13 00 00 00 mov $0x13,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <mkdir>: SYSCALL(mkdir) 34a: b8 14 00 00 00 mov $0x14,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <chdir>: SYSCALL(chdir) 352: b8 09 00 00 00 mov $0x9,%eax 357: cd 40 int $0x40 359: c3 ret 0000035a <dup>: SYSCALL(dup) 35a: b8 0a 00 00 00 mov $0xa,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <getpid>: SYSCALL(getpid) 362: b8 0b 00 00 00 mov $0xb,%eax 367: cd 40 int $0x40 369: c3 ret 0000036a <sbrk>: SYSCALL(sbrk) 36a: b8 0c 00 00 00 mov $0xc,%eax 36f: cd 40 int $0x40 371: c3 ret 00000372 <sleep>: SYSCALL(sleep) 372: b8 0d 00 00 00 mov $0xd,%eax 377: cd 40 int $0x40 379: c3 ret 0000037a <uptime>: SYSCALL(uptime) 37a: b8 0e 00 00 00 mov $0xe,%eax 37f: cd 40 int $0x40 381: c3 ret 00000382 <memsize>: SYSCALL(memsize) 382: b8 16 00 00 00 mov $0x16,%eax 387: cd 40 int $0x40 389: c3 ret 0000038a <set_ps_priority>: SYSCALL(set_ps_priority) 38a: b8 17 00 00 00 mov $0x17,%eax 38f: cd 40 int $0x40 391: c3 ret 00000392 <set_cfs_priority>: SYSCALL(set_cfs_priority) 392: b8 18 00 00 00 mov $0x18,%eax 397: cd 40 int $0x40 399: c3 ret 0000039a <policy>: SYSCALL(policy) 39a: b8 19 00 00 00 mov $0x19,%eax 39f: cd 40 int $0x40 3a1: c3 ret 000003a2 <proc_info>: 3a2: b8 1a 00 00 00 mov $0x1a,%eax 3a7: cd 40 int $0x40 3a9: c3 ret 3aa: 66 90 xchg %ax,%ax 3ac: 66 90 xchg %ax,%ax 3ae: 66 90 xchg %ax,%ax 000003b0 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 3b0: 55 push %ebp 3b1: 89 e5 mov %esp,%ebp 3b3: 57 push %edi 3b4: 56 push %esi 3b5: 53 push %ebx 3b6: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 3b9: 85 d2 test %edx,%edx { 3bb: 89 45 c0 mov %eax,-0x40(%ebp) neg = 1; x = -xx; 3be: 89 d0 mov %edx,%eax if(sgn && xx < 0){ 3c0: 79 76 jns 438 <printint+0x88> 3c2: f6 45 08 01 testb $0x1,0x8(%ebp) 3c6: 74 70 je 438 <printint+0x88> x = -xx; 3c8: f7 d8 neg %eax neg = 1; 3ca: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) } else { x = xx; } i = 0; 3d1: 31 f6 xor %esi,%esi 3d3: 8d 5d d7 lea -0x29(%ebp),%ebx 3d6: eb 0a jmp 3e2 <printint+0x32> 3d8: 90 nop 3d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi do{ buf[i++] = digits[x % base]; 3e0: 89 fe mov %edi,%esi 3e2: 31 d2 xor %edx,%edx 3e4: 8d 7e 01 lea 0x1(%esi),%edi 3e7: f7 f1 div %ecx 3e9: 0f b6 92 dc 07 00 00 movzbl 0x7dc(%edx),%edx }while((x /= base) != 0); 3f0: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 3f2: 88 14 3b mov %dl,(%ebx,%edi,1) }while((x /= base) != 0); 3f5: 75 e9 jne 3e0 <printint+0x30> if(neg) 3f7: 8b 45 c4 mov -0x3c(%ebp),%eax 3fa: 85 c0 test %eax,%eax 3fc: 74 08 je 406 <printint+0x56> buf[i++] = '-'; 3fe: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 403: 8d 7e 02 lea 0x2(%esi),%edi 406: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi 40a: 8b 7d c0 mov -0x40(%ebp),%edi 40d: 8d 76 00 lea 0x0(%esi),%esi 410: 0f b6 06 movzbl (%esi),%eax write(fd, &c, 1); 413: 83 ec 04 sub $0x4,%esp 416: 83 ee 01 sub $0x1,%esi 419: 6a 01 push $0x1 41b: 53 push %ebx 41c: 57 push %edi 41d: 88 45 d7 mov %al,-0x29(%ebp) 420: e8 dd fe ff ff call 302 <write> while(--i >= 0) 425: 83 c4 10 add $0x10,%esp 428: 39 de cmp %ebx,%esi 42a: 75 e4 jne 410 <printint+0x60> putc(fd, buf[i]); } 42c: 8d 65 f4 lea -0xc(%ebp),%esp 42f: 5b pop %ebx 430: 5e pop %esi 431: 5f pop %edi 432: 5d pop %ebp 433: c3 ret 434: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 438: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 43f: eb 90 jmp 3d1 <printint+0x21> 441: eb 0d jmp 450 <printf> 443: 90 nop 444: 90 nop 445: 90 nop 446: 90 nop 447: 90 nop 448: 90 nop 449: 90 nop 44a: 90 nop 44b: 90 nop 44c: 90 nop 44d: 90 nop 44e: 90 nop 44f: 90 nop 00000450 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 450: 55 push %ebp 451: 89 e5 mov %esp,%ebp 453: 57 push %edi 454: 56 push %esi 455: 53 push %ebx 456: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 459: 8b 75 0c mov 0xc(%ebp),%esi 45c: 0f b6 1e movzbl (%esi),%ebx 45f: 84 db test %bl,%bl 461: 0f 84 b3 00 00 00 je 51a <printf+0xca> ap = (uint*)(void*)&fmt + 1; 467: 8d 45 10 lea 0x10(%ebp),%eax 46a: 83 c6 01 add $0x1,%esi state = 0; 46d: 31 ff xor %edi,%edi ap = (uint*)(void*)&fmt + 1; 46f: 89 45 d4 mov %eax,-0x2c(%ebp) 472: eb 2f jmp 4a3 <printf+0x53> 474: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 478: 83 f8 25 cmp $0x25,%eax 47b: 0f 84 a7 00 00 00 je 528 <printf+0xd8> write(fd, &c, 1); 481: 8d 45 e2 lea -0x1e(%ebp),%eax 484: 83 ec 04 sub $0x4,%esp 487: 88 5d e2 mov %bl,-0x1e(%ebp) 48a: 6a 01 push $0x1 48c: 50 push %eax 48d: ff 75 08 pushl 0x8(%ebp) 490: e8 6d fe ff ff call 302 <write> 495: 83 c4 10 add $0x10,%esp 498: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 49b: 0f b6 5e ff movzbl -0x1(%esi),%ebx 49f: 84 db test %bl,%bl 4a1: 74 77 je 51a <printf+0xca> if(state == 0){ 4a3: 85 ff test %edi,%edi c = fmt[i] & 0xff; 4a5: 0f be cb movsbl %bl,%ecx 4a8: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 4ab: 74 cb je 478 <printf+0x28> state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 4ad: 83 ff 25 cmp $0x25,%edi 4b0: 75 e6 jne 498 <printf+0x48> if(c == 'd'){ 4b2: 83 f8 64 cmp $0x64,%eax 4b5: 0f 84 05 01 00 00 je 5c0 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 4bb: 81 e1 f7 00 00 00 and $0xf7,%ecx 4c1: 83 f9 70 cmp $0x70,%ecx 4c4: 74 72 je 538 <printf+0xe8> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 4c6: 83 f8 73 cmp $0x73,%eax 4c9: 0f 84 99 00 00 00 je 568 <printf+0x118> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 4cf: 83 f8 63 cmp $0x63,%eax 4d2: 0f 84 08 01 00 00 je 5e0 <printf+0x190> putc(fd, *ap); ap++; } else if(c == '%'){ 4d8: 83 f8 25 cmp $0x25,%eax 4db: 0f 84 ef 00 00 00 je 5d0 <printf+0x180> write(fd, &c, 1); 4e1: 8d 45 e7 lea -0x19(%ebp),%eax 4e4: 83 ec 04 sub $0x4,%esp 4e7: c6 45 e7 25 movb $0x25,-0x19(%ebp) 4eb: 6a 01 push $0x1 4ed: 50 push %eax 4ee: ff 75 08 pushl 0x8(%ebp) 4f1: e8 0c fe ff ff call 302 <write> 4f6: 83 c4 0c add $0xc,%esp 4f9: 8d 45 e6 lea -0x1a(%ebp),%eax 4fc: 88 5d e6 mov %bl,-0x1a(%ebp) 4ff: 6a 01 push $0x1 501: 50 push %eax 502: ff 75 08 pushl 0x8(%ebp) 505: 83 c6 01 add $0x1,%esi } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 508: 31 ff xor %edi,%edi write(fd, &c, 1); 50a: e8 f3 fd ff ff call 302 <write> for(i = 0; fmt[i]; i++){ 50f: 0f b6 5e ff movzbl -0x1(%esi),%ebx write(fd, &c, 1); 513: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 516: 84 db test %bl,%bl 518: 75 89 jne 4a3 <printf+0x53> } } } 51a: 8d 65 f4 lea -0xc(%ebp),%esp 51d: 5b pop %ebx 51e: 5e pop %esi 51f: 5f pop %edi 520: 5d pop %ebp 521: c3 ret 522: 8d b6 00 00 00 00 lea 0x0(%esi),%esi state = '%'; 528: bf 25 00 00 00 mov $0x25,%edi 52d: e9 66 ff ff ff jmp 498 <printf+0x48> 532: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); 538: 83 ec 0c sub $0xc,%esp 53b: b9 10 00 00 00 mov $0x10,%ecx 540: 6a 00 push $0x0 542: 8b 7d d4 mov -0x2c(%ebp),%edi 545: 8b 45 08 mov 0x8(%ebp),%eax 548: 8b 17 mov (%edi),%edx 54a: e8 61 fe ff ff call 3b0 <printint> ap++; 54f: 89 f8 mov %edi,%eax 551: 83 c4 10 add $0x10,%esp state = 0; 554: 31 ff xor %edi,%edi ap++; 556: 83 c0 04 add $0x4,%eax 559: 89 45 d4 mov %eax,-0x2c(%ebp) 55c: e9 37 ff ff ff jmp 498 <printf+0x48> 561: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 568: 8b 45 d4 mov -0x2c(%ebp),%eax 56b: 8b 08 mov (%eax),%ecx ap++; 56d: 83 c0 04 add $0x4,%eax 570: 89 45 d4 mov %eax,-0x2c(%ebp) if(s == 0) 573: 85 c9 test %ecx,%ecx 575: 0f 84 8e 00 00 00 je 609 <printf+0x1b9> while(*s != 0){ 57b: 0f b6 01 movzbl (%ecx),%eax state = 0; 57e: 31 ff xor %edi,%edi s = (char*)*ap; 580: 89 cb mov %ecx,%ebx while(*s != 0){ 582: 84 c0 test %al,%al 584: 0f 84 0e ff ff ff je 498 <printf+0x48> 58a: 89 75 d0 mov %esi,-0x30(%ebp) 58d: 89 de mov %ebx,%esi 58f: 8b 5d 08 mov 0x8(%ebp),%ebx 592: 8d 7d e3 lea -0x1d(%ebp),%edi 595: 8d 76 00 lea 0x0(%esi),%esi write(fd, &c, 1); 598: 83 ec 04 sub $0x4,%esp s++; 59b: 83 c6 01 add $0x1,%esi 59e: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); 5a1: 6a 01 push $0x1 5a3: 57 push %edi 5a4: 53 push %ebx 5a5: e8 58 fd ff ff call 302 <write> while(*s != 0){ 5aa: 0f b6 06 movzbl (%esi),%eax 5ad: 83 c4 10 add $0x10,%esp 5b0: 84 c0 test %al,%al 5b2: 75 e4 jne 598 <printf+0x148> 5b4: 8b 75 d0 mov -0x30(%ebp),%esi state = 0; 5b7: 31 ff xor %edi,%edi 5b9: e9 da fe ff ff jmp 498 <printf+0x48> 5be: 66 90 xchg %ax,%ax printint(fd, *ap, 10, 1); 5c0: 83 ec 0c sub $0xc,%esp 5c3: b9 0a 00 00 00 mov $0xa,%ecx 5c8: 6a 01 push $0x1 5ca: e9 73 ff ff ff jmp 542 <printf+0xf2> 5cf: 90 nop write(fd, &c, 1); 5d0: 83 ec 04 sub $0x4,%esp 5d3: 88 5d e5 mov %bl,-0x1b(%ebp) 5d6: 8d 45 e5 lea -0x1b(%ebp),%eax 5d9: 6a 01 push $0x1 5db: e9 21 ff ff ff jmp 501 <printf+0xb1> putc(fd, *ap); 5e0: 8b 7d d4 mov -0x2c(%ebp),%edi write(fd, &c, 1); 5e3: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 5e6: 8b 07 mov (%edi),%eax write(fd, &c, 1); 5e8: 6a 01 push $0x1 ap++; 5ea: 83 c7 04 add $0x4,%edi putc(fd, *ap); 5ed: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); 5f0: 8d 45 e4 lea -0x1c(%ebp),%eax 5f3: 50 push %eax 5f4: ff 75 08 pushl 0x8(%ebp) 5f7: e8 06 fd ff ff call 302 <write> ap++; 5fc: 89 7d d4 mov %edi,-0x2c(%ebp) 5ff: 83 c4 10 add $0x10,%esp state = 0; 602: 31 ff xor %edi,%edi 604: e9 8f fe ff ff jmp 498 <printf+0x48> s = "(null)"; 609: bb d5 07 00 00 mov $0x7d5,%ebx while(*s != 0){ 60e: b8 28 00 00 00 mov $0x28,%eax 613: e9 72 ff ff ff jmp 58a <printf+0x13a> 618: 66 90 xchg %ax,%ax 61a: 66 90 xchg %ax,%ax 61c: 66 90 xchg %ax,%ax 61e: 66 90 xchg %ax,%ax 00000620 <free>: static Header base; static Header *freep; void free(void *ap) { 620: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 621: a1 8c 0a 00 00 mov 0xa8c,%eax { 626: 89 e5 mov %esp,%ebp 628: 57 push %edi 629: 56 push %esi 62a: 53 push %ebx 62b: 8b 5d 08 mov 0x8(%ebp),%ebx bp = (Header*)ap - 1; 62e: 8d 4b f8 lea -0x8(%ebx),%ecx 631: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 638: 39 c8 cmp %ecx,%eax 63a: 8b 10 mov (%eax),%edx 63c: 73 32 jae 670 <free+0x50> 63e: 39 d1 cmp %edx,%ecx 640: 72 04 jb 646 <free+0x26> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 642: 39 d0 cmp %edx,%eax 644: 72 32 jb 678 <free+0x58> break; if(bp + bp->s.size == p->s.ptr){ 646: 8b 73 fc mov -0x4(%ebx),%esi 649: 8d 3c f1 lea (%ecx,%esi,8),%edi 64c: 39 fa cmp %edi,%edx 64e: 74 30 je 680 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 650: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 653: 8b 50 04 mov 0x4(%eax),%edx 656: 8d 34 d0 lea (%eax,%edx,8),%esi 659: 39 f1 cmp %esi,%ecx 65b: 74 3a je 697 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 65d: 89 08 mov %ecx,(%eax) freep = p; 65f: a3 8c 0a 00 00 mov %eax,0xa8c } 664: 5b pop %ebx 665: 5e pop %esi 666: 5f pop %edi 667: 5d pop %ebp 668: c3 ret 669: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 670: 39 d0 cmp %edx,%eax 672: 72 04 jb 678 <free+0x58> 674: 39 d1 cmp %edx,%ecx 676: 72 ce jb 646 <free+0x26> { 678: 89 d0 mov %edx,%eax 67a: eb bc jmp 638 <free+0x18> 67c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 680: 03 72 04 add 0x4(%edx),%esi 683: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 686: 8b 10 mov (%eax),%edx 688: 8b 12 mov (%edx),%edx 68a: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 68d: 8b 50 04 mov 0x4(%eax),%edx 690: 8d 34 d0 lea (%eax,%edx,8),%esi 693: 39 f1 cmp %esi,%ecx 695: 75 c6 jne 65d <free+0x3d> p->s.size += bp->s.size; 697: 03 53 fc add -0x4(%ebx),%edx freep = p; 69a: a3 8c 0a 00 00 mov %eax,0xa8c p->s.size += bp->s.size; 69f: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6a2: 8b 53 f8 mov -0x8(%ebx),%edx 6a5: 89 10 mov %edx,(%eax) } 6a7: 5b pop %ebx 6a8: 5e pop %esi 6a9: 5f pop %edi 6aa: 5d pop %ebp 6ab: c3 ret 6ac: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 000006b0 <malloc>: return freep; } void* malloc(uint nbytes) { 6b0: 55 push %ebp 6b1: 89 e5 mov %esp,%ebp 6b3: 57 push %edi 6b4: 56 push %esi 6b5: 53 push %ebx 6b6: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6b9: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 6bc: 8b 15 8c 0a 00 00 mov 0xa8c,%edx nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6c2: 8d 78 07 lea 0x7(%eax),%edi 6c5: c1 ef 03 shr $0x3,%edi 6c8: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 6cb: 85 d2 test %edx,%edx 6cd: 0f 84 9d 00 00 00 je 770 <malloc+0xc0> 6d3: 8b 02 mov (%edx),%eax 6d5: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 6d8: 39 cf cmp %ecx,%edi 6da: 76 6c jbe 748 <malloc+0x98> 6dc: 81 ff 00 10 00 00 cmp $0x1000,%edi 6e2: bb 00 10 00 00 mov $0x1000,%ebx 6e7: 0f 43 df cmovae %edi,%ebx p = sbrk(nu * sizeof(Header)); 6ea: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi 6f1: eb 0e jmp 701 <malloc+0x51> 6f3: 90 nop 6f4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 6f8: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 6fa: 8b 48 04 mov 0x4(%eax),%ecx 6fd: 39 f9 cmp %edi,%ecx 6ff: 73 47 jae 748 <malloc+0x98> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 701: 39 05 8c 0a 00 00 cmp %eax,0xa8c 707: 89 c2 mov %eax,%edx 709: 75 ed jne 6f8 <malloc+0x48> p = sbrk(nu * sizeof(Header)); 70b: 83 ec 0c sub $0xc,%esp 70e: 56 push %esi 70f: e8 56 fc ff ff call 36a <sbrk> if(p == (char*)-1) 714: 83 c4 10 add $0x10,%esp 717: 83 f8 ff cmp $0xffffffff,%eax 71a: 74 1c je 738 <malloc+0x88> hp->s.size = nu; 71c: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 71f: 83 ec 0c sub $0xc,%esp 722: 83 c0 08 add $0x8,%eax 725: 50 push %eax 726: e8 f5 fe ff ff call 620 <free> return freep; 72b: 8b 15 8c 0a 00 00 mov 0xa8c,%edx if((p = morecore(nunits)) == 0) 731: 83 c4 10 add $0x10,%esp 734: 85 d2 test %edx,%edx 736: 75 c0 jne 6f8 <malloc+0x48> return 0; } } 738: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 73b: 31 c0 xor %eax,%eax } 73d: 5b pop %ebx 73e: 5e pop %esi 73f: 5f pop %edi 740: 5d pop %ebp 741: c3 ret 742: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if(p->s.size == nunits) 748: 39 cf cmp %ecx,%edi 74a: 74 54 je 7a0 <malloc+0xf0> p->s.size -= nunits; 74c: 29 f9 sub %edi,%ecx 74e: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 751: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 754: 89 78 04 mov %edi,0x4(%eax) freep = prevp; 757: 89 15 8c 0a 00 00 mov %edx,0xa8c } 75d: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 760: 83 c0 08 add $0x8,%eax } 763: 5b pop %ebx 764: 5e pop %esi 765: 5f pop %edi 766: 5d pop %ebp 767: c3 ret 768: 90 nop 769: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; 770: c7 05 8c 0a 00 00 90 movl $0xa90,0xa8c 777: 0a 00 00 77a: c7 05 90 0a 00 00 90 movl $0xa90,0xa90 781: 0a 00 00 base.s.size = 0; 784: b8 90 0a 00 00 mov $0xa90,%eax 789: c7 05 94 0a 00 00 00 movl $0x0,0xa94 790: 00 00 00 793: e9 44 ff ff ff jmp 6dc <malloc+0x2c> 798: 90 nop 799: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi prevp->s.ptr = p->s.ptr; 7a0: 8b 08 mov (%eax),%ecx 7a2: 89 0a mov %ecx,(%edx) 7a4: eb b1 jmp 757 <malloc+0xa7>
#include "../../dist/librm2fb.hpp" int main() { srand(time(NULL)); printf("SENDING MSG UPDATE\n"); swtfb::SwtFB fb; int offset = (rand() % 1024); for (unsigned int i = 0; i < WIDTH * HEIGHT; i++) { fb.fbmem[i] = i + offset; } uint32_t x = (rand() % WIDTH); uint32_t y = (rand() % HEIGHT); if (x > WIDTH) { x -= WIDTH; }; if (y > HEIGHT) { y -= HEIGHT; }; uint32_t w = 200 + (rand() % 10 + 1) * 50; uint32_t h = 200 + (rand() % 10 + 1) * 50; fb.mark_dirty({.left = x, .top = y, w, h}); fb.redraw_screen(); }
CGABubbles label byte word C_BLACK Bitmap <67,41,0,BMF_MONO> db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 db 0x7f, 0xff, 0xff, 0xff, 0x00, 0x03, 0xff, 0xff, 0xc0 db 0x7f, 0xff, 0xff, 0xff, 0x80, 0x01, 0xff, 0xff, 0xc0 db 0x7f, 0xff, 0xff, 0xff, 0xc0, 0x00, 0xff, 0xc0, 0x00 db 0x78, 0x00, 0x00, 0x01, 0x60, 0x00, 0x7f, 0xe0, 0x00 db 0x7c, 0x00, 0x00, 0x01, 0xb0, 0x00, 0x3f, 0xb0, 0x00 db 0x76, 0x00, 0x00, 0x00, 0xd8, 0x00, 0x1f, 0xd8, 0x00 db 0x7b, 0x00, 0x00, 0x00, 0x6f, 0xff, 0xff, 0xac, 0x00 db 0x75, 0x80, 0x00, 0x00, 0x34, 0x00, 0x0f, 0xd6, 0x00 db 0x7a, 0xc0, 0x00, 0x00, 0x1c, 0x00, 0x0f, 0xab, 0xc0 db 0x75, 0x60, 0x00, 0x00, 0x0c, 0x00, 0x0f, 0xd5, 0x00 db 0x7a, 0xb0, 0x00, 0x00, 0x07, 0xff, 0xff, 0xeb, 0x00 db 0x75, 0x58, 0x00, 0x00, 0x00, 0x01, 0xff, 0xf5, 0x00 db 0x7a, 0xaf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0x00 db 0x75, 0x54, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xfd, 0x00 db 0x7e, 0xac, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00 db 0x01, 0x54, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x3f, 0x00 db 0x00, 0xac, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x1f, 0xc0 db 0x00, 0x54, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x0f, 0xc0 db 0x7f, 0xec, 0x00, 0x00, 0x00, 0xa8, 0x00, 0x07, 0xc0 db 0x00, 0x34, 0x00, 0x00, 0x00, 0xd4, 0x00, 0x03, 0xc0 db 0x00, 0x2c, 0x00, 0x00, 0x00, 0xaa, 0x00, 0x01, 0xc0 db 0x00, 0x34, 0x00, 0x00, 0x00, 0xd5, 0xff, 0xff, 0xc0 db 0x00, 0x2c, 0x00, 0x00, 0x00, 0xab, 0x00, 0x00, 0xc0 db 0x7f, 0xf4, 0x00, 0x00, 0x00, 0xd5, 0x00, 0x00, 0xc0 db 0x7f, 0xec, 0x00, 0x00, 0x00, 0x6b, 0x00, 0x00, 0xc0 db 0x7f, 0xf4, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0xc0 db 0x7e, 0x1c, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0xc0 db 0x7d, 0x0c, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0xc0 db 0x7e, 0x87, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xc0 db 0x7d, 0x40, 0x00, 0x00, 0xfd, 0x63, 0x00, 0x00, 0xc0 db 0x7e, 0xa0, 0x00, 0x00, 0x7e, 0xa1, 0xff, 0xff, 0xc0 db 0x7d, 0x50, 0x00, 0x00, 0x3f, 0x60, 0x00, 0x1f, 0xc0 db 0x7e, 0xa8, 0x00, 0x00, 0x1f, 0xa0, 0x00, 0x1f, 0xc0 db 0x7d, 0x57, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x1f, 0xc0 db 0x7e, 0xac, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xc0 db 0x7f, 0x54, 0x00, 0x00, 0x0f, 0xff, 0xf0, 0x00, 0x00 db 0x7f, 0xac, 0x00, 0x00, 0x0f, 0xff, 0xe8, 0x00, 0x00 db 0x7f, 0xd4, 0x00, 0x00, 0x0f, 0xff, 0xf4, 0x00, 0x00 db 0x7f, 0xec, 0x00, 0x00, 0x0f, 0xff, 0xea, 0x00, 0x00 db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
; A033484: a(n) = 3*2^n - 2. ; 1,4,10,22,46,94,190,382,766,1534,3070,6142,12286,24574,49150,98302,196606,393214,786430,1572862,3145726,6291454,12582910,25165822,50331646,100663294,201326590,402653182,805306366,1610612734,3221225470 mov $1,2 pow $1,$0 mul $1,3 sub $1,2
\ ****************************************************************************** \ \ ELITE-A LOADER SOURCE \ \ Elite-A is an extended version of BBC Micro Elite by Angus Duggan \ \ The original Elite was written by Ian Bell and David Braben and is copyright \ Acornsoft 1984, and the extra code in Elite-A is copyright Angus Duggan \ \ The code on this site is identical to Angus Duggan's source discs (it's just \ been reformatted, and the label names have been changed to be consistent with \ the sources for the original BBC Micro disc version on which it is based) \ \ The commentary is copyright Mark Moxon, and any misunderstandings or mistakes \ in the documentation are entirely my fault \ \ The terminology and notations used in this commentary are explained at \ https://www.bbcelite.com/about_site/terminology_used_in_this_commentary.html \ \ The deep dive articles referred to in this commentary can be found at \ https://www.bbcelite.com/deep_dives \ \ ------------------------------------------------------------------------------ \ \ This source file produces the following binary file: \ \ * ELITE.bin \ \ ****************************************************************************** INCLUDE "1-source-files/main-sources/elite-header.h.asm" _RELEASED = (_RELEASE = 1) _SOURCE_DISC = (_RELEASE = 2) _BUG_FIX = (_RELEASE = 3) GUARD &6000 \ Guard against assembling over screen memory \ ****************************************************************************** \ \ Configuration variables \ \ ****************************************************************************** Q% = _REMOVE_CHECKSUMS \ Set Q% to TRUE to max out the default commander, FALSE \ for the standard default commander (this is set to \ TRUE if checksums are disabled, just for convenience) N% = 67 \ N% is set to the number of bytes in the VDU table, so \ we can loop through them in part 1 below VSCAN = 57 \ Defines the split position in the split-screen mode BRKV = &0202 \ The break vector that we intercept to enable us to \ handle and display system errors IRQ1V = &0204 \ The IRQ1V vector that we intercept to implement the \ split-screen mode WRCHV = &020E \ The WRCHV vector that we intercept with our custom \ text printing routine BYTEV = &020A \ The BYTEV vector that we intercept on the BBC Master FILEV = &0212 \ The FILEV vector that we intercept on the BBC Master FSCV = &021E \ The FSCV vector that we intercept on the BBC Master NETV = &0224 \ The NETV vector that we intercept as part of the copy \ protection LASCT = &0346 \ The laser pulse count for the current laser, matching \ the address in the main game code HFX = &0348 \ A flag that toggles the hyperspace colour effect, \ matching the address in the main game code CRGO = &036E \ The flag that determines whether we have an I.F.F. \ system fitted, matching the address in the main game \ code ESCP = &0386 \ The flag that determines whether we have an escape pod \ fitted, matching the address in the main game code S% = &11E3 \ The adress of the main entry point workspace in the \ main game code VIA = &FE00 \ Memory-mapped space for accessing internal hardware, \ such as the video ULA, 6845 CRTC and 6522 VIAs (also \ known as SHEILA) OSWRCH = &FFEE \ The address for the OSWRCH routine OSBYTE = &FFF4 \ The address for the OSBYTE routine OSWORD = &FFF1 \ The address for the OSWORD routine OSCLI = &FFF7 \ The address for the OSCLI vector VEC = &7FFE \ VEC is where we store the original value of the IRQ1 \ vector, matching the address in the elite-missile.asm \ source \ ****************************************************************************** \ \ Name: ZP \ Type: Workspace \ Address: &0070 to &008C \ Category: Workspaces \ Summary: Important variables used by the loader \ \ ****************************************************************************** ORG &0004 .TRTB% SKIP 2 \ Contains the address of the keyboard translation \ table, which is used to translate internal key \ numbers to ASCII ORG &0020 .INF SKIP 2 \ Temporary storage, typically used for storing the \ address of a ship's data block, so it can be copied \ to and from the internal workspace at INWK ORG &0070 .ZP SKIP 2 \ Stores addresses used for moving content around .P SKIP 1 \ Temporary storage, used in a number of places .Q SKIP 1 \ Temporary storage, used in a number of places .YY SKIP 1 \ Temporary storage, used in a number of places .T SKIP 1 \ Temporary storage, used in a number of places .SC SKIP 1 \ Screen address (low byte) \ \ Elite draws on-screen by poking bytes directly into \ screen memory, and SC(1 0) is typically set to the \ address of the character block containing the pixel \ we want to draw (see the deep dives on "Drawing \ monochrome pixels in mode 4" and "Drawing colour \ pixels in mode 5" for more details) .SCH SKIP 1 \ Screen address (high byte) .CHKSM SKIP 2 \ Used in the copy protection code ORG &008B .DL SKIP 1 \ Vertical sync flag \ \ DL gets set to 30 every time we reach vertical sync on \ the video system, which happens 50 times a second \ (50Hz). The WSCAN routine uses this to pause until the \ vertical sync, by setting DL to 0 and then monitoring \ its value until it changes to 30 .TYPE SKIP 1 \ The current ship type \ \ This is where we store the current ship type for when \ we are iterating through the ships in the local bubble \ as part of the main flight loop. See the table at XX21 \ for information about ship types ORG &0090 .key_tube SKIP 2 \ Contains the address of the I/O processor's keyboard \ translation table (as opposed to the parasite's \ table), which is used to translate internal key \ numbers to ASCII in the I/O processor code ORG &00F4 .LATCH SKIP 2 \ The RAM copy of the currently selected paged ROM/RAM \ in SHEILA &30 \ ****************************************************************************** \ \ ELITE LOADER \ \ ****************************************************************************** CODE% = &1900 LOAD% = &1900 ORG CODE% \ ****************************************************************************** \ \ Name: B% \ Type: Variable \ Category: Screen mode \ Summary: VDU commands for setting the square mode 4 screen \ Deep dive: The split-screen mode \ Drawing monochrome pixels in mode 4 \ \ ------------------------------------------------------------------------------ \ \ This block contains the bytes that get written by OSWRCH to set up the screen \ mode (this is equivalent to using the VDU statement in BASIC). \ \ It defines the whole screen using a square, monochrome mode 4 configuration; \ the mode 5 part for the dashboard is implemented in the IRQ1 routine. \ \ The top part of Elite's screen mode is based on mode 4 but with the following \ differences: \ \ * 32 columns, 31 rows (256 x 248 pixels) rather than 40, 32 \ \ * The horizontal sync position is at character 45 rather than 49, which \ pushes the screen to the right (which centres it as it's not as wide as \ the normal screen modes) \ \ * Screen memory goes from &6000 to &7EFF, which leaves another whole page \ for code (i.e. 256 bytes) after the end of the screen. This is where the \ Python ship blueprint slots in \ \ * The text window is 1 row high and 13 columns wide, and is at (2, 16) \ \ * The cursor is disabled \ \ This almost-square mode 4 variant makes life a lot easier when drawing to the \ screen, as there are 256 pixels on each row (or, to put it in screen memory \ terms, there's one page of memory per row of pixels). For more details of the \ screen mode, see the deep dive on "Drawing monochrome pixels in mode 4". \ \ There is also an interrupt-driven routine that switches the bytes-per-pixel \ setting from that of mode 4 to that of mode 5, when the raster reaches the \ split between the space view and the dashboard. See the deep dive on "The \ split-screen mode" for details. \ \ ****************************************************************************** .B% EQUB 22, 4 \ Switch to screen mode 4 EQUB 28 \ Define a text window as follows: EQUB 2, 17, 15, 16 \ \ * Left = 2 \ * Right = 15 \ * Top = 16 \ * Bottom = 17 \ \ i.e. 1 row high, 13 columns wide at (2, 16) EQUB 23, 0, 6, 31 \ Set 6845 register R6 = 31 EQUB 0, 0, 0 \ EQUB 0, 0, 0 \ This is the "vertical displayed" register, and sets \ the number of displayed character rows to 31. For \ comparison, this value is 32 for standard modes 4 and \ 5, but we claw back the last row for storing code just \ above the end of screen memory EQUB 23, 0, 12, &0C \ Set 6845 register R12 = &0C and R13 = &00 EQUB 0, 0, 0 \ EQUB 0, 0, 0 \ This sets 6845 registers (R12 R13) = &0C00 to point EQUB 23, 0, 13, &00 \ to the start of screen memory in terms of character EQUB 0, 0, 0 \ rows. There are 8 pixel lines in each character row, EQUB 0, 0, 0 \ so to get the actual address of the start of screen \ memory, we multiply by 8: \ \ &0C00 * 8 = &6000 \ \ So this sets the start of screen memory to &6000 EQUB 23, 0, 1, 32 \ Set 6845 register R1 = 32 EQUB 0, 0, 0 \ EQUB 0, 0, 0 \ This is the "horizontal displayed" register, which \ defines the number of character blocks per horizontal \ character row. For comparison, this value is 40 for \ modes 4 and 5, but our custom screen is not as wide at \ only 32 character blocks across EQUB 23, 0, 2, 45 \ Set 6845 register R2 = 45 EQUB 0, 0, 0 \ EQUB 0, 0, 0 \ This is the "horizontal sync position" register, which \ defines the position of the horizontal sync pulse on \ the horizontal line in terms of character widths from \ the left-hand side of the screen. For comparison this \ is 49 for modes 4 and 5, but needs to be adjusted for \ our custom screen's width EQUB 23, 0, 10, 32 \ Set 6845 register R10 = 32 EQUB 0, 0, 0 \ EQUB 0, 0, 0 \ This is the "cursor start" register, so this sets the \ cursor start line at 0, effectively disabling the \ cursor \ ****************************************************************************** \ \ Name: E% \ Type: Variable \ Category: Sound \ Summary: Sound envelope definitions \ \ ------------------------------------------------------------------------------ \ \ This table contains the sound envelope data, which is passed to OSWORD by the \ FNE macro to create the four sound envelopes used in-game. Refer to chapter 30 \ of the BBC Micro User Guide for details of sound envelopes and what all the \ parameters mean. \ \ The envelopes are as follows: \ \ * Envelope 1 is the sound of our own laser firing \ \ * Envelope 2 is the sound of lasers hitting us, or hyperspace \ \ * Envelope 3 is the first sound in the two-part sound of us dying, or the \ second sound in the two-part sound of us making hitting or killing an \ enemy ship \ \ * Envelope 4 is the sound of E.C.M. firing \ \ ****************************************************************************** .E% EQUB 1, 1, 0, 111, -8, 4, 1, 8, 8, -2, 0, -1, 126, 44 EQUB 2, 1, 14, -18, -1, 44, 32, 50, 6, 1, 0, -2, 120, 126 EQUB 3, 1, 1, -1, -3, 17, 32, 128, 1, 0, 0, -1, 1, 1 EQUB 4, 1, 4, -8, 44, 4, 6, 8, 22, 0, 0, -127, 126, 0 \ ****************************************************************************** \ \ Name: FNE \ Type: Macro \ Category: Sound \ Summary: Macro definition for defining a sound envelope \ \ ------------------------------------------------------------------------------ \ \ The following macro is used to define the four sound envelopes used in the \ game. It uses OSWORD 8 to create an envelope using the 14 parameters in the \ the I%-th block of 14 bytes at location E%. This OSWORD call is the same as \ BBC BASIC's ENVELOPE command. \ \ See variable E% for more details of the envelopes themselves. \ \ ****************************************************************************** MACRO FNE I% LDX #LO(E%+I%*14) \ Set (Y X) to point to the I%-th set of envelope data LDY #HI(E%+I%*14) \ in E% LDA #8 \ Call OSWORD with A = 8 to set up sound envelope I% JSR OSWORD ENDMACRO \ ****************************************************************************** \ \ Name: Elite loader (Part 1 of 3) \ Type: Subroutine \ Category: Loader \ Summary: Set up the split screen mode, move code around, set up the sound \ envelopes and configure the system \ \ ****************************************************************************** .ENTRY \ --- Mod: Original Acornsoft code removed: -----------> \ JSR PROT1 \ Call PROT1 to calculate checksums into CHKSM \ \ LDA #144 \ Call OSBYTE with A = 144, X = 255 and Y = 0 to move \ LDX #255 \ the screen down one line and turn screen interlace on \ JSR OSB \ --- And replaced by: --------------------------------> CLI \ Enable interrupts LDA #144 \ Call OSBYTE with A = 144, X = 255 and Y = 1 to move LDX #255 \ the screen down one line and turn screen interlace off LDY #1 JSR OSBYTE \ --- End of replacement ------------------------------> LDA #LO(B%) \ Set the low byte of ZP(1 0) to point to the VDU code STA ZP \ table at B% LDA #HI(B%) \ Set the high byte of ZP(1 0) to point to the VDU code STA ZP+1 \ table at B% LDY #0 \ We are now going to send the N% VDU bytes in the table \ at B% to OSWRCH to set up the special mode 4 screen \ that forms the basis for the split-screen mode .loop1 LDA (ZP),Y \ Pass the Y-th byte of the B% table to OSWRCH JSR OSWRCH INY \ Increment the loop counter CPY #N% \ Loop back for the next byte until we have done them BNE loop1 \ all (the number of bytes was set in N% above) JSR PLL1 \ Call PLL1 to draw Saturn \ --- Mod: Original Acornsoft code removed: -----------> \ LDA #16 \ Call OSBYTE with A = 16 and X = 3 to set the ADC to \ LDX #3 \ sample 3 channels from the joystick/Bitstik \ JSR OSBYTE \ --- And replaced by: --------------------------------> LDA #16 \ Call OSBYTE with A = 16 and X = 2 to set the ADC to LDX #2 \ sample 2 channels from the joystick JSR OSBYTE \ --- End of replacement ------------------------------> LDA #&60 \ Store an RTS instruction in location &0232 STA &0232 LDA #&02 \ Point the NETV vector to &0232, which we just filled STA NETV+1 \ with an RTS LDA #&32 STA NETV LDA #190 \ Call OSBYTE with A = 190, X = 8 and Y = 0 to set the LDX #8 \ ADC conversion type to 8 bits, for the joystick JSR OSB \ --- Mod: Original Acornsoft code removed: -----------> \ LDA #200 \ Call OSBYTE with A = 200, X = 0 and Y = 0 to enable \ LDX #0 \ the ESCAPE key and disable memory clearing if the \ JSR OSB \ BREAK key is pressed \ --- And replaced by: --------------------------------> LDA #200 \ Call OSBYTE with A = 200, X = 3 and Y = 0 to disable LDX #3 \ the ESCAPE key and clear memory if the BREAK key is JSR OSB \ pressed \ --- End of replacement ------------------------------> LDA #13 \ Call OSBYTE with A = 13, X = 0 and Y = 0 to disable LDX #0 \ the "output buffer empty" event JSR OSB LDA #225 \ Call OSBYTE with A = 225, X = 128 and Y = 0 to set LDX #128 \ the function keys to return ASCII codes for SHIFT-fn JSR OSB \ keys (i.e. add 128) \ --- Mod: Original Acornsoft code removed: -----------> \ LDA #12 \ Set A = 12 and X = 0 to pretend that this is an to \ LDX #0 \ innocent call to OSBYTE to reset the keyboard delay \ \ and auto-repeat rate to the default, when in reality \ \ the OSB address in the next instruction gets modified \ \ to point to OSBmod \ \.OSBjsr \ \ JSR OSB \ This JSR gets modified by code inserted into PLL1 so \ \ that it points to OSBmod instead of OSB, so this \ \ actually calls OSBmod to calculate some checksums \ --- End of removed code -----------------------------> LDA #13 \ Call OSBYTE with A = 13, X = 2 and Y = 0 to disable LDX #2 \ the "character entering buffer" event JSR OSB LDA #4 \ Call OSBYTE with A = 4, X = 1 and Y = 0 to disable LDX #1 \ cursor editing, so the cursor keys return ASCII values JSR OSB \ and can therefore be used in-game LDA #9 \ Call OSBYTE with A = 9, X = 0 and Y = 0 to disable LDX #0 \ flashing colours JSR OSB \ --- Mod: Code added for Elite-A: --------------------> LDA #119 \ Call OSBYTE with A = 119 to close any *SPOOL or *EXEC JSR OSBYTE \ files \ --- End of added code -------------------------------> JSR PROT3 \ Call PROT3 to do more checks on the CHKSM checksum LDA #&00 \ Set the following: STA ZP \ LDA #&11 \ ZP(1 0) = &1100 STA ZP+1 \ P(1 0) = TVT1code LDA #LO(TVT1code) STA P LDA #HI(TVT1code) STA P+1 \ --- Mod: Original Acornsoft code removed: -----------> \ JSR MVPG \ Call MVPG to move and decrypt a page of memory from \ \ TVT1code to &1100-&11FF \ --- And replaced by: --------------------------------> JSR MVPG \ Call MVPG to move a page of memory from TVT1code to \ &1100-&11FF LDA #LO(S%+11) \ Point BRKV to the fifth entry in the main docked STA BRKV \ code's S% workspace, which contains JMP BRBR LDA #HI(S%+11) STA BRKV+1 \ --- End of replacement ------------------------------> LDA #&00 \ Set the following: STA ZP \ LDA #&78 \ ZP(1 0) = &7800 STA ZP+1 \ P(1 0) = DIALS LDA #LO(DIALS) \ X = 8 STA P LDA #HI(DIALS) STA P+1 LDX #8 \ --- Mod: Original Acornsoft code removed: -----------> \ JSR MVBL \ Call MVBL to move and decrypt 8 pages of memory from \ \ DIALS to &7800-&7FFF \ \ SEI \ Disable interrupts while we set up our interrupt \ \ handler to support the split-screen mode \ \ LDA VIA+&44 \ Read the 6522 System VIA T1C-L timer 1 low-order \ STA &0001 \ counter (SHEILA &44), which increments 1000 times a \ \ second so this will be pretty random, and store it in \ \ &0001 among the random number seeds at &0000 \ \ LDA #%00111001 \ Set 6522 System VIA interrupt enable register IER \ STA VIA+&4E \ (SHEILA &4E) bits 0 and 3-5 (i.e. disable the Timer1, \ \ CB1, CB2 and CA2 interrupts from the System VIA) \ \ LDA #%01111111 \ Set 6522 User VIA interrupt enable register IER \ STA VIA+&6E \ (SHEILA &6E) bits 0-7 (i.e. disable all hardware \ \ interrupts from the User VIA) \ \ LDA IRQ1V \ Copy the current IRQ1V vector address into VEC(1 0) \ STA VEC \ LDA IRQ1V+1 \ STA VEC+1 \ \ LDA #LO(IRQ1) \ Set the IRQ1V vector to IRQ1, so IRQ1 is now the \ STA IRQ1V \ interrupt handler \ LDA #HI(IRQ1) \ STA IRQ1V+1 \ \ LDA #VSCAN \ Set 6522 System VIA T1C-L timer 1 high-order counter \ STA VIA+&45 \ (SHEILA &45) to VSCAN (57) to start the T1 counter \ \ counting down from 14622 at a rate of 1 MHz \ \ CLI \ Re-enable interrupts \ --- And replaced by: --------------------------------> JSR MVBL \ Call MVBL to move 8 pages of memory from DIALS to \ &7800-&7FFF \ --- End of replacement ------------------------------> LDA #&00 \ Set the following: STA ZP \ LDA #&61 \ ZP(1 0) = &6100 STA ZP+1 \ P(1 0) = ASOFT LDA #LO(ASOFT) STA P LDA #HI(ASOFT) STA P+1 JSR MVPG \ Call MVPG to move a page of memory from ASOFT to \ &6100-&61FF LDA #&63 \ Set the following: STA ZP+1 \ LDA #LO(ELITE) \ ZP(1 0) = &6300 STA P \ P(1 0) = ELITE LDA #HI(ELITE) STA P+1 JSR MVPG \ Call MVPG to move a page of memory from ELITE to \ &6300-&63FF LDA #&76 \ Set the following: STA ZP+1 \ LDA #LO(CpASOFT) \ ZP(1 0) = &7600 STA P \ P(1 0) = CpASOFT LDA #HI(CpASOFT) STA P+1 \ --- Mod: Original Acornsoft code removed: -----------> \ JSR MVPG \ Call MVPG to move and decrypt a page of memory from \ \ CpASOFT to &7600-&76FF \ \ LDA #&00 \ Set the following: \ STA ZP \ \ LDA #&04 \ ZP(1 0) = &0400 \ STA ZP+1 \ P(1 0) = WORDS \ LDA #LO(WORDS) \ X = 4 \ STA P \ LDA #HI(WORDS) \ STA P+1 \ LDX #4 \ \ JSR MVBL \ Call MVBL to move and decrypt 4 pages of memory from \ \ WORDS to &0400-&07FF \ \ LDX #35 \ We now want to copy the disc catalogue routine from \ \ CATDcode to CATD, so set a counter in X for the 36 \ \ bytes to copy \ \.loop2 \ \ LDA CATDcode,X \ Copy the X-th byte of CATDcode to the X-th byte of \ STA CATD,X \ CATD \ \ DEX \ Decrement the loop counter \ \ BPL loop2 \ Loop back to copy the next byte until they are all \ \ done \ \ LDA &76 \ Set the drive number in the CATD routine to the \ STA CATBLOCK \ contents of &76, which gets set in ELITE3 \ --- And replaced by: --------------------------------> JSR MVPG \ Call MVPG to move a page of memory from CpASOFT to \ &7600-&76FF \ --- End of replacement ------------------------------> FNE 0 \ Set up sound envelopes 0-3 using the FNE macro FNE 1 FNE 2 FNE 3 LDX #LO(MESS1) \ Set (Y X) to point to MESS1 ("DIR E") LDY #HI(MESS1) JSR OSCLI \ Call OSCLI to run the OS command in MESS1, which \ changes the disc directory to E \ --- Mod: Original Acornsoft code removed: -----------> \ LDA #LO(LOAD) \ Set the following: \ STA ZP \ \ LDA #HI(LOAD) \ ZP(1 0) = LOAD \ STA ZP+1 \ P(1 0) = LOADcode \ LDA #LO(LOADcode) \ STA P \ LDA #HI(LOADcode) \ STA P+1 \ \ LDY #0 \ We now want to move and decrypt one page of memory \ \ from LOADcode to LOAD, so set Y as a byte counter \ \.loop3 \ \ LDA (P),Y \ Fetch the Y-th byte of the P(1 0) memory block \ \ EOR #&18 \ Decrypt it by EOR'ing with &18 \ \ STA (ZP),Y \ Store the decrypted result in the Y-th byte of the \ \ ZP(1 0) memory block \ \ DEY \ Decrement the byte counter \ \ BNE loop3 \ Loop back to copy the next byte until we have done a \ \ whole page of 256 bytes \ \ JMP LOAD \ Jump to the start of the routine we just decrypted \ --- And replaced by: --------------------------------> LDA #%11110000 \ Set the Data Direction Register (DDR) of port B of the STA VIA+&62 \ user port so we can read the buttons on the Delta 14b \ joystick, using PB4 to PB7 as output (so we can write \ to the button columns to select the column we are \ interested in) and PB0 to PB3 as input (so we can read \ from the button rows) LDA #0 \ Set HFX = 0 STA HFX STA LASCT \ Set LASCT = 0 LDA #&FF \ Set ESCP = &FF so we show the palette for when we have STA ESCP \ an escape pod fitted (i.e. black, red, white, cyan) SEI \ Disable interrupts while we set up our interrupt \ handler to support the split-screen mode LDA VIA+&44 \ If the STA instruction were not commented out, then \STA &0001 \ this would set location &0001 among the random number \ seeds to a pretty random number (i.e. the value of the \ the 6522 System VIA T1C-L timer 1 low-order counter), \ but as the STA is commented out, this has no effect LDA #%00111001 \ Set 6522 System VIA interrupt enable register IER STA VIA+&4E \ (SHEILA &4E) bits 0 and 3-5 (i.e. disable the Timer1, \ CB1, CB2 and CA2 interrupts from the System VIA) LDA #%01111111 \ Set 6522 User VIA interrupt enable register IER STA VIA+&6E \ (SHEILA &6E) bits 0-7 (i.e. disable all hardware \ interrupts from the User VIA) LDA IRQ1V \ Copy the current IRQ1V vector address into VEC(1 0) STA VEC LDA IRQ1V+1 STA VEC+1 LDA #LO(IRQ1) \ Set the IRQ1V vector to IRQ1, so IRQ1 is now the STA IRQ1V \ interrupt handler LDA #HI(IRQ1) STA IRQ1V+1 LDA #VSCAN \ Set 6522 System VIA T1C-L timer 1 high-order counter STA VIA+&45 \ (SHEILA &45) to VSCAN (57) to start the T1 counter \ counting down from 14622 at a rate of 1 MHz CLI \ Re-enable interrupts LDA #0 \ Call OSBYTE with A = 0 and X = 1 to fetch bit 0 of the LDX #1 \ operating system version into X JSR OSBYTE CPX #3 \ If X =< 3 then this is not a BBC Master, so jump to BCC not_master \ not_master to continue loading the BBC Micro version \ This is a BBC Master, so now we copy the block of \ Master-specific filing system code from to_dd00 to \ &DD00 (so we copy the following routines: do_FILEV, \ do_FSCV, do_BYTEV, set_vectors and old_BYTEV) LDX #0 \ Set up a counter in X for the copy .cpmaster LDA to_dd00,X \ Copy the X-th byte of to_dd00 to &DD00 STA &DD00,X INX \ Increment the loop counter CPX #dd00_len \ Loop back until we have copied all the bytes in the BNE cpmaster \ to_dd00 block (as the length of the block is set in \ dd00_len below) LDA #143 \ Call OSBYTE 143 to issue a paged ROM service call of LDX #&21 \ type &21 with argument &C0, which is the "Indicate LDY #&C0 \ static workspace in 'hidden' RAM" service call. This JSR OSBYTE \ call returns the address of a safe place that we can \ use within the memory bank &C000-&DFFF, and returns \ the start location in (Y X) \ We now modify the savews routine so that when it's \ called, it copies the first three pages from the &C000 \ workspace to this safe place, and then copies the MOS \ character set into the first three pages of &C000, so \ the character printing routines can use them \ We also modify the restorews routine in a similar way, \ so that when it's called, it copies the three pages \ from the safe place back into the first three pages \ of &C000, thus restoring the filing system workspace STX put0+1 \ Modify the low byte of the workspace save address in STX put1+1 \ the savews routine to that of (Y X) STX put2+1 STX get0+1 \ Modify the low byte of the workspace restore address STX get1+1 \ in the restorews routine to that of (Y X) STX get2+1 STY put0+2 \ Modify the high byte of the workspace save address of \ the first page in the savews routine to that of (Y X) STY get0+2 \ Modify the high byte of the workspace restore address \ of the first page in the restorews routine to that of \ (Y X) INY \ Increment Y so that (Y X) points to the second page, \ i.e. (Y+1 X) STY put1+2 \ Modify the high byte of the workspace save address of \ the second page in the savews routine to (Y+1 X) STY get1+2 \ Modify the high byte of the workspace restore address \ of the second page in the restorews routine to that of \ (Y+1 X) INY \ Increment Y so that (Y X) points to the third page, \ i.e. (Y+2 X) STY put2+2 \ Modify the high byte of the workspace save address of \ the third page in the savews routine to (Y+2 X) STY get2+2 \ Modify the high byte of the workspace restore address \ of the third page in the restorews routine to that of \ (Y+2 X) LDA FILEV \ Set old_FILEV(1 0) to the existing address for FILEV STA old_FILEV+1 \ (this modifies the JMP instruction in the do_FILEV LDA FILEV+1 \ routine) STA old_FILEV+2 LDA FSCV \ Set old_FSCV(1 0) to the existing address for FSCV STA old_FSCV+1 \ (this modifies the JMP instruction in the do_FILEV LDA FSCV+1 \ routine) STA old_FSCV+2 LDA BYTEV \ Set old_BYTEV(1 0) to the existing address for BYTEV STA old_BYTEV+1 \ (this modifies the JMP instruction in the old_BYTEV LDA BYTEV+1 \ routine) STA old_BYTEV+2 JSR set_vectors \ Call set_vectors to update FILEV, FSCV and BYTEV to \ point to the new handlers in do_FILEV, do_FSCV and \ do_BYTEV .not_master LDA #234 \ Call OSBYTE with A = 234, X = 0 and Y = &FF, which LDY #&FF \ detects whether Tube hardware is present, returning LDX #0 \ X = 0 (not present) or X = &FF (present) JSR OSBYTE TXA \ Copy the result of the Tube check from X into A BNE tube_go \ If X is non-zero then we are running this over the \ Tube, so jump to tube_go to set up the Tube version \ If we get here then we are not running on a 6502 \ Second Processor LDA #172 \ Call OSBYTE 172 to read the address of the MOS LDX #0 \ keyboard translation table into (Y X) LDY #&FF JSR OSBYTE STX TRTB% \ Store the address of the keyboard translation table in STY TRTB%+1 \ TRTB%(1 0) LDA #&00 \ Set the following: STA ZP \ LDA #&04 \ ZP(1 0) = &0400 STA ZP+1 \ P(1 0) = WORDS LDA #LO(WORDS) \ X = 4 STA P LDA #HI(WORDS) STA P+1 LDX #4 JSR MVBL \ Call MVBL to move 4 pages of memory from WORDS to \ &0400-&07FF LDA #LO(S%+6) \ Point WRCHV to the third entry in the main docked STA WRCHV \ code's S% workspace, which contains JMP CHPR LDA #HI(S%+6) STA WRCHV+1 LDA #LO(LOAD) \ Set the following: STA ZP \ LDA #HI(LOAD) \ ZP(1 0) = LOAD STA ZP+1 \ P(1 0) = LOADcode LDA #LO(LOADcode) STA P LDA #HI(LOADcode) STA P+1 JSR MVPG \ Call MVPG to move a page of memory from LOADcode to \ LOAD LDY #35 \ We now want to copy the iff_index routine from \ iff_index_code to iff_index, so set a counter in Y \ for the 36 bytes to copy .copy_d7a LDA iff_index_code,Y \ Copy the X-th byte of iff_index_code to the X-th byte STA iff_index,Y \ of iff_index DEY \ Decrement the loop counter BPL copy_d7a \ Loop back to copy the next byte until they are all \ done JMP LOAD \ Jump to the start of the LOAD routine we moved above, \ to run the game .tube_go LDA #172 \ Call OSBYTE 172 to read the address of the MOS LDX #0 \ keyboard translation table into (Y X) LDY #&FF JSR OSBYTE STX key_tube \ Store the address of the keyboard translation table in STY key_tube+1 \ key_tube(1 0) \LDX #LO(tube_400) \ These instructions are commented out in the original \LDY #HI(tube_400) \ source \LDA #1 \JSR &0406 \LDA #LO(WORDS) \STA &72 \LDA #HI(WORDS) \STA &73 \LDX #&04 \LDY #&00 \.tube_wr \LDA (&72),Y \JSR tube_wait \BIT tube_r3s \BVC tube_wr \STA tube_r3d \INY \BNE tube_wr \INC &73 \DEX \BNE tube_wr \LDA #LO(tube_wrch) \STA WRCHV \LDA #HI(tube_wrch) \STA WRCHV+&01 LDX #LO(tube_run) \ Set (Y X) to point to tube_run ("R.2.H") LDY #HI(tube_run) JMP OSCLI \ Call OSCLI to run the OS command in tube_run, which \ runs the I/O processor code in 2.H .tube_run EQUS "R.2.H" \ The OS command for running the Tube version's I/O EQUB 13 \ processor code in file 2.H (this command is short for \ "*RUN 2.H") \.tube_400 \ These instructions are commented out in the original \EQUD &0400 \ source \.tube_wait \JSR tube_wait2 \.tube_wait2 \JSR tube_wait3 \.tube_wait3 \RTS \ --- End of replacement ------------------------------> \ ****************************************************************************** \ \ Name: iff_index_code \ Type: Subroutine \ Category: Dashboard \ Summary: The iff_index routine, bundled up in the loader so it can be moved \ to &0D7A to be run \ \ ****************************************************************************** .iff_index_code ORG &0D7A \ ****************************************************************************** \ \ Name: iff_index \ Type: Subroutine \ Category: Dashboard \ Summary: Return the type index for this ship in the I.F.F. system \ Deep dive: The I.F.F. system \ \ ------------------------------------------------------------------------------ \ \ This routine is copied to &0D7A in part 1 above. \ \ Returns: \ \ X The index for the current ship in the I.F.F. system: \ \ * 0 = Clean \ Innocent trader, innocent bounty hunter \ \ * 1 = Station tracked \ Cop, space station, escape pod \ \ * 2 = Debris \ Cargo, alloy plate, asteroid, boulder, splinter \ \ * 3 = Missile \ \ * 4 = Offender/fugitive \ Pirate, non-innocent bounty hunter \ \ If there is no I.F.F. system fitted, the index returned \ in X is always 0 \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .iff_index LDX CRGO \ If we do not have an I.F.F. system fitted (i.e. CRGO BEQ iff_not \ is zero), jump to iff_not to return from the routine \ with X = 0 \ If we get here then X = &FF (as CRGO is &FF if we have \ an I.F.F. system fitted) LDY #36 \ Set A to byte #36 of the ship's blueprint, i.e. the LDA (INF),Y \ NEWB flags ASL A \ If bit 6 is set, i.e. this is a cop, a space station ASL A \ or an escape pod, jump to iff_cop to return X = 1 BCS iff_cop ASL A \ If bit 5 is set, i.e. this is an innocent bystander BCS iff_trade \ (which applies to traders and some bounty hunters), \ jump to iff_trade to return X = 0 LDY TYPE \ Set Y to the ship's type - 1 DEY BEQ iff_missle \ If Y = 0, i.e. this is a missile, then jump to \ iff_missle to return X = 3 CPY #8 \ If Y < 8, i.e. this is a cargo canister, alloy plate, BCC iff_aster \ boulder, asteroid or splinter, then jump to iff_aster \ to return X = 2 \ If we get here then the ship is not the following: \ \ * A cop/station/escape pod \ * An innocent bystander/trader/good bounty hunter \ * A missile \ * Cargo or an asteroid \ \ So it must be a pirate or a non-innocent bounty hunter INX \ X is &FF at this point, so this INX sets X = 0, and we \ then fall through into the four INX instructions below \ to return X = 4 .iff_missle INX \ If we jump to this point, then return X = 3 .iff_aster INX \ If we jump to this point, then return X = 2 .iff_cop INX \ If we jump to this point, then return X = 1 .iff_trade INX \ If we jump to this point, then return X = 0 .iff_not RTS \ Return from the subroutine \ --- End of added section ----------------------------> COPYBLOCK iff_index, P%, iff_index_code ORG iff_index_code + P% - iff_index \ ****************************************************************************** \ \ Name: LOADcode \ Type: Subroutine \ Category: Loader \ Summary: Encrypted LOAD routine, bundled up in the loader so it can be \ moved to &0B00 to be run \ \ ****************************************************************************** .LOADcode ORG &0B00 \ ****************************************************************************** \ \ Name: LOAD \ Type: Subroutine \ Category: Loader \ Summary: Load the main docked code, set up various vectors, run a checksum \ and start the game \ \ ****************************************************************************** .LOAD \ --- Mod: Original Acornsoft code removed: -----------> \ LDX #LO(LTLI) \ Set (Y X) to point to LTLI ("L.T.CODE") \ LDY #HI(LTLI) \ \ JSR OSCLI \ Call OSCLI to run the OS command in LTLI, which loads \ \ the T.CODE binary (the main docked code) to its load \ \ address of &11E3 \ \ LDA #LO(S%+11) \ Point BRKV to the fifth entry in the main docked \ STA BRKV \ code's S% workspace, which contains JMP BRBR1 \ LDA #HI(S%+11) \ STA BRKV+1 \ \ LDA #LO(S%+6) \ Point WRCHV to the third entry in the main docked \ STA WRCHV \ code's S% workspace, which contains JMP CHPR \ LDA #HI(S%+6) \ STA WRCHV+1 \ \ SEC \ Set the C flag so the checksum we calculate in A \ \ starts with an initial value of 18 (17 plus carry) \ \ LDY #0 \ Set Y = 0 to act as a byte pointer \ \ STY ZP \ Set the low byte of ZP(1 0) to 0, so ZP(1 0) always \ \ points to the start of a page \ \ LDX #&11 \ Set X = &11, so ZP(1 0) will point to &1100 when we \ \ stick X in ZP+1 below \ \ TXA \ Set A = &11 = 17, to set the intial value of the \ \ checksum to 18 (17 plus carry) \ \.l1 \ \ STX ZP+1 \ Set the high byte of ZP(1 0) to the page number in X \ \ ADC (ZP),Y \ Set A = A + the Y-th byte of ZP(1 0) \ \ DEY \ Decrement the byte pointer \ \ BNE l1 \ Loop back to add the next byte until we have added the \ \ whole page \ \ INX \ Increment the page number in X \ \ CPX #&54 \ Loop back to checksum the next page until we have \ BCC l1 \ checked up to (but not including) page &54 \ \ CMP &55FF \ Compare the checksum with the value in &55FF, which is \ \ in the docked file we just loaded, in the byte before \ \ the ship hanger blueprints at XX21 \ \IF _REMOVE_CHECKSUMS \ \ NOP \ If we have disabled checksums, then ignore the result \ NOP \ of the checksum comparison \ \ELSE \ \ BNE P% \ If the checksums don't match then enter an infinite \ \ loop, which hangs the computer \ \ENDIF \ --- And replaced by: --------------------------------> LDX #LO(LTLI) \ Set (Y X) to point to LTLI ("L.1.D") LDY #HI(LTLI) JSR OSCLI \ Call OSCLI to run the OS command in LTLI, which loads \ the 1.D binary (the main docked code) to its load \ address of &11E3 \ --- End of replacement ------------------------------> JMP S%+3 \ Jump to the second entry in the main docked code's S% \ workspace to start a new game .LTLI \ --- Mod: Original Acornsoft code removed: -----------> \ EQUS "L.T.CODE" \ This is short for "*LOAD T.CODE" \ EQUB 13 \ \ EQUS "Does your mother know you do this?" \ --- And replaced by: --------------------------------> EQUS "L.1.D" \ This is short for "*LOAD 1.D" EQUB 13 \ --- End of replacement ------------------------------> COPYBLOCK LOAD, P%, LOADcode ORG LOADcode + P% - LOAD \ ****************************************************************************** \ \ Name: PLL1 \ Type: Subroutine \ Category: Drawing planets \ Summary: Draw Saturn on the loading screen \ Deep dive: Drawing Saturn on the loading screen \ \ ****************************************************************************** .PLL1 \ The following loop iterates CNT(1 0) times, i.e. &300 \ or 768 times, and draws the planet part of the \ loading screen's Saturn LDA VIA+&44 \ Read the 6522 System VIA T1C-L timer 1 low-order STA RAND+1 \ counter (SHEILA &44), which increments 1000 times a \ second so this will be pretty random, and store it in \ RAND+1 among the hard-coded random seeds in RAND JSR DORND \ Set A and X to random numbers, say A = r1 JSR SQUA2 \ Set (A P) = A * A \ = r1^2 STA ZP+1 \ Set ZP(1 0) = (A P) LDA P \ = r1^2 STA ZP \ --- Mod: Original Acornsoft code removed: -----------> \ LDA #LO(OSBmod) \ As part of the copy protection, the JSR OSB \ STA OSBjsr+1 \ instruction at OSBjsr gets modified to point to OSBmod \ \ instead of OSB, and this is where we modify the low \ \ byte of the destination address \ --- End of removed code -----------------------------> JSR DORND \ Set A and X to random numbers, say A = r2 STA YY \ Set YY = A \ = r2 JSR SQUA2 \ Set (A P) = A * A \ = r2^2 TAX \ Set (X P) = (A P) \ = r2^2 LDA P \ Set (A ZP) = (X P) + ZP(1 0) ADC ZP \ STA ZP \ first adding the low bytes TXA \ And then adding the high bytes ADC ZP+1 BCS PLC1 \ If the addition overflowed, jump down to PLC1 to skip \ to the next pixel STA ZP+1 \ Set ZP(1 0) = (A ZP) \ = r1^2 + r2^2 LDA #1 \ Set ZP(1 0) = &4001 - ZP(1 0) - (1 - C) SBC ZP \ = 128^2 - ZP(1 0) STA ZP \ \ (as the C flag is clear), first subtracting the low \ bytes LDA #&40 \ And then subtracting the high bytes SBC ZP+1 STA ZP+1 BCC PLC1 \ If the subtraction underflowed, jump down to PLC1 to \ skip to the next pixel \ If we get here, then both calculations fitted into \ 16 bits, and we have: \ \ ZP(1 0) = 128^2 - (r1^2 + r2^2) \ \ where ZP(1 0) >= 0 JSR ROOT \ Set ZP = SQRT(ZP(1 0)) LDA ZP \ Set X = ZP >> 1 LSR A \ = SQRT(128^2 - (a^2 + b^2)) / 2 TAX LDA YY \ Set A = YY \ = r2 CMP #128 \ If YY >= 128, set the C flag (so the C flag is now set \ to bit 7 of A) ROR A \ Rotate A and set the sign bit to the C flag, so bits \ 6 and 7 are now the same, i.e. A is a random number in \ one of these ranges: \ \ %00000000 - %00111111 = 0 to 63 (r2 = 0 - 127) \ %11000000 - %11111111 = 192 to 255 (r2 = 128 - 255) \ \ The PIX routine flips bit 7 of A before drawing, and \ that makes -A in these ranges: \ \ %10000000 - %10111111 = 128-191 \ %01000000 - %01111111 = 64-127 \ \ so that's in the range 64 to 191 JSR PIX \ Draw a pixel at screen coordinate (X, -A), i.e. at \ \ (ZP / 2, -A) \ \ where ZP = SQRT(128^2 - (r1^2 + r2^2)) \ \ So this is the same as plotting at (x, y) where: \ \ r1 = random number from 0 to 255 \ r1 = random number from 0 to 255 \ (r1^2 + r1^2) < 128^2 \ \ y = r2, squished into 64 to 191 by negation \ \ x = SQRT(128^2 - (r1^2 + r1^2)) / 2 \ \ which is what we want .PLC1 DEC CNT \ Decrement the counter in CNT (the low byte) BNE PLL1 \ Loop back to PLL1 until CNT = 0 DEC CNT+1 \ Decrement the counter in CNT+1 (the high byte) BNE PLL1 \ Loop back to PLL1 until CNT+1 = 0 \ The following loop iterates CNT2(1 0) times, i.e. &1DD \ or 477 times, and draws the background stars on the \ loading screen .PLL2 JSR DORND \ Set A and X to random numbers, say A = r3 TAX \ Set X = A \ = r3 JSR SQUA2 \ Set (A P) = A * A \ = r3^2 STA ZP+1 \ Set ZP+1 = A \ = r3^2 / 256 JSR DORND \ Set A and X to random numbers, say A = r4 STA YY \ Set YY = r4 JSR SQUA2 \ Set (A P) = A * A \ = r4^2 ADC ZP+1 \ Set A = A + r3^2 / 256 \ = r4^2 / 256 + r3^2 / 256 \ = (r3^2 + r4^2) / 256 CMP #&11 \ If A < 17, jump down to PLC2 to skip to the next pixel BCC PLC2 LDA YY \ Set A = r4 JSR PIX \ Draw a pixel at screen coordinate (X, -A), i.e. at \ (r3, -r4), where (r3^2 + r4^2) / 256 >= 17 \ \ Negating a random number from 0 to 255 still gives a \ random number from 0 to 255, so this is the same as \ plotting at (x, y) where: \ \ x = random number from 0 to 255 \ y = random number from 0 to 255 \ (x^2 + y^2) div 256 >= 17 \ \ which is what we want .PLC2 DEC CNT2 \ Decrement the counter in CNT2 (the low byte) BNE PLL2 \ Loop back to PLL2 until CNT2 = 0 DEC CNT2+1 \ Decrement the counter in CNT2+1 (the high byte) BNE PLL2 \ Loop back to PLL2 until CNT2+1 = 0 \ The following loop iterates CNT3(1 0) times, i.e. &333 \ or 819 times, and draws the rings around the loading \ screen's Saturn .PLL3 JSR DORND \ Set A and X to random numbers, say A = r5 STA ZP \ Set ZP = r5 JSR SQUA2 \ Set (A P) = A * A \ = r5^2 STA ZP+1 \ Set ZP+1 = A \ = r5^2 / 256 \ --- Mod: Original Acornsoft code removed: -----------> \ LDA #HI(OSBmod) \ As part of the copy protection, the JSR OSB \ STA OSBjsr+2 \ instruction at OSBjsr gets modified to point to OSBmod \ \ instead of OSB, and this is where we modify the high \ \ byte of the destination address \ --- End of removed code -----------------------------> JSR DORND \ Set A and X to random numbers, say A = r6 STA YY \ Set YY = r6 JSR SQUA2 \ Set (A P) = A * A \ = r6^2 STA T \ Set T = A \ = r6^2 / 256 ADC ZP+1 \ Set ZP+1 = A + r5^2 / 256 STA ZP+1 \ = r6^2 / 256 + r5^2 / 256 \ = (r5^2 + r6^2) / 256 LDA ZP \ Set A = ZP \ = r5 CMP #128 \ If A >= 128, set the C flag (so the C flag is now set \ to bit 7 of ZP, i.e. bit 7 of A) ROR A \ Rotate A and set the sign bit to the C flag, so bits \ 6 and 7 are now the same CMP #128 \ If A >= 128, set the C flag (so again, the C flag is \ set to bit 7 of A) ROR A \ Rotate A and set the sign bit to the C flag, so bits \ 5-7 are now the same, i.e. A is a random number in one \ of these ranges: \ \ %00000000 - %00011111 = 0-31 \ %11100000 - %11111111 = 224-255 \ \ In terms of signed 8-bit integers, this is a random \ number from -32 to 31. Let's call it r7 ADC YY \ Set X = A + YY TAX \ = r7 + r6 JSR SQUA2 \ Set (A P) = r7 * r7 TAY \ Set Y = A \ = r7 * r7 / 256 ADC ZP+1 \ Set A = A + ZP+1 \ = r7^2 / 256 + (r5^2 + r6^2) / 256 \ = (r5^2 + r6^2 + r7^2) / 256 BCS PLC3 \ If the addition overflowed, jump down to PLC3 to skip \ to the next pixel CMP #80 \ If A >= 80, jump down to PLC3 to skip to the next BCS PLC3 \ pixel CMP #32 \ If A < 32, jump down to PLC3 to skip to the next pixel BCC PLC3 TYA \ Set A = Y + T ADC T \ = r7^2 / 256 + r6^2 / 256 \ = (r6^2 + r7^2) / 256 CMP #16 \ If A > 16, skip to PL1 to plot the pixel BCS PL1 LDA ZP \ If ZP is positive (50% chance), jump down to PLC3 to BPL PLC3 \ skip to the next pixel .PL1 LDA YY \ Set A = YY \ = r6 JSR PIX \ Draw a pixel at screen coordinate (X, -A), where: \ \ X = (random -32 to 31) + r6 \ A = r6 \ \ Negating a random number from 0 to 255 still gives a \ random number from 0 to 255, so this is the same as \ plotting at (x, y) where: \ \ r5 = random number from 0 to 255 \ r6 = random number from 0 to 255 \ r7 = r5, squashed into -32 to 31 \ \ x = r5 + r7 \ y = r5 \ \ 32 <= (r5^2 + r6^2 + r7^2) / 256 <= 79 \ Draw 50% fewer pixels when (r6^2 + r7^2) / 256 <= 16 \ \ which is what we want .PLC3 DEC CNT3 \ Decrement the counter in CNT3 (the low byte) BNE PLL3 \ Loop back to PLL3 until CNT3 = 0 DEC CNT3+1 \ Decrement the counter in CNT3+1 (the high byte) BNE PLL3 \ Loop back to PLL3 until CNT3+1 = 0 LDA #&00 \ Set ZP(1 0) = &6300 STA ZP LDA #&63 STA ZP+1 LDA #&62 \ Set P(1 0) = &2A62 STA P LDA #&2A STA P+1 LDX #8 \ Call MVPG with X = 8 to copy 8 pages of memory from JSR MVPG \ the address in P(1 0) to the address in ZP(1 0) \ ****************************************************************************** \ \ Name: DORND \ Type: Subroutine \ Category: Utility routines \ Summary: Generate random numbers \ Deep dive: Generating random numbers \ Fixing ship positions \ \ ------------------------------------------------------------------------------ \ \ Set A and X to random numbers (though note that X is set to the random number \ that was returned in A the last time DORND was called). \ \ The C and V flags are also set randomly. \ \ This is a simplified version of the DORND routine in the main game code. It \ swaps the two calculations around and omits the ROL A instruction, but is \ otherwise very similar. See the DORND routine in the main game code for more \ details. \ \ ****************************************************************************** .DORND LDA RAND+1 \ r1´ = r1 + r3 + C TAX \ r3´ = r1 ADC RAND+3 STA RAND+1 STX RAND+3 LDA RAND \ X = r2´ = r0 TAX \ A = r0´ = r0 + r2 ADC RAND+2 STA RAND STX RAND+2 RTS \ Return from the subroutine \ ****************************************************************************** \ \ Name: RAND \ Type: Variable \ Category: Drawing planets \ Summary: The random number seed used for drawing Saturn \ \ ****************************************************************************** .RAND EQUD &34785349 \ ****************************************************************************** \ \ Name: SQUA2 \ Type: Subroutine \ Category: Maths (Arithmetic) \ Summary: Calculate (A P) = A * A \ \ ------------------------------------------------------------------------------ \ \ Do the following multiplication of unsigned 8-bit numbers: \ \ (A P) = A * A \ \ This uses the same approach as routine SQUA2 in the main game code, which \ itself uses the MU11 routine to do the multiplication. See those routines for \ more details. \ \ ****************************************************************************** .SQUA2 BPL SQUA \ If A > 0, jump to SQUA EOR #&FF \ Otherwise we need to negate A for the SQUA algorithm CLC \ to work, so we do this using two's complement, by ADC #1 \ setting A = ~A + 1 .SQUA STA Q \ Set Q = A and P = A STA P \ Set P = A LDA #0 \ Set A = 0 so we can start building the answer in A LDY #8 \ Set up a counter in Y to count the 8 bits in P LSR P \ Set P = P >> 1 \ and C flag = bit 0 of P .SQL1 BCC SQ1 \ If C (i.e. the next bit from P) is set, do the CLC \ addition for this bit of P: ADC Q \ \ A = A + Q .SQ1 ROR A \ Shift A right to catch the next digit of our result, \ which the next ROR sticks into the left end of P while \ also extracting the next bit of P ROR P \ Add the overspill from shifting A to the right onto \ the start of P, and shift P right to fetch the next \ bit for the calculation into the C flag DEY \ Decrement the loop counter BNE SQL1 \ Loop back for the next bit until P has been rotated \ all the way RTS \ Return from the subroutine \ ****************************************************************************** \ \ Name: PIX \ Type: Subroutine \ Category: Drawing pixels \ Summary: Draw a single pixel at a specific coordinate \ \ ------------------------------------------------------------------------------ \ \ Draw a pixel at screen coordinate (X, -A). The sign bit of A gets flipped \ before drawing, and then the routine uses the same approach as the PIXEL \ routine in the main game code, except it plots a single pixel from TWOS \ instead of a two pixel dash from TWOS2. This applies to the top part of the \ screen (the monochrome mode 4 space view). \ \ See the PIXEL routine in the main game code for more details. \ \ Arguments: \ \ X The screen x-coordinate of the pixel to draw \ \ A The screen y-coordinate of the pixel to draw, negated \ \ Other entry points: \ \ out Contains an RTS \ \ ****************************************************************************** .PIX TAY \ Copy A into Y, for use later EOR #%10000000 \ Flip the sign of A LSR A \ Set A = A >> 3 LSR A LSR A LSR CHKSM+1 \ Rotate the high byte of CHKSM+1 to the right, as part \ of the copy protection ORA #&60 \ Set ZP+1 = &60 + A >> 3 STA ZP+1 TXA \ Set ZP = (X >> 3) * 8 EOR #%10000000 AND #%11111000 STA ZP TYA \ Set Y = Y AND %111 AND #%00000111 TAY TXA \ Set X = X AND %111 AND #%00000111 TAX LDA TWOS,X \ Fetch a pixel from TWOS and poke it into ZP+Y STA (ZP),Y .out RTS \ Return from the subroutine \ ****************************************************************************** \ \ Name: TWOS \ Type: Variable \ Category: Drawing pixels \ Summary: Ready-made single-pixel character row bytes for mode 4 \ \ ------------------------------------------------------------------------------ \ \ Ready-made bytes for plotting one-pixel points in mode 4 (the top part of the \ split screen). See the PIX routine for details. \ \ ****************************************************************************** .TWOS EQUB %10000000 EQUB %01000000 EQUB %00100000 EQUB %00010000 EQUB %00001000 EQUB %00000100 EQUB %00000010 EQUB %00000001 \ ****************************************************************************** \ \ Name: CNT \ Type: Variable \ Category: Drawing planets \ Summary: A counter for use in drawing Saturn's planetary body \ \ ------------------------------------------------------------------------------ \ \ Defines the number of iterations of the PLL1 loop, which draws the planet part \ of the loading screen's Saturn. \ \ ****************************************************************************** .CNT EQUW &0300 \ The number of iterations of the PLL1 loop (768) \ ****************************************************************************** \ \ Name: CNT2 \ Type: Variable \ Category: Drawing planets \ Summary: A counter for use in drawing Saturn's background stars \ \ ------------------------------------------------------------------------------ \ \ Defines the number of iterations of the PLL2 loop, which draws the background \ stars on the loading screen. \ \ ****************************************************************************** .CNT2 EQUW &01DD \ The number of iterations of the PLL2 loop (477) \ ****************************************************************************** \ \ Name: CNT3 \ Type: Variable \ Category: Drawing planets \ Summary: A counter for use in drawing Saturn's rings \ \ ------------------------------------------------------------------------------ \ \ Defines the number of iterations of the PLL3 loop, which draws the rings \ around the loading screen's Saturn. \ \ ****************************************************************************** .CNT3 EQUW &0333 \ The number of iterations of the PLL3 loop (819) \ ****************************************************************************** \ \ Name: PROT3 \ Type: Subroutine \ Category: Copy protection \ Summary: Part of the CHKSM copy protection checksum calculation \ \ ****************************************************************************** .PROT3 LDA CHKSM \ Update the checksum AND CHKSM+1 ORA #&0C ASL A STA CHKSM RTS \ Return from the subroutine \ --- Mod: Original Acornsoft code removed: -----------> \ JMP P% \ This would hang the computer, but we never get here as \ \ the checksum code has been disabled \ --- End of removed code -----------------------------> \ ****************************************************************************** \ \ Name: ROOT \ Type: Subroutine \ Category: Maths (Arithmetic) \ Summary: Calculate ZP = SQRT(ZP(1 0)) \ \ ------------------------------------------------------------------------------ \ \ Calculate the following square root: \ \ ZP = SQRT(ZP(1 0)) \ \ This routine is identical to LL5 in the main game code - it even has the same \ label names. The only difference is that LL5 calculates Q = SQRT(R Q), but \ apart from the variables used, the instructions are identical, so see the LL5 \ routine in the main game code for more details on the algorithm used here. \ \ ****************************************************************************** .ROOT LDY ZP+1 \ Set (Y Q) = ZP(1 0) LDA ZP STA Q \ So now to calculate ZP = SQRT(Y Q) LDX #0 \ Set X = 0, to hold the remainder STX ZP \ Set ZP = 0, to hold the result LDA #8 \ Set P = 8, to use as a loop counter STA P .LL6 CPX ZP \ If X < ZP, jump to LL7 BCC LL7 BNE LL8 \ If X > ZP, jump to LL8 CPY #64 \ If Y < 64, jump to LL7 with the C flag clear, BCC LL7 \ otherwise fall through into LL8 with the C flag set .LL8 TYA \ Set Y = Y - 64 SBC #64 \ TAY \ This subtraction will work as we know C is set from \ the BCC above, and the result will not underflow as we \ already checked that Y >= 64, so the C flag is also \ set for the next subtraction TXA \ Set X = X - ZP SBC ZP TAX .LL7 ROL ZP \ Shift the result in Q to the left, shifting the C flag \ into bit 0 and bit 7 into the C flag ASL Q \ Shift the dividend in (Y S) to the left, inserting TYA \ bit 7 from above into bit 0 ROL A TAY TXA \ Shift the remainder in X to the left ROL A TAX ASL Q \ Shift the dividend in (Y S) to the left TYA ROL A TAY TXA \ Shift the remainder in X to the left ROL A TAX DEC P \ Decrement the loop counter BNE LL6 \ Loop back to LL6 until we have done 8 loops RTS \ Return from the subroutine \ ****************************************************************************** \ \ Name: OSB \ Type: Subroutine \ Category: Utility routines \ Summary: A convenience routine for calling OSBYTE with Y = 0 \ \ ****************************************************************************** .OSB LDY #0 \ Call OSBYTE with Y = 0, returning from the subroutine JMP OSBYTE \ using a tail call (so we can call OSB to call OSBYTE \ for when we know we want Y set to 0) \ ****************************************************************************** \ \ Name: MVPG \ Type: Subroutine \ Category: Utility routines \ Summary: Move a page of memory \ \ ------------------------------------------------------------------------------ \ \ Arguments: \ \ P(1 0) The source address of the page to move \ \ ZP(1 0) The destination address of the page to move \ \ ****************************************************************************** .MVPG LDY #0 \ We want to move one page of memory, so set Y as a byte \ counter .MPL LDA (P),Y \ Fetch the Y-th byte of the P(1 0) memory block \ --- Mod: Original Acornsoft code removed: -----------> \ EOR #&A5 \ Decrypt it by EOR'ing with &A5 \ --- End of removed code -----------------------------> STA (ZP),Y \ Store the result in the Y-th byte of the ZP(1 0) \ memory block DEY \ Decrement the byte counter BNE MPL \ Loop back to copy the next byte until we have done a \ whole page of 256 bytes RTS \ Return from the subroutine \ ****************************************************************************** \ \ Name: MVBL \ Type: Subroutine \ Category: Utility routines \ Summary: Move a multi-page block of memory \ \ ------------------------------------------------------------------------------ \ \ Arguments: \ \ P(1 0) The source address of the block to move \ \ ZP(1 0) The destination address of the block to move \ \ X Number of pages of memory to move (1 page = 256 bytes) \ \ ****************************************************************************** .MVBL JSR MVPG \ Call MVPG above to copy one page of memory from the \ address in P(1 0) to the address in ZP(1 0) INC ZP+1 \ Increment the high byte of the source address to point \ to the next page INC P+1 \ Increment the high byte of the destination address to \ point to the next page DEX \ Decrement the page counter BNE MVBL \ Loop back to copy the next page until we have done X \ pages RTS \ Return from the subroutine \ ****************************************************************************** \ \ Name: MESS1 \ Type: Variable \ Category: Loader \ Summary: The OS command string for changing the disc directory to E \ \ ****************************************************************************** .MESS1 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUS "*DIR E" \ EQUB 13 \ --- And replaced by: --------------------------------> EQUS "DIR e" EQUB 13 \ --- End of replacement ------------------------------> \ ****************************************************************************** \ \ Name: Elite loader (Part 2 of 3) \ Type: Subroutine \ Category: Loader \ Summary: Include binaries for recursive tokens, Missile blueprint and \ images \ \ ------------------------------------------------------------------------------ \ \ The loader bundles a number of binary files in with the loader code, and moves \ them to their correct memory locations in part 1 above. \ \ There are two files containing code: \ \ * WORDS.bin contains the recursive token table, which is moved to &0400 \ before the main game is loaded \ \ * MISSILE.bin contains the missile ship blueprint, which gets moved to &7F00 \ before the main game is loaded \ \ and one file containing an image, which is moved into screen memory by the \ loader: \ \ * P.DIALS.bin contains the dashboard, which gets moved to screen address \ &7800, which is the starting point of the four-colour mode 5 portion at \ the bottom of the split screen \ \ There are three other image binaries bundled into the loader, which are \ described in part 3 below. \ \ ****************************************************************************** .DIALS INCBIN "1-source-files/images/P.DIALS.bin" .SHIP_MISSILE INCBIN "3-assembled-output/MISSILE.bin" .WORDS INCBIN "3-assembled-output/WORDS.bin" \ ****************************************************************************** \ \ Name: TVT1code \ Type: Subroutine \ Category: Loader \ Summary: Code block at &1100-&11E2 that remains resident in both docked and \ flight mode (palettes, screen mode routine and commander data) \ \ ****************************************************************************** .TVT1code ORG &1100 \ ****************************************************************************** \ \ Name: TVT1 \ Type: Variable \ Category: Screen mode \ Summary: Palette data for space and the two dashboard colour schemes \ \ ------------------------------------------------------------------------------ \ \ Palette bytes for use with the split-screen mode (see IRQ1 below for more \ details). \ \ Palette data is given as a set of bytes, with each byte mapping a logical \ colour to a physical one. In each byte, the logical colour is given in bits \ 4-7 and the physical colour in bits 0-3. See p.379 of the Advanced User Guide \ for details of how palette mapping works, as in modes 4 and 5 we have to do \ multiple palette commands to change the colours correctly, and the physical \ colour value is EOR'd with 7, just to make things even more confusing. \ \ Similarly, the palette at TVT1+16 is for the monochrome space view, where \ logical colour 1 is mapped to physical colour 0 EOR 7 = 7 (white), and \ logical colour 0 is mapped to physical colour 7 EOR 7 = 0 (black). Each of \ these mappings requires six calls to SHEILA &21 - see p.379 of the Advanced \ User Guide for an explanation. \ \ The mode 5 palette table has two blocks which overlap. The block used depends \ on whether or not we have an escape pod fitted. The block at TVT1 is used for \ the standard dashboard colours, while TVT1+8 is used for the dashboard when an \ escape pod is fitted. The colours are as follows: \ \ Normal (TVT1) Escape pod (TVT1+8) \ \ Colour 0 Black Black \ Colour 1 Red Red \ Colour 2 Yellow White \ Colour 3 Green Cyan \ \ ****************************************************************************** .TVT1 EQUB &D4, &C4 \ This block of palette data is used to create two EQUB &94, &84 \ palettes used in three different places, all of them EQUB &F5, &E5 \ redefining four colours in mode 5: EQUB &B5, &A5 \ \ 12 bytes from TVT1 (i.e. the first 6 rows): applied EQUB &76, &66 \ when the T1 timer runs down at the switch from the EQUB &36, &26 \ space view to the dashboard, so this is the standard \ dashboard palette EQUB &E1, &F1 \ EQUB &B1, &A1 \ 8 bytes from TVT1+8 (i.e. the last 4 rows): applied \ when the T1 timer runs down at the switch from the \ space view to the dashboard, and we have an escape \ pod fitted, so this is the escape pod dashboard \ palette \ \ 8 bytes from TVT1+8 (i.e. the last 4 rows): applied \ at vertical sync in LINSCN when HFX is non-zero, to \ create the hyperspace effect in LINSCN (where the \ whole screen is switched to mode 5 at vertical sync) EQUB &F0, &E0 \ 12 bytes of palette data at TVT1+16, used to set the EQUB &B0, &A0 \ mode 4 palette in LINSCN when we hit vertical sync, EQUB &D0, &C0 \ so the palette is set to monochrome when we start to EQUB &90, &80 \ draw the first row of the screen EQUB &77, &67 EQUB &37, &27 \ ****************************************************************************** \ \ Name: IRQ1 \ Type: Subroutine \ Category: Screen mode \ Summary: The main screen-mode interrupt handler (IRQ1V points here) \ Deep dive: The split-screen mode \ \ ------------------------------------------------------------------------------ \ \ The main interrupt handler, which implements Elite's split-screen mode (see \ the deep dive on "The split-screen mode" for details). \ \ IRQ1V is set to point to IRQ1 by the loading process. \ \ ****************************************************************************** .LINSCN \ This is called from the interrupt handler below, at \ the start of each vertical sync (i.e. when the screen \ refresh starts) LDA #30 \ Set the line scan counter to a non-zero value, so STA DL \ routines like WSCAN can set DL to 0 and then wait for \ it to change to non-zero to catch the vertical sync STA VIA+&44 \ Set 6522 System VIA T1C-L timer 1 low-order counter \ (SHEILA &44) to 30 LDA #VSCAN \ Set 6522 System VIA T1C-L timer 1 high-order counter STA VIA+&45 \ (SHEILA &45) to VSCAN (57) to start the T1 counter \ counting down from 14622 at a rate of 1 MHz LDA HFX \ If HFX is non-zero, jump to VNT1 to set the mode 5 BNE VNT1 \ palette instead of switching to mode 4, which will \ have the effect of blurring and colouring the top \ screen. This is how the white hyperspace rings turn \ to colour when we do a hyperspace jump, and is \ triggered by setting HFX to 1 in routine LL164 LDA #%00001000 \ Set the Video ULA control register (SHEILA &20) to STA VIA+&20 \ %00001000, which is the same as switching to mode 4 \ (i.e. the top part of the screen) but with no cursor .VNT3 LDA TVT1+16,Y \ Copy the Y-th palette byte from TVT1+16 to SHEILA &21 STA VIA+&21 \ to map logical to actual colours for the bottom part \ of the screen (i.e. the dashboard) DEY \ Decrement the palette byte counter BPL VNT3 \ Loop back to VNT3 until we have copied all the \ palette bytes LDA LASCT \ Decrement the value of LASCT, but if we go too far BEQ P%+5 \ and it becomes negative, bump it back up again (this DEC LASCT \ controls the pulsing of pulse lasers) PLA \ Otherwise restore Y from the stack TAY LDA VIA+&41 \ Read 6522 System VIA input register IRA (SHEILA &41) LDA &FC \ Set A to the interrupt accumulator save register, \ which restores A to the value it had on entering the \ interrupt RTI \ Return from interrupts, so this interrupt is not \ passed on to the next interrupt handler, but instead \ the interrupt terminates here .IRQ1 TYA \ Store Y on the stack PHA LDY #11 \ Set Y as a counter for 12 bytes, to use when setting \ the dashboard palette below LDA #%00000010 \ Read the 6522 System VIA status byte bit 1 (SHEILA BIT VIA+&4D \ &4D), which is set if vertical sync has occurred on \ the video system BNE LINSCN \ If we are on the vertical sync pulse, jump to LINSCN \ to set up the timers to enable us to switch the \ screen mode between the space view and dashboard BVC jvec \ Read the 6522 System VIA status byte bit 6, which is \ set if timer 1 has timed out. We set the timer in \ LINSCN above, so this means we only run the next bit \ if the screen redraw has reached the boundary between \ the space view and the dashboard. Otherwise bit 6 is \ clear and we aren't at the boundary, so we jump to \ jvec to pass control to the next interrupt handler ASL A \ Double the value in A to 4 STA VIA+&20 \ Set the Video ULA control register (SHEILA &20) to \ %00000100, which is the same as switching to mode 5, \ (i.e. the bottom part of the screen) but with no \ cursor LDA ESCP \ If an escape pod is fitted, jump to VNT1 to set the BNE VNT1 \ mode 5 palette differently (so the dashboard is a \ different colour if we have an escape pod) LDA TVT1,Y \ Copy the Y-th palette byte from TVT1 to SHEILA &21 STA VIA+&21 \ to map logical to actual colours for the bottom part \ of the screen (i.e. the dashboard) DEY \ Decrement the palette byte counter BPL P%-7 \ Loop back to the LDA TVT1,Y instruction until we have \ copied all the palette bytes .jvec PLA \ Restore Y from the stack TAY JMP (VEC) \ Jump to the address in VEC, which was set to the \ original IRQ1V vector by the loading process, so this \ instruction passes control to the next interrupt \ handler .VNT1 LDY #7 \ Set Y as a counter for 8 bytes LDA TVT1+8,Y \ Copy the Y-th palette byte from TVT1+8 to SHEILA &21 STA VIA+&21 \ to map logical to actual colours for the bottom part \ of the screen (i.e. the dashboard) DEY \ Decrement the palette byte counter BPL VNT1+2 \ Loop back to the LDA TVT1+8,Y instruction until we \ have copied all the palette bytes BMI jvec \ Jump up to jvec to pass control to the next interrupt \ handler (this BMI is effectively a JMP as we didn't \ loop back with the BPL above, so BMI is always true) \ ****************************************************************************** \ \ Name: S1% \ Type: Variable \ Category: Save and load \ Summary: The drive and directory number used when saving or loading a \ commander file \ Deep dive: Commander save files \ \ ------------------------------------------------------------------------------ \ \ The drive part of this string (the "0") is updated with the chosen drive in \ the QUS1 routine, but the directory part (the "E") is fixed. The variable is \ followed directly by the commander file at NA%, which starts with the \ commander name, so the full string at S1% is in the format ":0.E.JAMESON", \ which gives the full filename of the commander file. \ \ ****************************************************************************** .S1% EQUS ":0.E." \ ****************************************************************************** \ \ Name: NA% \ Type: Variable \ Category: Save and load \ Summary: The data block for the last saved commander \ Deep dive: Commander save files \ The competition code \ \ ------------------------------------------------------------------------------ \ \ Contains the last saved commander data, with the name at NA% and the data at \ NA%+8 onwards. The size of the data block is given in NT% (which also includes \ the two checksum bytes that follow this block). This block is initially set up \ with the default commander, which can be maxed out for testing purposes by \ setting Q% to TRUE. \ \ The commander's name is stored at NA%, and can be up to 7 characters long \ (the DFS filename limit). It is terminated with a carriage return character, \ ASCII 13. \ \ The offset of each byte within a saved commander file is also shown as #0, #1 \ and so on, so the kill tally, for example, is in bytes #71 and #72 of the \ saved file. The related variable name from the current commander block is \ also shown. \ \ ****************************************************************************** .NA% \ --- Mod: Original Acornsoft code removed: -----------> \ EQUS "JAMESON" \ The current commander name, which defaults to JAMESON \ EQUB 13 \ \ \ The commander name can be up to 7 characters (the DFS \ \ limit for filenames), and is terminated by a carriage \ \ return \ --- And replaced by: --------------------------------> EQUS "NEWCOME" \ The current commander name, which defaults to NEWCOME EQUB 13 \ \ The commander name can be up to 7 characters (the DFS \ limit for filenames), and is terminated by a carriage \ return \ --- End of replacement ------------------------------> \ NA%+8 is the start of the commander data block \ \ This block contains the last saved commander data \ block. As the game is played it uses an identical \ block at location TP to store the current commander \ state, and that block is copied here when the game is \ saved. Conversely, when the game starts up, the block \ here is copied to TP, which restores the last saved \ commander when we die \ \ The initial state of this block defines the default \ commander. Q% can be set to TRUE to give the default \ commander lots of credits and equipment EQUB 0 \ TP = Mission status, #0 EQUB 20 \ QQ0 = Current system X-coordinate (Lave), #1 EQUB 173 \ QQ1 = Current system Y-coordinate (Lave), #2 EQUW &5A4A \ QQ21 = Seed s0 for system 0, galaxy 0 (Tibedied), #3-4 EQUW &0248 \ QQ21 = Seed s1 for system 0, galaxy 0 (Tibedied), #5-6 EQUW &B753 \ QQ21 = Seed s2 for system 0, galaxy 0 (Tibedied), #7-8 \ --- Mod: Original Acornsoft code removed: -----------> \IF Q% \ EQUD &00CA9A3B \ CASH = Amount of cash (100,000,000 Cr), #9-12 \ELSE \ EQUD &E8030000 \ CASH = Amount of cash (100 Cr), #9-12 \ENDIF \ \ EQUB 70 \ QQ14 = Fuel level, #13 \ --- And replaced by: --------------------------------> IF Q% EQUD &00CA9A3B \ CASH = Amount of cash (100,000,000 Cr), #9-12 ELSE EQUD &88130000 \ CASH = Amount of cash (500 Cr), #9-12 ENDIF EQUB 60+(15 AND Q%) \ QQ14 = Fuel level, #13 \ --- End of replacement ------------------------------> EQUB 0 \ COK = Competition flags, #14 EQUB 0 \ GCNT = Galaxy number, 0-7, #15 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB POW+(128 AND Q%) \ LASER = Front laser, #16 \ \ EQUB (POW+128) AND Q% \ LASER+1 = Rear laser, #17 \ --- And replaced by: --------------------------------> EQUB &9C AND Q% \ LASER = Front laser, #16 EQUB &9C AND Q% \ LASER+1 = Rear laser, #17 \ --- End of replacement ------------------------------> EQUB 0 \ LASER+2 = Left laser, #18 EQUB 0 \ LASER+3 = Right laser, #19 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUW 0 \ These bytes appear to be unused (they were originally \ \ used for up/down lasers, but they were dropped), \ \ #20-21 \ \ EQUB 22+(15 AND Q%) \ CRGO = Cargo capacity, #22 \ --- And replaced by: --------------------------------> EQUB 0 \ This byte appears to be unused, #20 EQUB 8 AND Q% \ cmdr_type = Type of our current ship, #21 EQUB Q% \ CRGO = I.F.F. system, #22 \ --- End of replacement ------------------------------> EQUB 0 \ QQ20+0 = Amount of food in cargo hold, #23 EQUB 0 \ QQ20+1 = Amount of textiles in cargo hold, #24 EQUB 0 \ QQ20+2 = Amount of radioactives in cargo hold, #25 EQUB 0 \ QQ20+3 = Amount of slaves in cargo hold, #26 EQUB 0 \ QQ20+4 = Amount of liquor/Wines in cargo hold, #27 EQUB 0 \ QQ20+5 = Amount of luxuries in cargo hold, #28 EQUB 0 \ QQ20+6 = Amount of narcotics in cargo hold, #29 EQUB 0 \ QQ20+7 = Amount of computers in cargo hold, #30 EQUB 0 \ QQ20+8 = Amount of machinery in cargo hold, #31 EQUB 0 \ QQ20+9 = Amount of alloys in cargo hold, #32 EQUB 0 \ QQ20+10 = Amount of firearms in cargo hold, #33 EQUB 0 \ QQ20+11 = Amount of furs in cargo hold, #34 EQUB 0 \ QQ20+12 = Amount of minerals in cargo hold, #35 EQUB 0 \ QQ20+13 = Amount of gold in cargo hold, #36 EQUB 0 \ QQ20+14 = Amount of platinum in cargo hold, #37 EQUB 0 \ QQ20+15 = Amount of gem-stones in cargo hold, #38 EQUB 0 \ QQ20+16 = Amount of alien items in cargo hold, #39 EQUB Q% \ ECM = E.C.M. system, #40 EQUB Q% \ BST = Fuel scoops ("barrel status"), #41 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB Q% AND 127 \ BOMB = Energy bomb, #42 \ --- And replaced by: --------------------------------> EQUB Q% \ BOMB = Hyperspace unit, #42 \ --- End of replacement ------------------------------> EQUB Q% AND 1 \ ENGY = Energy/shield level, #43 EQUB Q% \ DKCMP = Docking computer, #44 EQUB Q% \ GHYP = Galactic hyperdrive, #45 EQUB Q% \ ESCP = Escape pod, #46 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUD 0 \ These four bytes appear to be unused, #47-50 \ \ EQUB 3+(Q% AND 1) \ NOMSL = Number of missiles, #51 \ --- And replaced by: --------------------------------> EQUW 0 \ cmdr_cour = Special cargo mission timer, #47 EQUB 0 \ cmdr_courx = Special cargo destination x-coord, #49 EQUB 0 \ cmdr_coury = Special cargo destination y-coord, #50 EQUB 0 \ NOMSL = Number of missiles, #51 \ --- End of replacement ------------------------------> EQUB 0 \ FIST = Legal status ("fugitive/innocent status"), #52 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 16 \ AVL+0 = Market availability of food, #53 \ --- And replaced by: --------------------------------> EQUB 0 \ AVL+0 = Market availability of food, #53 \ --- End of replacement ------------------------------> EQUB 15 \ AVL+1 = Market availability of textiles, #54 EQUB 17 \ AVL+2 = Market availability of radioactives, #55 EQUB 0 \ AVL+3 = Market availability of slaves, #56 EQUB 3 \ AVL+4 = Market availability of liquor/Wines, #57 EQUB 28 \ AVL+5 = Market availability of luxuries, #58 EQUB 14 \ AVL+6 = Market availability of narcotics, #59 EQUB 0 \ AVL+7 = Market availability of computers, #60 EQUB 0 \ AVL+8 = Market availability of machinery, #61 EQUB 10 \ AVL+9 = Market availability of alloys, #62 EQUB 0 \ AVL+10 = Market availability of firearms, #63 EQUB 17 \ AVL+11 = Market availability of furs, #64 EQUB 58 \ AVL+12 = Market availability of minerals, #65 EQUB 7 \ AVL+13 = Market availability of gold, #66 EQUB 9 \ AVL+14 = Market availability of platinum, #67 EQUB 8 \ AVL+15 = Market availability of gem-stones, #68 EQUB 0 \ AVL+16 = Market availability of alien items, #69 EQUB 0 \ QQ26 = Random byte that changes for each visit to a \ system, for randomising market prices, #70 EQUW 0 \ TALLY = Number of kills, #71-72 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 128 \ SVC = Save count, #73 \ --- And replaced by: --------------------------------> EQUB 32 \ SVC = Save count, #73 \ --- End of replacement ------------------------------> \ ****************************************************************************** \ \ Name: CHK2 \ Type: Variable \ Category: Save and load \ Summary: Second checksum byte for the saved commander data file \ Deep dive: Commander save files \ The competition code \ \ ------------------------------------------------------------------------------ \ \ Second commander checksum byte. If the default commander is changed, a new \ checksum will be calculated and inserted by the elite-checksum.py script. \ \ The offset of this byte within a saved commander file is also shown (it's at \ byte #74). \ \ ****************************************************************************** .CHK2 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB &03 EOR &A9 \ The checksum value for the default commander, EOR'd \ \ with &A9 to make it harder to tamper with the checksum \ \ byte, #74 \ --- And replaced by: --------------------------------> EQUB &58 EOR &A9 \ The checksum value for the default commander, EOR'd \ with &A9 to make it harder to tamper with the checksum \ byte, #74 \ --- End of replacement ------------------------------> \ ****************************************************************************** \ \ Name: CHK \ Type: Variable \ Category: Save and load \ Summary: First checksum byte for the saved commander data file \ Deep dive: Commander save files \ The competition code \ \ ------------------------------------------------------------------------------ \ \ Commander checksum byte. If the default commander is changed, a new checksum \ will be calculated and inserted by the elite-checksum.py script. \ \ The offset of this byte within a saved commander file is also shown (it's at \ byte #75). \ \ ****************************************************************************** .CHK \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB &03 \ The checksum value for the default commander, #75 \ --- And replaced by: --------------------------------> EQUB &58 \ The checksum value for the default commander, #75 \ --- End of replacement ------------------------------> \ ****************************************************************************** \ \ Name: BRBR1 \ Type: Subroutine \ Category: Loader \ Summary: Loader break handler: print a newline and the error message, and \ then hang the computer \ \ ------------------------------------------------------------------------------ \ \ This break handler is used during loading and during flight, and is resident \ in memory throughout the game's lifecycle. The docked code loads its own \ break handler and overrides this one until the flight code is run. \ \ The main difference between the two handlers is that this one display the \ error and then hangs, while the docked code displays the error and returns. \ This is because the docked code has to cope gracefully with errors from the \ disc access menu (such as "File not found"), which we obviously don't want to \ terminate the game. \ \ ****************************************************************************** .BRBR1 \ The following loop prints out the null-terminated \ message pointed to by (&FD &FE), which is the MOS \ error message pointer - so this prints the error \ message on the next line LDY #0 \ Set Y = 0 to act as a character counter LDA #13 \ Set A = 13 so the first character printed is a \ carriage return .BRBRLOOP JSR OSWRCH \ Print the character in A (which contains a carriage \ return on the first loop iteration), and then any \ characters we fetch from the error message INY \ Increment the loop counter LDA (&FD),Y \ Fetch the Y-th byte of the block pointed to by \ (&FD &FE), so that's the Y-th character of the message \ pointed to by the MOS error message pointer BNE BRBRLOOP \ If the fetched character is non-zero, loop back to the \ JSR OSWRCH above to print the it, and keep looping \ until we fetch a zero (which marks the end of the \ message) BEQ P% \ Hang the computer as something has gone wrong \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB &64, &5F, &61 \ These bytes appear to be unused \ EQUB &74, &74, &72 \ EQUB &69, &62, &75 \ EQUB &74, &65, &73 \ EQUB &00, &C4, &24 \ EQUB &6A, &43, &67 \ EQUB &65, &74, &72 \ EQUB &64, &69, &73 \ EQUB &63, &00, &B6 \ EQUB &3C, &C6 \ --- End of removed code -----------------------------> COPYBLOCK TVT1, P%, TVT1code ORG TVT1code + P% - TVT1 \ ****************************************************************************** \ \ Name: Elite loader (Part 3 of 3) \ Type: Subroutine \ Category: Loader \ Summary: Include binaries for the loading screen images \ \ ------------------------------------------------------------------------------ \ \ The loader bundles a number of binary files in with the loader code, and moves \ them to their correct memory locations in part 1 above. \ \ This part includes three files containing images, which are all moved into \ screen memory by the loader: \ \ * P.A-SOFT.bin contains the "ACORNSOFT" title across the top of the loading \ screen, which gets moved to screen address &6100, on the second character \ row of the monochrome mode 4 screen \ \ * P.ELITE.bin contains the "ELITE" title across the top of the loading \ screen, which gets moved to screen address &6300, on the fourth character \ row of the monochrome mode 4 screen \ \ * P.(C)ASFT.bin contains the "(C) Acornsoft 1984" title across the bottom \ of the loading screen, which gets moved to screen address &7600, the \ penultimate character row of the monochrome mode 4 screen, just above the \ dashboard \ \ There are three other binaries bundled into the loader, which are described in \ part 2 above. \ \ ****************************************************************************** .ELITE INCBIN "1-source-files/images/P.ELITE.bin" .ASOFT INCBIN "1-source-files/images/P.A-SOFT.bin" .CpASOFT INCBIN "1-source-files/images/P.(C)ASFT.bin" \ ****************************************************************************** \ \ Name: to_dd00 \ Type: Subroutine \ Category: Loader \ Summary: BBC Master code for saving and restoring the MOS character set, \ bundled up in the loader so it can be moved to &DD00 to be run \ \ ****************************************************************************** CPU 1 .to_dd00 ORG &DD00 \ ****************************************************************************** \ \ Name: do_FILEV \ Type: Subroutine \ Category: Loader \ Summary: The custom handler for OSFILE calls in the BBC Master version \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .do_FILEV JSR restorews \ Call restorews to restore the filing system workspace, \ so we can use the filing system .old_FILEV JSR &100 \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it calls the existing FILEV handler \ Fall through into savews to save the filing system \ workspace in a safe place and replace it with the MOS \ character set, so that character printing will work \ once again \ --- End of added section ----------------------------> \ ****************************************************************************** \ \ Name: savews \ Type: Subroutine \ Category: Loader \ Summary: Save the filing system workspace in a safe place and replace it \ with the MOS character set \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .savews PHP \ Store the status register, A, X and Y on the stack, so PHA \ we can retrieve them later to preserve them across PHX \ calls to the subroutine PHY LDA #%00001000 \ Set bit 3 of the Access Control Register at SHEILA &34 TSB VIA+&34 \ to map the filing system RAM space into &C000-&DFFF \ (HAZEL), in place of the MOS VDU workspace (the TSB \ instruction applies the accumulator to the memory \ location using an OR) \ We now want to copy the first three pages from &C000 \ to the safe place that we obtained in the loader, and \ whose location we poked directly into the put0, put1 \ and put2 instructions below, back in part 1 of the \ loader LDX #0 \ Set a byte counter in X so we can copy an entire page \ of bytes, starting from 0 .putws LDA &C000,X \ Fetch the X-th byte from the first page of the &C000 \ workspace .put0 STA &C000,X \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it points to the first page of the safe \ place where we can copy the filing system workspace LDA &C100,X \ Fetch the X-th byte from the second page of the &C000 \ workspace (i.e. &C100) .put1 STA &C100,X \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it points to the second page of the safe \ place where we can copy the filing system workspace LDA &C200,X \ Fetch the X-th byte from the third page of the &C000 \ workspace (i.e. &C200) .put2 STA &C200,X \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it points to the third page of the safe \ place where we can copy the filing system workspace INX \ Increment the byte counter BNE putws \ Loop back until we have copied a whole page of bytes \ (three times) LDA LATCH \ Fetch the RAM copy of the currently selected paged ROM PHA \ from LATCH and save it on the stack so we can restore \ it below LDA #%10000000 \ Set the RAM copy of the currently selected paged ROM STA LATCH \ so it matches the paged ROM selection latch at SHEILA \ &30 that we are about to set STA VIA+&30 \ Set bit 7 of the ROM Select latch at SHEILA &30, to \ map the MOS ROM to &8000-&8FFF in RAM (ANDY) \ We now want to copy the three pages of MOS character \ definitions from the MOS ROM to &C000, so the \ character printing routines can use them LDX #0 \ Set a byte counter in X so we can copy an entire page \ of bytes, starting from 0 .copych LDA &8900,X \ Copy the X-th byte of the first page of MOS character STA &C000,X \ definitions at &8900 into the X-th byte of &C000 LDA &8A00,X \ Copy the X-th byte of the second page of MOS character STA &C100,X \ definitions at &8A00 into the X-th byte of &C100 LDA &8B00,X \ Copy the X-th byte of the third page of MOS character STA &C200,X \ definitions at &8B00 into the X-th byte of &C100 INX \ Increment the byte counter BNE copych \ Loop back until we have copied a whole page of bytes \ (three times) PLA \ Restore the paged ROM number that we saved on the STA LATCH \ stack and store it in LATCH so it matches the paged \ ROM selection latch at SHEILA &30 that we are about \ to set STA VIA+&30 \ Store the same value in SHEILA &30, to switch back to \ the ROM that was selected before we changed it above PLY \ Restore the status register, A, X and Y from the PLX \ stack, so they are preserved by the subroutine PLA PLP RTS \ Return from the subroutine \ --- End of added section ----------------------------> \ ****************************************************************************** \ \ Name: do_FSCV \ Type: Subroutine \ Category: Loader \ Summary: The custom handler for filing system calls in the BBC Master \ version \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .do_FSCV JSR restorews \ Call restorews to restore the filing system workspace, \ so we can use the filing system .old_FSCV JSR &100 \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it calls the existing FSCV handler JMP savews \ Call savews to save the filing system workspace in a \ safe place and replace it with the MOS character set, \ so that character printing will work once again \ --- End of added section ----------------------------> \ ****************************************************************************** \ \ Name: restorews \ Type: Subroutine \ Category: Loader \ Summary: Restore the filing system workspace \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .restorews PHA \ Store A and X on the stack, so we can retrieve them PHX \ later to preserve them across calls to the subroutine \ We now want to copy the first three pages from the \ safe place back to &C00), reversing the copy that we \ did in savews. As with savews, the location of the \ safe place was poked directly into the get0, get1 and \ get2 instructions below, back in part 1 of the loader LDX #0 \ Set a byte counter in X so we can copy an entire page \ of bytes, starting from 0 .getws .get0 LDA &C000,X \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it points to the first page of the safe \ place where we copied the filing system workspace in \ the savews routine STA &C000,X \ Copy the X-th byte from the first page of the safe \ place to the X-th byte of the first page of the &C000 \ block .get1 LDA &C100,X \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it points to the second page of the safe \ place where we copied the filing system workspace in \ the savews routine STA &C100,X \ Copy the X-th byte from the second page of the safe \ place to the X-th byte of the second page of the &C000 \ block (i.e. &C100) .get2 LDA &C200,X \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it points to the third page of the safe \ place where we copied the filing system workspace in \ the savews routine STA &C200,X \ Copy the X-th byte from the third page of the safe \ place to the X-th byte of the third page of the &C000 \ block (i.e. &C200) INX \ Increment the byte counter BNE getws \ Loop back until we have copied a whole page of bytes \ (three times) PLX \ Retore A and X from the stack, so they are preserved PLA \ by the subroutine RTS \ Return from the subroutine \ --- End of added section ----------------------------> \ ****************************************************************************** \ \ Name: do_BYTEV \ Type: Subroutine \ Category: Loader \ Summary: The custom handler for OSBYTE calls in the BBC Master version \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .do_BYTEV CMP #143 \ If this is not OSBYTE 143, the paged ROM service call, BNE old_BYTEV \ then jump to old_BYTEV to pass the call onto the \ default handler CPX #&F \ If the value of X is not &F ("vectors changed"), jump BNE old_BYTEV \ to old_BYTEV to pass the call onto the default \ handler JSR old_BYTEV \ This is OSBYTE 143 with X = &F (the "vectors changed" \ service call), so first of all call old_BYTEV so the \ service call can be processed by the default handler \ And then fall through into set_vectors to set the \ FILEV, FSCV and BYTEV vectors to point to our custom \ handlers \ --- End of added section ----------------------------> \ ****************************************************************************** \ \ Name: set_vectors \ Type: Subroutine \ Category: Loader \ Summary: Set the FILEV, FSCV and BYTEV vectors to point to our custom \ handlers \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .set_vectors SEI \ Disable interrupts while we update the vectors PHA \ Store A on the stack so we can retrieve it below LDA #LO(do_FILEV) \ Set the FILEV to point to our custom handler in STA FILEV \ do_FILEV LDA #HI(do_FILEV) STA FILEV+1 LDA #LO(do_FSCV) \ Set the FSCV to point to our custom handler in STA FSCV \ do_FSCV LDA #HI(do_FSCV) STA FSCV+1 LDA #LO(do_BYTEV) \ Set the BYTEV to point to our custom handler in STA BYTEV \ do_BYTEV LDA #HI(do_BYTEV) STA BYTEV+1 PLA \ Restore A from the stack, so the subroutine doesn't \ change its value CLI \ Enable interrupts again RTS \ Return from the subroutine \ --- End of added section ----------------------------> \ ****************************************************************************** \ \ Name: old_BYTEV \ Type: Subroutine \ Category: Loader \ Summary: Call the default OSBYTE handler \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .old_BYTEV JMP &100 \ This address is modified by the Master-specific code \ in part 1 of the loader (just after the cpmaster \ loop), so it calls the existing BYTEV handler and \ returns from the subroutine using a tail call \ --- End of added section ----------------------------> dd00_len = P% - do_FILEV COPYBLOCK do_FILEV, P%, to_dd00 ORG to_dd00 + P% - do_FILEV \ ****************************************************************************** \ \ Save ELITE.bin \ \ ****************************************************************************** PRINT "S.ELITE ", ~CODE%, " ", ~P%, " ", ~LOAD%, " ", ~LOAD% SAVE "3-assembled-output/ELITE.bin", CODE%, P%, LOAD%
; A162526: Numbers k whose largest divisor <= sqrt(k) equals 6. ; 36,42,48,54,60,66,78,102,114,138,174,186,222,246,258,282,318,354,366,402,426,438,474,498,534,582,606,618,642,654,678,762,786,822,834,894,906,942,978,1002,1038,1074,1086,1146,1158,1182,1194,1266,1338,1362 mov $1,$0 trn $1,1 seq $1,6005 ; The odd prime numbers together with 1. sub $1,6 max $0,$1 mul $0,6 add $0,36
; Substitute for the z80 ex (sp),hl instruction ; CPU Min T Max T ; 8080 18 18 ; 8085 16 16 ; gbz80 148 148 ; r2ka 15 15 ; z180 16 16 ; z80 19 19 ; z80n 19 19 IF __CPU_GBZ80__ SECTION code_l_sccz80 PUBLIC __z80asm__ex_sp_hl __z80asm__ex_sp_hl: push af ;16 push de ;16 ld d, h ;4 DE = HL0 ld e, l ;4 ld hl, sp+6 ;12, (sp) HL = & SP0 ld a, (hl) ;8 ld (hl), e ;8 ld e, a ;4 swap low HL0, SP0 inc hl ;8 HL = & SP0+1 ld a, (hl) ;8 ld (hl), d ;8 ld h, a ;4 swap hi HL0, SP0 -> HL ld l, e ;4 pop de ;12 pop af ;12 ret ;16 ENDIF
; =============================================================== ; 2014 ; =============================================================== ; ; void bit_beep_di(uint16_t duration_ms, uint16_t frequency_hz) ; ; As bit_beep() but interrupts are disabled around the tone. ; Proper interrupt status is restored prior to return. ; ; =============================================================== SECTION code_clib SECTION code_sound_bit PUBLIC asm_bit_beep_di EXTERN asm_bit_beep, asm_cpu_push_di, asm0_cpu_pop_ei asm_bit_beep_di: ; enter : hl = note_frequency ; de = duration_ms ; ; uses : af, bc, de, hl, (bc', de', hl', ix for integer division) call asm_cpu_push_di call asm_bit_beep jp asm0_cpu_pop_ei
NamesPointers:: ; entries correspond to GetName constants (see constants/text_constants.asm); MON_NAME is not handled by this table dba MoveNames ; MOVE_NAME dba ItemNames ; ITEM_NAME dbw 0, wPartyMonOT ; PARTY_OT_NAME dbw 0, wOTPartyMonOT ; ENEMY_OT_NAME dba TrainerClassNames ; TRAINER_NAME GetName:: ; Return name wCurSpecies from name list wNamedObjectTypeBuffer in wStringBuffer1. ldh a, [hROMBank] push af push hl push bc push de ld a, [wNamedObjectTypeBuffer] dec a jr nz, .not_mon_name ld a, [wCurSpecies] ld [wNamedObjectIndexBuffer], a call GetPokemonName jr .done .not_mon_name dec a ld l, a add a, a add a, l add a, LOW(NamesPointers) ld l, a ld a, HIGH(NamesPointers) adc 0 ld h, a ld a, [hli] rst Bankswitch ld a, [hli] ld h, [hl] ld l, a ld a, [wCurSpecies] dec a call GetNthString ld de, wStringBuffer1 ld bc, ITEM_NAME_LENGTH call CopyBytes .done pop de pop bc pop hl pop af rst Bankswitch ret GetNthString:: ; Return the address of the ; ath string starting from hl. and a ret z push bc ld b, a ld c, "@" .readChar ld a, [hli] cp c jr nz, .readChar dec b jr nz, .readChar pop bc ret GetBasePokemonName:: ; Discards gender (Nidoran). push hl call GetPokemonName ld hl, wStringBuffer1 .loop ld a, [hl] cp "@" jr z, .quit cp "♂" jr z, .end cp "♀" jr z, .end inc hl jr .loop .end ld [hl], "@" .quit pop hl ret GetPokemonName:: ; Get Pokemon name for wNamedObjectIndexBuffer. ldh a, [hROMBank] push af push hl ld a, BANK(PokemonNames) rst Bankswitch ; Each name is ten characters ld a, [wNamedObjectIndexBuffer] call GetPokemonIndexFromID ld e, l ld d, h add hl, hl ; hl = hl * 4 add hl, hl ; hl = hl * 4 add hl, de ; hl = (hl*4) + de add hl, hl ; hl = (5*hl) + (5*hl) ld de, PokemonNames - 10 add hl, de ; Terminator ld de, wStringBuffer1 push de ld bc, MON_NAME_LENGTH - 1 call CopyBytes ld hl, wStringBuffer1 + MON_NAME_LENGTH - 1 ld [hl], "@" pop de pop hl pop af rst Bankswitch ret GetItemName:: ; Get item name for wNamedObjectIndexBuffer. push hl push bc ld a, [wNamedObjectIndexBuffer] cp TM01 jr nc, .TM ld [wCurSpecies], a ld a, ITEM_NAME ld [wNamedObjectTypeBuffer], a call GetName jr .Copied .TM: call GetTMHMName .Copied: ld de, wStringBuffer1 pop bc pop hl ret GetTMHMName:: ; Get TM/HM name for item wNamedObjectIndexBuffer. push hl push de push bc ld a, [wNamedObjectIndexBuffer] push af ; TM/HM prefix cp HM01 push af jr c, .TM ld hl, .HMText ld bc, .HMTextEnd - .HMText jr .asm_34a1 .TM: ld hl, .TMText ld bc, .TMTextEnd - .TMText .asm_34a1 ld de, wStringBuffer1 call CopyBytes ; TM/HM number push de ld a, [wNamedObjectIndexBuffer] ld c, a callfar GetTMHMNumber pop de ; HM numbers start from 51, not 1 pop af ld a, c jr c, .asm_34b9 sub NUM_TMS .asm_34b9 ; Divide and mod by 10 to get the top and bottom digits respectively ld b, "0" .mod10 sub 10 jr c, .asm_34c2 inc b jr .mod10 .asm_34c2 add 10 push af ld a, b ld [de], a inc de pop af ld b, "0" add b ld [de], a ; End the string inc de ld a, "@" ld [de], a pop af ld [wNamedObjectIndexBuffer], a pop bc pop de pop hl ret .TMText: db "TM" .TMTextEnd: db "@" .HMText: db "HM" .HMTextEnd: db "@" INCLUDE "home/hm_moves.asm" GetMoveName:: push hl ld a, MOVE_NAME ld [wNamedObjectTypeBuffer], a ld a, [wNamedObjectIndexBuffer] ; move id ld [wCurSpecies], a call GetName ld de, wStringBuffer1 pop hl ret
/// \file // Range v3 library // // Copyright Eric Niebler 2014 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_ALGORITHM_REPLACE_COPY_HPP #define RANGES_V3_ALGORITHM_REPLACE_COPY_HPP #include <range/v3/range_fwd.hpp> #include <range/v3/begin_end.hpp> #include <range/v3/range_concepts.hpp> #include <range/v3/range_traits.hpp> #include <range/v3/utility/meta.hpp> #include <range/v3/utility/iterator_concepts.hpp> #include <range/v3/utility/iterator_traits.hpp> #include <range/v3/utility/functional.hpp> #include <range/v3/utility/static_const.hpp> namespace ranges { inline namespace v3 { /// \ingroup group-concepts template<typename I, typename O, typename T0, typename T1, typename P = ident> using ReplaceCopyable = meta::fast_and< InputIterator<I>, WeakOutputIterator<O, T1>, IndirectlyCopyable<I, O>, IndirectInvokableRelation<equal_to, Project<I, P>, T0 const *>>; /// \addtogroup group-algorithms /// @{ struct replace_copy_fn { template<typename I, typename S, typename O, typename T0, typename T1, typename P = ident, CONCEPT_REQUIRES_(ReplaceCopyable<I, O, T0, T1, P>() && IteratorRange<I, S>())> std::pair<I, O> operator()(I begin, S end, O out, T0 const & old_value, T1 const & new_value, P proj_ = {}) const { auto &&proj = invokable(proj_); for(; begin != end; ++begin, ++out) { auto &&x = *begin; if(proj(x) == old_value) *out = new_value; else *out = (decltype(x) &&) x; } return {begin, out}; } template<typename Rng, typename O, typename T0, typename T1, typename P = ident, typename I = range_iterator_t<Rng>, CONCEPT_REQUIRES_(ReplaceCopyable<I, O, T0, T1, P>() && Iterable<Rng &>())> std::pair<I, O> operator()(Rng & rng, O out, T0 const & old_value, T1 const & new_value, P proj = {}) const { return (*this)(begin(rng), end(rng), std::move(out), old_value, new_value, std::move(proj)); } }; /// \sa `replace_copy_fn` /// \ingroup group-algorithms namespace { constexpr auto&& replace_copy = static_const<replace_copy_fn>::value; } /// @} } // namespace v3 } // namespace ranges #endif // include guard
/* dtkMathArray.cpp --- * * Author: Thibaud Kloczko * Created: Tue Jul 23 14:59:07 2013 (+0200) */ /* Commentary: * * For credits, see EOF */ #include "dtkMathArray.h" /*! \class dtkMathArray \brief The dtkMathArray class is a template class that provides a dynamic array of simple types. \since 4.8 \ingroup qt3d \ingroup qt3d::arrays dtkMathArray is similar to QVector except that it has much less overhead when constructing large arrays by appending individual elements one by one. dtkMathArray instances have a preallocated data area for quickly building small arrays on the stack without malloc overhead. Once the array grows beyond the preallocated size, it is copied to the heap. The size of the preallocated area, which defaults to 8, can be specified with the second template parameter: \code dtkMathArray<QVector3D, 32> array; \endcode dtkMathArray uses implicit sharing and copy-on-write semantics to support passing large arrays around an application with little overhead. dtkMathArray is heavily optimized for copy-on-write and the case of constructing an array by calling append(). It has a slight performance penalty for random access using the non-const version of operator[](). */ /*! \fn dtkMathArray::dtkMathArray() Constructs an empty array. \sa reserve() */ /*! \fn dtkMathArray::dtkMathArray(qlonglong size, const T &value) Constructs an array of \a size elements, all initialized to \a value. \sa fill() */ /*! \fn dtkMathArray::dtkMathArray(qlonglong size) Constructs an array of \a size elements, all initialized to their default-constructed values. */ /*! \fn dtkMathArray::dtkMathArray(const T *values, qlonglong size) Constructs an array of \a size elements, initialized from \a values. */ /*! \fn dtkMathArray::dtkMathArray(const dtkMathArray<T, PreallocSize> &other) Constructs a copy of \a other. \sa operator=() */ /*! \fn dtkMathArray::~dtkMathArray() Destroys the array. */ /*! \fn dtkMathArray<T, PreallocSize> &dtkMathArray::operator=(const dtkMathArray<T, PreallocSize> &other) Assigns \a other to this array and returns a reference to this array. */ /*! \fn qlonglong dtkMathArray::size() const Returns the number of elements in this array. \sa resize(), capacity(), isEmpty() */ /*! \fn qlonglong dtkMathArray::count() const \overload Same as size(), provided for convenience. */ /*! \fn qlonglong dtkMathArray::capacity() const Returns the number of elements that can be stored in this array before reallocation. \sa reserve(), size() */ /*! \fn bool dtkMathArray::isEmpty() const Returns true if this array is empty; false otherwise. \sa size(), clear() */ /*! \fn bool dtkMathArray::isDetached() const \internal Returns true if this array has definitely been detached from all other shared copies of the data; false otherwise. It is possible for this function to return false if the array was previously shared but no longer is. It is thus an indication that a detach() will probably be required. This function can be used to determine if functions that write to this array such as append(), replace(), and rawData(), will need to make a copy. Raw data arrays that are created with fromRawData() are never detached. \sa detach() */ /*! \fn void dtkMathArray::detach() \internal Detaches this array from all other shared copies of the data. \sa isDetached() */ /*! \fn void dtkMathArray::clear() Clears all elements from this array and sets the size to zero. This function will deallocate any memory that is used on the heap to store the array's elements. To reuse the same memory as before, call resize() with an argument of zero. \sa resize(), isEmpty() */ /*! \fn const T &dtkMathArray::at(qlonglong index) const Returns the item at position \a index in the array. \a index must be a valid index position in the array (i.e., 0 <= \a index < size()). \sa operator[](), constRawData(), value() */ /*! \fn T &dtkMathArray::operator[](qlonglong index) Returns the item at position \a index as a modifiable reference. \a index must be a valid index position in the vector (i.e., 0 <= \a index < size()). Note that using non-const operators can cause dtkMathArray to do a deep copy. \sa at(), value() */ /*! \fn const T &dtkMathArray::operator[](qlonglong index) const \overload Same as at(\a index). */ /*! \fn T dtkMathArray::value(qlonglong index) const Returns the value at position \a index in the vector. If the \a index is out of bounds, the function returns a default-constructed value. If you are certain that \a index is within bounds, you can use at() instead, which is slightly faster. \sa at(), operator[]() */ /*! \fn T dtkMathArray::value(qlonglong index, const T &defaultValue) const \overload If the \a index is out of bounds, the function returns \a defaultValue. */ /*! \fn T *dtkMathArray::extend(qlonglong size) Extends this array by \a size elements and returns a pointer to the storage, which is not initialized. The pointer is only valid until the array is reallocated or destroyed. The append() or resize() functions are recommended if T is a complex type, with extend() only used for simple types. Because the storage is not initialized, the caller should use the in-place new operator to set elements: \code dtkMathArray<QRegExp> array; QRegExp *space = array.extend(1); new (space) QRegExp(QLatin1String("exp")); \endcode \sa append(), resize() */ /*! \fn void dtkMathArray::append(const T &value) Appends \a value to this array. \sa prepend(), insert() */ /*! \fn void dtkMathArray::append(const T &value1, const T &value2) \overload Appends \a value1 and \a value2 to this array. */ /*! \fn void dtkMathArray::append(const T &value1, const T &value2, const T &value3) \overload Appends \a value1, \a value2, and \a value3 to this array. */ /*! \fn void dtkMathArray::append(const T &value1, const T &value2, const T &value3, const T &value4) \overload Appends \a value1, \a value2, \a value3, and \a value4 to this array. */ /*! \fn void dtkMathArray::append(const T *values, qlonglong count) Appends the \a count elements of \a values to this array. */ /*! \fn void dtkMathArray::append(const dtkMathArray<T, PreallocSize> &other) Appends the elements of \a other to this array. */ /*! \fn void dtkMathArray::prepend(const T &value) Prepends \a value to this array. \sa append(), insert() */ /*! \fn void dtkMathArray::insert(qlonglong index, const T &value) Inserts \a value at position \a index in this array. If \a index is 0, then \a value is prepended to the array. If \a index is size(), then \a value is appended to the array. \sa append(), prepend() */ /*! \fn void dtkMathArray::insert(qlonglong index, qlonglong count, const T &value) \overload Inserts \a count copies of \a value at position \a index in this array. */ /*! \fn dtkMathArray::iterator dtkMathArray::insert(iterator before, qlonglong count, const T &value) Inserts \a count copies of \a value in front of the item pointed to by the iterator \a before. Returns an iterator pointing at the first of the inserted items. */ /*! \fn dtkMathArray::iterator dtkMathArray::insert(iterator before, const T &value) \overload Inserts \a value in front of the item pointed to by the iterator \a before. Returns an iterator pointing at the inserted item. */ /*! \fn void dtkMathArray::replace(qlonglong index, const T &value) Replaces the element at \a index with \a value. \sa operator[](), remove() */ /*! \fn void dtkMathArray::replace(qlonglong index, const T *values, qlonglong count) \overload Replaces the \a count elements of this array with the contents of \a values, starting at \a index. If (\a index + \a count) is larger than the current size of this array, the array will be extended to that size. \sa append() */ /*! \fn void dtkMathArray::remove(qlonglong index) \overload Removes the element at position \a index in this array. */ /*! \fn void dtkMathArray::remove(qlonglong index, qlonglong count) Removes the \a count elements starting at position \a index in this array. If \a index or \a count is out of range, the set of removed elements will be truncated to those that are in range. */ /*! \fn dtkMathArray::iterator dtkMathArray::erase(iterator begin, iterator end) \overload Removes all the items from \a begin up to (but not including) \a end. Returns an iterator to the same item that \a end referred to before the call. */ /*! \fn dtkMathArray::iterator dtkMathArray::erase(iterator pos) Removes the item pointed to by the iterator \a pos from the vector, and returns an iterator to the next item in the vector (which may be end()). \sa insert(), remove() */ /*! \fn void dtkMathArray::removeFirst() Removes the first element from this array. Does nothing if the array is empty. \sa remove(), removeLast() */ /*! \fn void dtkMathArray::removeLast() Removes the last element from this array. Does nothing if the array is empty. \sa remove(), removeFirst() */ /*! \fn qlonglong dtkMathArray::indexOf(const T &value, qlonglong from) const Returns the index position of the first occurrence of \a value in the array, searching forward from index position \a from. Returns -1 if no item matched. If \a from is negative, then it indicates an index position relative to the end of the array, -1 being the last index position. This function requires the value type T to have an implementation of \c operator==(). \sa lastIndexOf(), contains() */ /*! \fn qlonglong dtkMathArray::lastIndexOf(const T &value, qlonglong from) const Returns the index position of the last occurrence of \a value in the array, searching backward from index position \a from. Returns -1 if no item matched. If \a from is negative, then it indicates an index position relative to the end of the array, -1 being the last index position. The default for \a from is -1. This function requires the value type T to have an implementation of \c operator==(). \sa indexOf(), contains() */ /*! \fn bool dtkMathArray::contains(const T &value) const Returns true if the array contains an occurrence of \a value; false otherwise. This function requires the value type T to have an implementation of \c operator==(). \sa indexOf(), count() */ /*! \fn qlonglong dtkMathArray::count(const T &value) const Returns the number of occurrences of \a value in the array. This function requires the value type T to have an implementation of \c operator==(). \sa contains(), indexOf() */ /*! \fn void dtkMathArray::resize(qlonglong size) Sets the size of the array to \a size. If \a size is greater than the current size, elements are added to the end and are initialized to a default-constructed value. If \a size is less than the current size, elements are removed from the end. \sa size(), reserve(), squeeze() */ /*! \fn void dtkMathArray::reserve(qlonglong size) Increases the capacity of this array to reserve space for at least \a size elements. If the capacity is already larger than \a size, this function does nothing; in particular, it does not remove elements from the array like resize() does. This function can be useful when you know how roughly many elements will be appended ahead of time. Reserving the space once can avoid unnecessary realloc operations later. \sa capacity(), resize(), squeeze() */ /*! \fn void dtkMathArray::squeeze() Releases any memory not required to store the array's elements by reducing its capacity() to size(). This function is intended for reclaiming memory in an array that is being used over and over with different contents. As elements are added to an array, it will be constantly expanded in size. This function can realloc the array to a smaller size to reclaim unused memory. \sa reserve(), capacity() */ /*! \fn dtkMathArray<T, PreallocSize> &dtkMathArray::fill(const T &value, qlonglong size) Assigns \a value to all items in the array. If \a size is different from -1 (the default), the array is resized to \a size beforehand. Returns a reference to the array. \sa resize() */ /*! \fn void dtkMathArray::reverse() Reverses the order of this array in place. \sa reversed() */ /*! \fn dtkMathArray<T, PreallocSize> dtkMathArray::reversed() const Returns a copy of this array with elements in the reverse order. \sa reverse() */ /*! \fn dtkMathArray<T, PreallocSize> dtkMathArray::mid(qlonglong index, qlonglong length) const Returns an array containing the \a length elements of this array, starting at \a index. If \a length is less than zero, or extends further than the end of the array, then all elements extending from \a index to the end of the array will be included in the return value. \sa left(), right() */ /*! \fn dtkMathArray<T, PreallocSize> dtkMathArray::left(qlonglong length) const; Returns an array containing the first \a length elements of this array. If \a length is less than zero, or greater than size(), then all elements in this array will be included in the return value. \sa mid(), right() */ /*! \fn dtkMathArray<T, PreallocSize> dtkMathArray::right(qlonglong length) const; Returns an array containing the last \a length elements of this array. If \a length is less than zero, or greater than size(), then all elements in this array will be included in the return value. \sa mid(), left() */ /*! \fn void dtkMathArray::setRawData(const T *raw_data, qlonglong size, RawDataType data_type = ReadOnly) Sets the array using the raw data \a raw_data of \a size elements. By default, the input \a raw_data is of type dtkMathArray::ReadOnly which means that any modification of the content or the shape of the array leads to a copy according to COW principles. If the input \a raw_data is of type dtkMathArray::Writable, then its elements can be modified in-place. The copy only occurs when the shape of the array is enlarged. \sa rawData(), constRawData(), fromWritableRawData(), fromRawData() */ /*! \fn T *dtkMathArray::rawData() Returns a pointer to the data stored in the array. The pointer can be used to access and modify the items in the array. The pointer remains valid as long as the array isn't reallocated. This function is mostly useful to pass an array to a function that accepts a plain C++ array. It may make a deep copy of the array's elements if the array is implicitly shared. \sa constRawData(), operator[]() */ /*! \fn const T *dtkMathArray::rawData() const \overload */ /*! \fn const T *dtkMathArray::constRawData() const Returns a const pointer to the data stored in the array. The pointer can be used to access the items in the array. The pointer remains valid as long as the array isn't reallocated. This function is mostly useful to pass an array to a function that accepts a plain C++ array. \sa rawData(), operator[]() */ /*! \fn dtkMathArray<T, PreallocSize> dtkMathArray::fromRawData(const T *data, qlonglong size) Returns an array consisting of the \a size elements from \a data. This function takes a reference to \a data, but does not copy the elements until the array is modified. The memory at \a data must remain valid until the returned array is destroyed or modified. Use append() instead of fromRawData() to force a copy to be made of the elements at \a data when the array is created: \code // Makes a copy of the data immediately. dtkMathArray<float> array; array.append(data, size); // Does not make a copy of the data until the array is modified. dtkMathArray<float> array; array = dtkMathArray<float>::fromRawData(data, size); \endcode \sa fromWritableRawData(), append() */ /*! \fn dtkMathArray<T, PreallocSize> dtkMathArray::fromWritableRawData(T *data, qlonglong size) Returns an array consisting of the \a size elements from \a data. This function takes a reference to \a data, but does not copy the elements until the array is reallocated to a larger size. The memory at \a data must remain valid until the returned array is destroyed or reallocated. The elements of \a data will be modified in-place. This differs from fromRawData() which will make a copy of the elements of \a data when the array is modified. If the returned array is resized to less than \a size, then a copy will not be made, and append() can be used to append new items up to \a size. Further calls to append() after \a size will force the array to be reallocated. If the returned array is resized to more than \a size, then a copy of the data will be made and further modifications will not affect the elements at \a data. \sa fromRawData() */ /*! \fn bool dtkMathArray::operator==(const dtkMathArray<T, PreallocSize> &other) const Returns true if \a other is equal to this array; otherwise returns false. Two arrays are considered equal if they contain the same values in the same order. This function requires the value type to have an implementation of \c operator==(). \sa operator!=() */ /*! \fn bool dtkMathArray::operator!=(const dtkMathArray<T, PreallocSize> &other) const Returns true if \a other is not equal to this array; otherwise returns false. Two arrays are considered equal if they contain the same values in the same order. This function requires the value type to have an implementation of \c operator==(). \sa operator==() */ /*! \fn dtkMathArray<T, PreallocSize> &dtkMathArray::operator+=(const T &value) \overload Appends \a value to this array and returns a reference to this array. \sa operator<<(), append() */ /*! \fn dtkMathArray<T, PreallocSize> &dtkMathArray::operator+=(const dtkMathArray<T, PreallocSize> &other) Appends the elements of the \a other array to this array and returns a reference to this array. \sa operator<<(), append() */ /*! \fn dtkMathArray<T, PreallocSize> &dtkMathArray::operator<<(const T &value) \overload Appends \a value to this array and returns a reference to this array. \sa operator+=(), append() */ /*! \fn dtkMathArray<T, PreallocSize> &dtkMathArray::operator<<(const dtkMathArray<T, PreallocSize> &other) Appends the elements of the \a other array to this array and returns a reference to this array. \sa operator+=(), append() */ /*! \typedef dtkMathArray::iterator The dtkMathArray::iterator typedef provides an STL-style non-const iterator for dtkMathArray. The iterator is simply a typedef for "T *" (pointer to T). \sa dtkMathArray::begin(), dtkMathArray::const_iterator */ /*! \typedef dtkMathArray::const_iterator The dtkMathArray::iterator typedef provides an STL-style const iterator for dtkMathArray. The iterator is simply a typedef for "const T *" (pointer to const T). \sa dtkMathArray::constBegin(), dtkMathArray::iterator */ /*! \typedef dtkMathArray::Iterator Qt-style synonym for dtkMathArray::iterator. */ /*! \typedef dtkMathArray::ConstIterator Qt-style synonym for dtkMathArray::const_iterator. */ /*! \typedef dtkMathArray::const_pointer Typedef for const T *. Provided for STL compatibility. */ /*! \typedef dtkMathArray::const_reference Typedef for T &. Provided for STL compatibility. */ /*! \typedef dtkMathArray::difference_type Typedef for ptrdiff_t. Provided for STL compatibility. */ /*! \typedef dtkMathArray::pointer Typedef for T *. Provided for STL compatibility. */ /*! \typedef dtkMathArray::reference Typedef for T &. Provided for STL compatibility. */ /*! \typedef dtkMathArray::size_type Typedef for int. Provided for STL compatibility. */ /*! \typedef dtkMathArray::value_type Typedef for T. Provided for STL compatibility. */ /*! \fn dtkMathArray::iterator dtkMathArray::begin() Returns an STL-style iterator pointing to the first item in the array. \sa end(), constBegin(), dtkMathArray::iterator */ /*! \fn dtkMathArray::const_iterator dtkMathArray::begin() const \overload */ /*! \fn dtkMathArray::const_iterator dtkMathArray::constBegin() const Returns a const STL-style iterator pointing to the first item in the array. \sa constEnd(), begin(), dtkMathArray::const_iterator */ /*! \fn dtkMathArray::iterator dtkMathArray::end() Returns an STL-style iterator pointing to the imaginary item after the last item in the array. \sa begin(), constEnd(), dtkMathArray::iterator */ /*! \fn dtkMathArray::const_iterator dtkMathArray::end() const \overload */ /*! \fn dtkMathArray::const_iterator dtkMathArray::constEnd() const Returns a const STL-style iterator pointing to the imaginary item after the last item in the array. \sa constBegin(), end(), dtkMathArray::const_iterator */ /*! \fn T &dtkMathArray::first() Returns a reference to the first item in the array. This function assumes that the array isn't empty. \sa last(), isEmpty() */ /*! \fn const T &dtkMathArray::first() const \overload */ /*! \fn T &dtkMathArray::last() Returns a reference to the last item in the array. This function assumes that the array isn't empty. \sa first(), isEmpty() */ /*! \fn const T &dtkMathArray::last() const \overload */ /*! \fn bool dtkMathArray::startsWith(const T &value) const Returns true if this array is not empty and its first item is equal to \a value; otherwise returns false. \sa isEmpty(), first() */ /*! \fn bool dtkMathArray::endsWith(const T &value) const Returns true if this array is not empty and its last item is equal to \a value; otherwise returns false. \sa isEmpty(), last() */ /*! \fn void dtkMathArray::push_back(const T &value) This function is provided for STL compatibility. It is equivalent to append(\a value). */ /*! \fn void dtkMathArray::push_front(const T &value) This function is provided for STL compatibility. It is equivalent to prepend(\a value). */ /*! \fn void dtkMathArray::pop_front() This function is provided for STL compatibility. It is equivalent to removeFirst(). */ /*! \fn void dtkMathArray::pop_back() This function is provided for STL compatibility. It is equivalent to removeLast(). */ /*! \fn dtkMathArray::reference dtkMathArray::front() This function is provided for STL compatibility. It is equivalent to first(). */ /*! \fn dtkMathArray::const_reference dtkMathArray::front() const \overload */ /*! \fn dtkMathArray::reference dtkMathArray::back() This function is provided for STL compatibility. It is equivalent to last(). */ /*! \fn dtkMathArray::const_reference dtkMathArray::back() const \overload */ /*! \fn bool dtkMathArray::empty() const This function is provided for STL compatibility. It is equivalent to isEmpty(), returning true if the array is empty; otherwise returns false. */ #ifndef QT_NO_DATASTREAM /*! \fn QDataStream& operator<<(QDataStream& stream, const dtkMathArray<T, PreallocSize>& array) \relates dtkMathArray Writes \a array to the given \a stream and returns a reference to the \a stream. */ /*! \fn QDataStream& operator>>(QDataStream& stream, dtkMathArray<T, PreallocSize>& array) \relates dtkMathArray Reads \a array from the given \a stream and returns a reference to the \a stream. */ #endif qlonglong dtkMathArrayAllocMore(qlonglong alloc, qlonglong extra, qlonglong sizeOfT) { if (alloc == 0 && extra == 0) return 0; // Set the maximum allocatable value (= LLONG_MAX) qlonglong maximum = (quint64(1) << 63) - 1; const qlonglong page = 1 << 12; qlonglong nalloc; alloc += extra; alloc *= sizeOfT; // don't do anything if the loop will overflow signed int. if (alloc >= maximum/2) return maximum / sizeOfT; nalloc = (alloc < page) ? 64 : page; while (nalloc < alloc) { if (nalloc <= 0) return maximum / sizeOfT; nalloc *= 2; } return nalloc / sizeOfT; } // /////////////////////////////////////////////////////////////////// // Credits // /////////////////////////////////////////////////////////////////// /**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt3D module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/
// Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Unit tests for denial-of-service detection/prevention code #include "chainparams.h" #include "keystore.h" #include "net.h" #include "net_processing.h" #include "pow.h" #include "script/sign.h" #include "serialize.h" #include "util.h" #include "validation.h" #include "test/test_bitcoin.h" #include <stdint.h> #include <boost/test/unit_test.hpp> // Tests these internal-to-net_processing.cpp methods: extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer); extern void EraseOrphansFor(NodeId peer); extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans); struct COrphanTx { CTransactionRef tx; NodeId fromPeer; int64_t nTimeExpire; }; extern std::map<uint256, COrphanTx> mapOrphanTransactions; CService ip(uint32_t i) { struct in_addr s; s.s_addr = i; return CService(CNetAddr(s), Params().GetDefaultPort()); } static NodeId id = 0; BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup) BOOST_AUTO_TEST_CASE(DoS_banning) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); CAddress addr1(ip(0xa0b0c001), NODE_NONE); CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, CAddress(), "", true); dummyNode1.SetSendVersion(PROTOCOL_VERSION); GetNodeSignals().InitializeNode(&dummyNode1, *connman); dummyNode1.nVersion = 1; dummyNode1.fSuccessfullyConnected = true; Misbehaving(dummyNode1.GetId(), 100); // Should get banned SendMessages(&dummyNode1, *connman, interruptDummy); BOOST_CHECK(connman->IsBanned(addr1)); BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned CAddress addr2(ip(0xa0b0c002), NODE_NONE); CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, CAddress(), "", true); dummyNode2.SetSendVersion(PROTOCOL_VERSION); GetNodeSignals().InitializeNode(&dummyNode2, *connman); dummyNode2.nVersion = 1; dummyNode2.fSuccessfullyConnected = true; Misbehaving(dummyNode2.GetId(), 50); SendMessages(&dummyNode2, *connman, interruptDummy); BOOST_CHECK(!connman->IsBanned(addr2)); // 2 not banned yet... BOOST_CHECK(connman->IsBanned(addr1)); // ... but 1 still should be Misbehaving(dummyNode2.GetId(), 50); SendMessages(&dummyNode2, *connman, interruptDummy); BOOST_CHECK(connman->IsBanned(addr2)); } BOOST_AUTO_TEST_CASE(DoS_banscore) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); gArgs.ForceSetArg("-banscore", "111"); // because 11 is my favorite number CAddress addr1(ip(0xa0b0c001), NODE_NONE); CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, CAddress(), "", true); dummyNode1.SetSendVersion(PROTOCOL_VERSION); GetNodeSignals().InitializeNode(&dummyNode1, *connman); dummyNode1.nVersion = 1; dummyNode1.fSuccessfullyConnected = true; Misbehaving(dummyNode1.GetId(), 100); SendMessages(&dummyNode1, *connman, interruptDummy); BOOST_CHECK(!connman->IsBanned(addr1)); Misbehaving(dummyNode1.GetId(), 10); SendMessages(&dummyNode1, *connman, interruptDummy); BOOST_CHECK(!connman->IsBanned(addr1)); Misbehaving(dummyNode1.GetId(), 1); SendMessages(&dummyNode1, *connman, interruptDummy); BOOST_CHECK(connman->IsBanned(addr1)); gArgs.ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD)); } BOOST_AUTO_TEST_CASE(DoS_bantime) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); int64_t nStartTime = GetTime(); SetMockTime(nStartTime); // Overrides future calls to GetTime() CAddress addr(ip(0xa0b0c001), NODE_NONE); CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, CAddress(), "", true); dummyNode.SetSendVersion(PROTOCOL_VERSION); GetNodeSignals().InitializeNode(&dummyNode, *connman); dummyNode.nVersion = 1; dummyNode.fSuccessfullyConnected = true; Misbehaving(dummyNode.GetId(), 100); SendMessages(&dummyNode, *connman, interruptDummy); BOOST_CHECK(connman->IsBanned(addr)); SetMockTime(nStartTime+60*60); BOOST_CHECK(connman->IsBanned(addr)); SetMockTime(nStartTime+60*60*24+1); BOOST_CHECK(!connman->IsBanned(addr)); } CTransactionRef RandomOrphan() { std::map<uint256, COrphanTx>::iterator it; it = mapOrphanTransactions.lower_bound(InsecureRand256()); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); return it->second.tx; } BOOST_AUTO_TEST_CASE(DoS_mapOrphans) { CKey key; key.MakeNewKey(true); CBasicKeyStore keystore; keystore.AddKey(key); // 50 orphan transactions: for (int i = 0; i < 50; i++) { CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = InsecureRand256(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); AddOrphanTx(MakeTransactionRef(tx), i); } // ... and 50 that depend on other orphans: for (int i = 0; i < 50; i++) { CTransactionRef txPrev = RandomOrphan(); CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = txPrev->GetHash(); tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL); AddOrphanTx(MakeTransactionRef(tx), i); } // This really-big orphan should be ignored: for (int i = 0; i < 10; i++) { CTransactionRef txPrev = RandomOrphan(); CMutableTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); tx.vin.resize(2777); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = j; tx.vin[j].prevout.hash = txPrev->GetHash(); } SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL); // Re-use same signature for other inputs // (they don't have to be valid for this test) for (unsigned int j = 1; j < tx.vin.size(); j++) tx.vin[j].scriptSig = tx.vin[0].scriptSig; BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i)); } // Test EraseOrphansFor: for (NodeId i = 0; i < 3; i++) { size_t sizeBefore = mapOrphanTransactions.size(); EraseOrphansFor(i); BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore); } // Test LimitOrphanTxSize() function: LimitOrphanTxSize(40); BOOST_CHECK(mapOrphanTransactions.size() <= 40); LimitOrphanTxSize(10); BOOST_CHECK(mapOrphanTransactions.size() <= 10); LimitOrphanTxSize(0); BOOST_CHECK(mapOrphanTransactions.empty()); } BOOST_AUTO_TEST_SUITE_END()
/* * Copyright 2016 The Cartographer Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cartographer/common/time.h" #include <string> #include <iostream> #include <iomanip> namespace cartographer { namespace common { Duration FromSeconds(const double seconds) { return std::chrono::duration_cast<Duration>( std::chrono::duration<double>(seconds)); } double ToSeconds(const Duration duration) { return std::chrono::duration_cast<std::chrono::duration<double>>(duration) .count(); } Time FromUniversal(const int64 ticks) { return Time(Duration(ticks)); } int64 ToUniversal(const Time time) { return time.time_since_epoch().count(); } double TicksToUnixSeconds(int64 ticks) { //return double(std::chrono::duration_cast<std::chrono::seconds>(time.time_since_epoch()).count()); return double(ticks) * double(0.0000001) - double(kUtsEpochOffsetFromUnixEpochInSeconds); } double ToUniversalDouble(const Time time) { //return double(time.time_since_epoch().count() - int64(636469000000000000)); return double(time.time_since_epoch().count()); } std::ostream& operator<<(std::ostream& os, const Time time) { os << std::to_string(ToUniversal(time)); return os; } common::Duration FromMilliseconds(const int64 milliseconds) { return std::chrono::duration_cast<Duration>( std::chrono::milliseconds(milliseconds)); } } // namespace common } // namespace cartographer
#include <vector> #include <iostream> #include <climits> #include <algorithm> #include <queue> #include <stack> #include <map> #define Max(a, b) a > b ? a : b #define Min(a, b) a < b ? a : b using namespace std; class Solution { public: int smallestRangeI(vector<int>& A, int K) { int max = INT_MIN; int min = INT_MAX; for (int i=0;i<A.size();i++) { if(max < A[i]) { max = A[i]; } if(min > A[i]) { min = A[i]; } } max -= K; min += K; if(max < min) return 0; return max - min; } }; int main() { Solution s; vector<int> c { 1,3,6 }; string str = "codeleet"; int k = 3; int result = s.smallestRangeI(c, k); cout<<result<<endl; }
;; xOS32 ;; Copyright (C) 2016-2017 by Omar Mohammad. use32 ; xOS GDI -- An internal graphics library used by the xOS Kernel ; Should be easy to port to other systems is_redraw_enabled db 1 align 4 text_background dd 0x000000 text_foreground dd 0xFFFFFF system_font dd font current_buffer db 0 ; 0 if the system is using the back buffer ; 1 if it's using the hardware buffer ; redraw_screen: ; Redraws the screen align 32 redraw_screen: cmp [is_redraw_enabled], 1 jne .quit cmp [current_buffer], 1 je .quit mov esi, VBE_BACK_BUFFER mov edi, VBE_PHYSICAL_BUFFER mov ecx, [screen.screen_size_dqwords] .loop: prefetchnta [esi+0x80] prefetchnta [esi+0x100] movdqa xmm0, [esi] movdqa xmm1, [esi+0x10] movdqa xmm2, [esi+0x20] movdqa xmm3, [esi+0x30] movdqa xmm4, [esi+0x40] movdqa xmm5, [esi+0x50] movdqa xmm6, [esi+0x60] movdqa xmm7, [esi+0x70] movdqa [edi], xmm0 movdqa [edi+0x10], xmm1 movdqa [edi+0x20], xmm2 movdqa [edi+0x30], xmm3 movdqa [edi+0x40], xmm4 movdqa [edi+0x50], xmm5 movdqa [edi+0x60], xmm6 movdqa [edi+0x70], xmm7 add esi, 128 add edi, 128 loop .loop .quit: ret ; get_screen_info: ; Returns the screen information ; In\ Nothing ; Out\ AX/BX = X/Y resolution ; Out\ CL = Bits per pixel (always 32 because xOS only supports 32-bit mode) align 32 get_screen_info: mov eax, [screen.width] mov ebx, [screen.height] mov ecx, [screen.bpp] ret ; use_back_buffer: ; Forces the system to use the back buffer align 32 use_back_buffer: mov [current_buffer], 0 ret ; use_front_buffer: ; Forces the system to use the hardware framebuffer align 32 use_front_buffer: mov [current_buffer], 1 ret ; lock_screen: ; Prevents screen redraws while using the back buffer align 32 lock_screen: mov [is_redraw_enabled], 0 ret ; unlock_screen: ; Enables screen redraws while using the back buffer align 32 unlock_screen: mov [is_redraw_enabled], 1 ret ; get_pixel_offset: ; Gets pixel offset ; In\ AX/BX = X/Y pos ; Out\ ESI = Offset within hardware framebuffer ; Out\ EDI = Offset within back buffer ; Note: ; If the system is using the hardware framebuffer (i.e. current_buffer is set to 1), ESI and EDI are swapped. ; This tricks the GDI into writing directly to the hardware framebuffer, and preventing manual screen redraws. ; This is needed for the mouse cursor. ;) align 32 get_pixel_offset: and eax, 0xFFFF and ebx, 0xFFFF push eax ; x mov ax, bx mov ebx, [screen.bytes_per_line] mul ebx ; y*pitch pop ebx ; ebx=x shl ebx, 2 ; mul 4 add eax, ebx mov esi, eax mov edi, eax add esi, VBE_PHYSICAL_BUFFER add edi, VBE_BACK_BUFFER cmp [current_buffer], 1 je .swap ret .swap: xchg esi, edi ; swap ;) ret ; put_pixel: ; Puts a pixel ; In\ AX/BX = X/Y pos ; In\ EDX = Color ; Out\ Nothing align 32 put_pixel: push edx call get_pixel_offset pop eax stosd call redraw_screen ret ; clear_screen: ; Clears the screen ; In\ EBX = Color ; Out\ Nothing align 32 clear_screen: ;mov [screen.x], 0 ;mov [screen.y], 0 cmp [current_buffer], 0 je .back .front: mov edi, VBE_PHYSICAL_BUFFER mov ecx, [screen.screen_size] shr ecx, 2 mov eax, ebx rep stosd ret .back: mov edi, VBE_BACK_BUFFER mov ecx, [screen.screen_size] shr ecx, 2 mov eax, ebx rep stosd call redraw_screen ret ; render_char: ; Renders a character ; In\ AL = Character ; In\ CX/DX = X/Y pos ; In\ ESI = Font data ; Out\ Nothing align 32 render_char: and eax, 0xFF shl eax, 4 add eax, esi mov [.font_data], eax mov ax, cx mov bx, dx call get_pixel_offset xor dl, dl mov [.row], dl mov [.column], dl mov esi, [.font_data] mov dl, [esi] inc [.font_data] .put_column: ;mov dl, [.byte] test dl, 0x80 jz .background .foreground: mov eax, [text_foreground] jmp .put .background: mov eax, [text_background] .put: stosd jmp .next_column .next_column: inc [.column] cmp [.column], 8 je .next_row shl dl, 1 jmp .put_column .next_row: mov [.column],0 inc [.row] cmp [.row], 16 je .done mov eax, [screen.bytes_per_pixel] shl eax, 3 sub edi, eax add edi, [screen.bytes_per_line] mov esi, [.font_data] mov dl, [esi] inc [.font_data] jmp .put_column .done: ret align 32 .font_data dd 0 .row db 0 .column db 0 ; render_char_transparent: ; Renders a character with transparent background ; In\ AL = Character ; In\ CX/DX = X/Y pos ; In\ ESI = Font data ; Out\ Nothing align 32 render_char_transparent: and eax, 0xFF shl eax, 4 add eax, esi mov [.font_data], eax mov ax, cx mov bx, dx call get_pixel_offset xor dl, dl mov [.row], dl mov [.column], dl mov esi, [.font_data] mov dl, [esi] inc [.font_data] .put_column: ;mov dl, [.byte] test dl, 0x80 jz .background .foreground: mov eax, [text_foreground] .put: stosd jmp .next_column .background: add edi, 4 .next_column: inc [.column] cmp [.column], 8 je .next_row shl dl, 1 jmp .put_column .next_row: mov [.column],0 inc [.row] cmp [.row], 16 je .done sub edi, 8*4 add edi, [screen.bytes_per_line] mov esi, [.font_data] mov dl, [esi] inc [.font_data] jmp .put_column .done: ret align 32 .font_data dd 0 .row db 0 .column db 0 ; set_font: ; Sets the system font ; In\ ESI = 4k buffer to use as font ; Out\ Nothing align 32 set_font: mov [system_font], esi ret ; set_text_color: ; Sets the text color ; In\ EBX = Background ; In\ ECX = Foreground ; Out\ Nothing align 32 set_text_color: mov [text_background], ebx mov [text_foreground], ecx ret ; print_string: ; Prints a string ; In\ ESI = String ; In\ CX/DX = X/Y pos ; Out\ Nothing align 32 print_string: mov [.x], cx mov [.y], dx mov [.ox], cx mov [.oy], dx .loop: lodsb or al, al jz .done cmp al, 13 je .carriage cmp al, 10 je .newline push esi mov cx, [.x] mov dx, [.y] mov esi, font call render_char pop esi add [.x], 8 jmp .loop .carriage: mov ax, [.ox] mov [.x], ax jmp .loop .newline: mov ax, [.ox] mov [.x], ax add [.y], 16 jmp .loop .done: call redraw_screen ret .x dw 0 .y dw 0 .ox dw 0 .oy dw 0 ; print_string_transparent: ; Prints a string with transparent background ; In\ ESI = String ; In\ CX/DX = X/Y pos ; Out\ Nothing align 32 print_string_transparent: mov [.x], cx mov [.y], dx mov [.ox], cx mov [.oy], dx .loop: lodsb or al, al jz .done cmp al, 13 je .carriage cmp al, 10 je .newline push esi mov cx, [.x] mov dx, [.y] mov esi, font call render_char_transparent pop esi add [.x], 8 jmp .loop .carriage: mov ax, [.ox] mov [.x], ax jmp .loop .newline: mov ax, [.ox] mov [.x], ax add [.y], 16 jmp .loop .done: call redraw_screen ret .x dw 0 .y dw 0 .ox dw 0 .oy dw 0 ; scroll_screen: ; Scrolls the screen align 32 scroll_screen: pusha mov esi, [screen.bytes_per_line] shl esi, 4 ; mul 16 add esi, VBE_BACK_BUFFER mov edi, VBE_BACK_BUFFER mov ecx, [screen.screen_size] call memcpy mov [screen.x], 0 mov eax, [screen.y_max] mov [screen.y], eax popa ret ; put_char: ; Puts a char at cursor position ; In\ AL = Character ; Out\ Nothing align 32 put_char: pusha cmp al, 13 je .carriage cmp al, 10 je .newline .start: mov edx, [screen.x_max] cmp [screen.x], edx jg .new_y mov edx, [screen.y_max] cmp [screen.y], edx jg .scroll mov ecx, [screen.x] mov edx, [screen.y] shl ecx, 3 shl edx, 4 mov esi, [system_font] call render_char inc [screen.x] .done: call redraw_screen popa ret .new_y: mov [screen.x], 0 inc [screen.y] mov edx, [screen.y_max] cmp [screen.y], edx jg .scroll jmp .start .scroll: call scroll_screen jmp .start .carriage: mov [screen.x], 0 jmp .done .newline: mov [screen.x], 0 inc [screen.y] mov edx, [screen.y_max] cmp [screen.y], edx jg .scroll_newline jmp .done .scroll_newline: call scroll_screen jmp .done ; fill_rect: ; Fills a rectangle ; In\ AX/BX = X/Y pos ; In\ SI/DI = Width/Height ; In\ EDX = Color ; Out\ Nothing align 32 fill_rect: mov [.x], ax mov [.y], bx mov [.width], si mov [.height], di mov [.color], edx movzx eax, [.width] mov ebx, [screen.bytes_per_pixel] mul ebx mov [.bytes_per_line], eax ; one line of rect mov ax, [.x] mov bx, [.y] call get_pixel_offset mov [.offset], edi mov [.current_line], 0 .loop: mov edi, [.offset] mov eax, [.color] mov ecx, [.bytes_per_line] shr ecx, 2 rep stosd .next_line: inc [.current_line] mov cx, [.height] cmp [.current_line], cx jge .done mov eax, [screen.bytes_per_line] add [.offset], eax jmp .loop .done: call redraw_screen ret align 32 .x dw 0 .y dw 0 .width dw 0 .height dw 0 .color dd 0 .offset dd 0 .bytes_per_line dd 0 .current_line dw 0 ; blit_buffer: ; Blits a pixel buffer ; In\ AX/BX = X/Y pos ; In\ SI/DI = Width/Height ; In\ ECX = Transparent color ; In\ EDX = Pixel buffer ; Out\ Nothing align 32 blit_buffer: mov [.transparent], ecx mov [.x], ax mov [.y], bx mov [.width], si mov [.height], di add ax, si add bx, di mov [.end_x], ax mov [.end_y], bx mov [.buffer], edx mov [.current_line], 0 mov ax, [.x] mov bx, [.y] call get_pixel_offset mov [.offset], edi .start: mov esi, [.buffer] mov edi, [.offset] movzx ecx, [.width] mov edx, [.transparent] jmp .loop align 64 .loop: lodsd cmp eax, edx je .skip stosd loop .loop jmp .line_done .skip: add edi, 4 loop .loop .line_done: mov [.buffer], esi mov eax, [screen.bytes_per_line] add [.offset], eax inc [.current_line] movzx eax, [.height] cmp [.current_line], eax jge .done jmp .start .done: call redraw_screen ret align 4 .transparent dd 0 .x dw 0 .y dw 0 .width dw 0 .height dw 0 .end_x dw 0 .end_y dw 0 align 4 .buffer dd 0 .offset dd 0 .current_line dd 0 ; blit_buffer_no_transparent: ; Blits a pixel buffer (same as above, but without support for transparent colors) ; In\ AX/BX = X/Y pos ; In\ SI/DI = Width/Height ; In\ EDX = Pixel buffer ; Out\ Nothing align 32 blit_buffer_no_transparent: mov [.x], ax mov [.y], bx mov [.width], si mov [.height], di add ax, si add bx, di mov [.end_x], ax mov [.end_y], bx mov [.buffer], edx mov [.current_line], 0 mov ax, [.x] mov bx, [.y] call get_pixel_offset mov [.offset], edi .start: mov esi, [.buffer] mov edi, [.offset] movzx ecx, [.width] .loop: shl ecx, 2 call memcpy ; SSE memcpy .line_done: mov [.buffer], esi mov eax, [screen.bytes_per_line] add [.offset], eax inc [.current_line] movzx eax, [.height] cmp [.current_line], eax jge .done jmp .start .done: call redraw_screen ret align 32 .x dw 0 .y dw 0 .width dw 0 .height dw 0 .end_x dw 0 .end_y dw 0 align 32 .buffer dd 0 .offset dd 0 .current_line dd 0 ; decode_bmp: ; Decodes a 24-bit BMP image ; In\ EDX = Pointer to image data ; In\ EBX = Pointer to memory location to store raw pixel buffer ; Out\ ECX = Size of raw pixel buffer in bytes, -1 on error ; Out\ SI/DI = Width/Height of image align 32 decode_bmp: mov [.image], edx mov [.memory], ebx mov esi, [.image] cmp word[esi], "BM" ; bmp image signature jne .bad mov esi, [.image] mov eax, [esi+18] mov [.width], eax mov eax, [esi+22] mov [.height], eax mov eax, [.width] mov ebx, [.height] mul ebx mov [.size_pixels], eax shl eax, 2 mov [.buffer_size], eax mov esi, [.image] add esi, 10 mov esi, [esi] add esi, [.image] mov edi, [.memory] mov ecx, [.size_pixels] .copy_loop: movsw movsb mov al, 0 stosb loop .copy_loop .done: mov edx, [.memory] mov esi, [.width] mov edi, [.height] call invert_buffer_vertically mov esi, [.width] mov edi, [.height] mov ecx, [.buffer_size] ret .bad: mov ecx, -1 mov esi, 0 mov edi, 0 ret align 32 .image dd 0 .memory dd 0 .width dd 0 .height dd 0 .size_pixels dd 0 .buffer_size dd 0 ; invert_buffer_vertically: ; Inverts a pixel buffer vertically ; In\ EDX = Pointer to pixel data ; In\ SI/DI = Width/Height ; Out\ Buffer inverted align 32 invert_buffer_vertically: mov [.buffer], edx mov [.width], si mov [.height], di movzx eax, [.width] shl eax, 2 mov [.bytes_per_line], eax movzx eax, [.height] dec eax mov ebx, [.bytes_per_line] mul ebx add eax, [.buffer] mov [.last_line], eax mov esi, [.buffer] mov edi, [.last_line] .loop: cmp esi, edi jge .done mov ecx, [.bytes_per_line] call memxchg add esi, [.bytes_per_line] sub edi, [.bytes_per_line] jmp .loop .done: ret align 32 .buffer dd 0 .width dw 0 .height dw 0 align 32 .current_row dd 0 .current_line dd 0 .bytes_per_line dd 0 .last_line dd 0 ; stretch_buffer: ; Stretches a pixel buffer ; In\ EDX = Pointer to image data ; In\ AX/BX = Current width/height ; In\ SI/DI = New width/height ; Out\ EAX = Pointer to pixel buffer stretch_buffer: mov [.old_buffer], edx mov [.old_width], ax mov [.old_height], bx mov [.new_width], si mov [.new_height], di movzx eax, [.new_width] movzx ebx, [.new_height] mul ebx mov ecx, eax shl ecx, 2 call kmalloc mov [.new_buffer], eax mov [.i], 0 mov [.j], 0 movzx eax, [.old_width] shl eax, 16 movzx ebx, [.new_width] mov edx, 0 div ebx inc eax mov [.x_ratio], eax movzx eax, [.old_height] shl eax, 16 movzx ebx, [.new_height] mov edx, 0 div ebx inc eax mov [.y_ratio], eax .loop: mov edx, [.j] cmp dx, [.new_width] jge .loop_finish mov eax, [.j] mov ebx, [.x_ratio] mul ebx shr eax, 16 mov [.x2], eax mov eax, [.i] mov ebx, [.y_ratio] mul ebx shr eax, 16 mov [.y2], eax mov eax, [.y2] movzx ebx, [.old_width] mul ebx add eax, [.x2] shl eax, 2 add eax, [.old_buffer] mov [.source], eax mov eax, [.i] movzx ebx, [.new_width] mul ebx add eax, [.j] shl eax, 2 add eax, [.new_buffer] mov [.dest], eax mov esi, [.source] mov edi, [.dest] movsd inc [.j] jmp .loop .loop_finish: mov [.j], 0 inc [.i] mov edx, [.i] cmp dx, [.new_height] jge .finish jmp .loop .finish: mov eax, [.new_buffer] ret align 2 .old_width dw 0 .old_height dw 0 .new_width dw 0 .new_height dw 0 align 4 .old_buffer dd 0 .new_buffer dd 0 .i dd 0 .j dd 0 .x_ratio dd 0 .y_ratio dd 0 .x2 dd 0 .y2 dd 0 .source dd 0 .dest dd 0 ; alpha_blend_colors: ; Blends two colors smoothly ; In\ EAX = Foreground ; In\ EBX = Background ; In\ DL = Alpha intensity (1 = less transparent, 4 = most transparent) ; Out\ EAX = New color ; Out\ EBX is destroyed align 64 alpha_blend_colors: xchg ecx, edx and eax, 0xF0F0F0 and ebx, 0xF0F0F0 ;mov cl, dl shr eax, cl shr ebx, 1 and eax, 0x7F7F7F and ebx, 0x7F7F7F add eax, ebx xchg ecx, edx ret ; alpha_fill_rect_no_sse: ; Fills a rectangle will alpha blending, without SSE ; In\ AX/BX = X/Y pos ; In\ SI/DI = Width/Height ; In\ CL = Alpha intensity ; In\ EDX = Color ; Out\ Nothing align 64 alpha_fill_rect_no_sse: ; ensure a valid alpha intensity cmp cl, 1 jl fill_rect cmp cl, 4 jg fill_rect mov [.x], ax mov [.y], bx mov [.width], si mov [.height], di mov [.intensity], cl mov [.color], edx mov [.current_line], 0 mov ax, [.x] mov bx, [.y] call get_pixel_offset mov [.offset], edi ;movzx eax, [.width] ;shl eax, 2 ; mul 4 ;mov [.bytes_per_line], eax .start: mov edi, [.offset] mov esi, [.color] ; avoid reading from memory too much for performance movzx ecx, [.width] ; counter .loop: mov ebx, [edi] ; background is the already-existing pixel mov eax, esi mov dl, [.intensity] call alpha_blend_colors stosd loop .loop .next_line: inc [.current_line] mov cx, [.height] cmp [.current_line], cx jge .done ; next offset mov edi, [screen.bytes_per_line] add [.offset], edi jmp .start .done: ret align 2 .x dw 0 .y dw 0 .width dw 0 .height dw 0 .intensity db 0 align 8 .color dd 0 .offset dd 0 .bytes_per_line dd 0 .current_line dw 0 ; ; EXPERIMENTAL SECTION: SSE-optimized alpha blending functions ; ; alpha_blend_colors_packed: ; Blends 8 colors in one SSE operation ; In\ XMM0 = Foreground 1, 4 pixels ; In\ XMM1 = Background 1, 4 pixels ; In\ XMM2 = Color mask ; In\ XMM6 = Foreground 2, 4 pixels ; In\ XMM7 = Background 2, 4 pixels ; In\ DL = Intensity ; Out\ XMM0 = New color, 4 pixels ; Out\ XMM6 = New color, 4 pixels align 32 alpha_blend_colors_packed: mov byte[.intensity], dl ;movdqa xmm2, dqword[.mask] andpd xmm0, xmm2 andpd xmm1, xmm2 andpd xmm6, xmm2 andpd xmm7, xmm2 psrlq xmm0, [.intensity] ; shift foreground by intensity psrlq xmm6, [.intensity] psrlq xmm1, 1 psrlq xmm7, 1 paddq xmm0, xmm1 paddq xmm6, xmm7 ret align 8 .intensity: dq 0 ; alpha_fill_rect: ; Fills a rectangle with alpha blending, using SSE for acceleration ; In\ AX/BX = X/Y pos ; In\ SI/DI = Width/Height ; In\ CL = Alpha intensity ; In\ EDX = Color ; Out\ Nothing align 32 alpha_fill_rect: test si, 7 ; must be multiple of 8, because the SSE function works on 8 pixels at a time jnz alpha_fill_rect_no_sse cmp cl, 1 jl fill_rect cmp cl, 4 jg fill_rect mov [.x], ax mov [.y], bx shr si, 3 ; div 8; because we'll work on 8 pixels at the same time mov [.width], si mov [.height], di mov [.alpha], cl mov dword[.color], edx mov dword[.color+4], edx mov dword[.color+8], edx mov dword[.color+12], edx mov ax, [.x] mov bx, [.y] call get_pixel_offset mov [.offset], edi mov [.current_line], 0 movdqa xmm3, dqword[.color] ; will use XMM3 to store the color movdqa xmm2, dqword[.mask] ; and XMM2 for the mask .start: test [.offset], 0x0F jnz .unaligned_start .aligned_start: mov edi, [.offset] movzx ecx, [.width] .aligned_loop: movdqa xmm0, xmm3 ; foreground movdqa xmm1, [edi] ; background movdqa xmm6, xmm3 movdqa xmm7, [edi+16] mov dl, [.alpha] call alpha_blend_colors_packed ; sse alpha blending movdqa [edi], xmm0 movdqa [edi+16], xmm6 add edi, 32 loop .aligned_loop .aligned_next_line: inc [.current_line] mov cx, [.height] cmp [.current_line], cx jge .done ; next offset mov edi, [screen.bytes_per_line] add [.offset], edi jmp .aligned_start .unaligned_start: mov edi, [.offset] movzx ecx, [.width] .unaligned_loop: movdqa xmm0, xmm3 ; foreground movdqu xmm1, [edi] ; background movdqa xmm6, xmm3 movdqu xmm7, [edi+16] mov dl, [.alpha] call alpha_blend_colors_packed ; sse alpha blending movdqu [edi], xmm0 movdqu [edi+16], xmm6 add edi, 32 loop .unaligned_loop .unaligned_next_line: inc [.current_line] mov cx, [.height] cmp [.current_line], cx jge .done ; next offset mov edi, [screen.bytes_per_line] add [.offset], edi jmp .unaligned_start .done: ret align 4 .x dw 0 .y dw 0 .width dw 0 .height dw 0 .alpha db 0 align 16 .color: times 2 dq 0 ; sse stuff ;) .offset dd 0 .current_line dw 0 align 16 .mask dq 0x00F0F0F000F0F0F0 dq 0x00F0F0F000F0F0F0
; ; Copyright (c) 2021 Alain (@AlainPlusPlus) ; ; Cascaron para juego de aventura de texto. ; Obtiene la tecla presionada por el usuario, reacciona a la opción y finaliza programa. ; section .data ;declara variables inicializadas ask db 'Pregunta/Acertijo',10,'¿Con [m]elon o con [s]andia?',10,'responde [m] o [s] para continuar: ' askLen equ $- ask melon db 'MELON!!!' melLen equ $- melon sandia db 'SANDIA!!!' sanLen equ $- sandia newLine equ 10 section .bss ;variables/espacios no inicializ@s res resb 1 section .text global _start _start: askme: mov ecx, ask mov edx, askLen call print mov eax, 3 mov ebx, 2 mov ecx, res mov edx, 5 int 80h mov eax, [res] and eax,255 cmp eax, 'm' je melonRes cmp eax, 's' je sandiaRes jmp finish melonRes: mov ecx, melon mov edx, melLen call print jmp finish sandiaRes: mov ecx, sandia mov edx, sanLen call print ; termina programa finish: mov eax, 1 mov ebx, 0 int 80h print: mov eax, 4 mov ebx, 1 int 80h ret
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r15 push %r8 push %rax push %rcx push %rdi push %rsi lea addresses_D_ht+0xb117, %rsi lea addresses_WT_ht+0x12e97, %rdi nop nop nop nop nop cmp $3882, %r8 mov $116, %rcx rep movsq nop nop nop nop nop and %r15, %r15 lea addresses_normal_ht+0x4201, %r10 nop nop nop nop xor %r15, %r15 mov (%r10), %r8 nop nop nop nop add $55100, %rdi lea addresses_normal_ht+0x19c97, %rsi lea addresses_A_ht+0x2517, %rdi nop nop nop nop sub $35496, %r13 mov $122, %rcx rep movsq nop nop nop nop mfence lea addresses_WC_ht+0x1b5c7, %rsi lea addresses_WC_ht+0x7ff, %rdi nop nop nop nop nop cmp %rax, %rax mov $48, %rcx rep movsl nop nop nop nop add $47249, %rsi lea addresses_D_ht+0x13b27, %rsi lea addresses_UC_ht+0x17697, %rdi dec %r13 mov $90, %rcx rep movsl nop nop add %r8, %r8 pop %rsi pop %rdi pop %rcx pop %rax pop %r8 pop %r15 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r14 push %r8 push %rbp push %rcx push %rdi // Faulty Load lea addresses_normal+0xc497, %r12 nop nop nop and $35763, %rcx vmovntdqa (%r12), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $0, %xmm3, %rdi lea oracles, %r14 and $0xff, %rdi shlq $12, %rdi mov (%r14,%rdi,1), %rdi pop %rdi pop %rcx pop %rbp pop %r8 pop %r14 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 16, 'AVXalign': True}, 'OP': 'LOAD'} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': True, 'type': 'addresses_normal', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_D_ht', 'congruent': 6, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': True}} {'src': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}} {'src': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}} {'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}} {'00': 293, '44': 19, '46': 15964, 'ff': 1, '48': 275} 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 48 46 46 46 48 46 46 46 46 46 48 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 48 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 00 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 48 48 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 00 00 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 48 48 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 48 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 00 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 00 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 00 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 00 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 00 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 */
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r15 push %r8 push %rbp push %rcx push %rdi push %rsi lea addresses_A_ht+0x6876, %rsi lea addresses_normal_ht+0x51e6, %rdi nop nop nop nop add $6442, %r13 mov $31, %rcx rep movsw nop nop nop sub %r8, %r8 lea addresses_normal_ht+0x2766, %rbp cmp %r15, %r15 mov (%rbp), %r13 nop nop nop nop nop sub %r15, %r15 lea addresses_A_ht+0x149b8, %rsi lea addresses_D_ht+0x1d276, %rdi nop nop dec %r15 mov $22, %rcx rep movsw nop nop nop nop cmp %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rbp pop %r8 pop %r15 pop %r13 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r15 push %r9 push %rbx push %rcx push %rdi // Store lea addresses_US+0xd0c2, %rcx nop nop nop nop nop cmp %rbx, %rbx movl $0x51525354, (%rcx) nop nop nop nop nop add %rcx, %rcx // Store lea addresses_RW+0x5de6, %rdi and $64588, %r9 mov $0x5152535455565758, %r15 movq %r15, (%rdi) nop nop nop sub %r15, %r15 // Faulty Load lea addresses_RW+0x5de6, %r12 nop nop nop sub %rcx, %rcx mov (%r12), %r9d lea oracles, %rdi and $0xff, %r9 shlq $12, %r9 mov (%rdi,%r9,1), %r9 pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': True, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_US'}} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': False, 'type': 'addresses_RW'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 4, 'NT': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 5, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_D_ht'}} {'58': 11293} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
include "xcalm.alm" include "bitset.inc" include "automata.inc" include "regex.inc" _regex?._declare? _register, _constant?._false? _regex?._compile? _register, "xmm1" ; "(x|y|z)mm([0-9]|(1[0-9])|(2[0-9])|30|31)" _regex?._match? _check, _register, "xmm1" if (_check) display "x86 Register Match" end if
AutoDocking DB 0 ; $033F PlayerECM DB 0 ; $0340 Laser2 DB 0 ; 0343 laser Power? Not sure LaserCount DB 0 ; 0346 LASCT \ laser count =9 for pulse, cooled off? Cash DB 0,0,0,0 ; 0361 - 0364 Cash now litte endian Fuel DB 25 ; 0365 QQ14 CargoBaySize DB 70 ; 036E CargoRunningLoad DB 0 CargoTonnes DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ;CargoTonnes DB 16,1,2,3,4,5,6,7,6,9,10,11,12,13,14,15 ; 036F - 037F QQ20 SlaveCargoTonnes equ CargoTonnes+3 NarcoticsCargoTonnes equ CargoTonnes+6 FirearmsCargoTonnes equ CargoTonnes+10 GoldCargoKGs: equ CargoTonnes+15 AlienItemsTonnes equ CargoTonnes+17 ; For each view laser a localised copy of the stats ; TODO - need to add code to maintain on load/save/equipment transactions LaserType DS 4 ; quick reference to laser type LaserDamagedFlag DS 4 ; probabiliy out of 255 that it will no fire, 0 = good, 255 = will not fire ; dont need as static from table LaserPulseRate DS 4 ; how many pulses can be fired before long pause ; dont need as static from table LaserPulsePause DS 4 ; time before next pulse - 0 = beam ; dont need as static from table LaserPulseRest DS 4 ; time before pulse count resets to 0 ; dont need as static from table LaserDamageOutput DS 4 ; amount of damage for a laser hit ; dont need as static from table LaserEnergyDrain DS 4 ; amount of energy drained by cycle ; dont need as static from table LaserHeat DS 4 ; amount of heat generated ; dont need as static from table LaserDurability DS 4 ; probabability out of 255 that a hit on it unshielded will add random amount of damage ; dont need as static from table LaserDurabilityAmount DS 4 ; max amount of damagage can be sustained in one damage hit QQ20 equ CargoTonnes EquipmentFitted DS EQ_ITEM_COUNT ; Series of flags for if each item is fitted ECMPresent EQU EquipmentFitted + EQ_ECM ; 0380 FuelScoop EQU EquipmentFitted + EQ_FUEL_SCOOPS EnergyBomb EQU EquipmentFitted + EQ_ENERGY_BOMB ; 0382 Also random hyperspeace in Elite A ExtraEnergyUnit EQU EquipmentFitted + EQ_ENERGY_UNIT ; 0383 DockingComputer EQU EquipmentFitted + EQ_DOCK_COMP ; 0384 GalacticHyperDrive EQU EquipmentFitted + EQ_GAL_DRIVE ; 0385 EscapePod EQU EquipmentFitted + EQ_ESCAPE_POD ; 0386 FuelScoopsBarrelStatus DB 1 ; 0381
GoBank: ; r1 = 6002,6000 BANK0, BANK1 ; r2 = address in bank to jump to ; li r0,004E0h mov r0,@SWBANK mov r1,@SWBANK+2 li r0,00460h mov r0,@SWBANK+4 mov r2,@SWBANK+6 b @SWBANK
; A105963: Expansion of (1+4*x)/(1-x-3*x^2). ; 1,5,8,23,47,116,257,605,1376,3191,7319,16892,38849,89525,206072,474647,1092863,2516804,5795393,13345805,30731984,70769399,162965351,375273548,864169601,1989990245,4582499048,10552469783,24299966927,55957376276,128857277057,296729405885,683301237056,1573489454711,3623393165879,8343861530012,19214041027649,44245625617685,101887748700632,234624625553687,540287871655583,1244161748316644,2865025363283393,6597510608233325,15192586698083504,34985118522783479,80562878617033991,185518234185384428,427206870036486401,983761572592639685,2265382182702098888,5216666900480017943,12012813448586314607,27662814150026368436,63701254495785312257,146689696945864417565,337793460433220354336,777862551270813607031,1791242932570474670039,4124830586382915491132,9498559384094339501249,21873051143243085974645,50368729295526104478392,115987882725255362402327,267094070611833675837503,615057718787599763044484,1416339930623100790556993,3261513086985900079690445,7510532878855202451361424,17295072139812902690432759,39826670776378510044517031,91711887195817218115815308,211191899524952748249366401,486327561112404402596812325,1119903259687262647344911528,2578885943024475855135348503,5938595722086263797170083087,13675253551159691362576128596,31491040717418482754086377857,72516801370897556841814763645,166989923523153005104073897216,384540327635845675629518188151,885510098205304690941739879799,2039131081112841717830294444252,4695661375728755790655514083649,10813054619067280944146397416405,24900038746253548316112939667352,57339202603455391148552131916567,132039318842216036096890950918623,304056926652582209542547346668324,700174883179230317833220199424193,1612345663136976946460862239429165,3712870312674667899960522837701744,8549907302085598739343109555989239,19688518240109602439224678069094471,45338240146366398657254006737062188,104403794866695205974928040944345601,240418515305794401946690061155532165,553629899905880019871474183988568968 mov $4,6 mov $5,2 lpb $0 sub $0,1 mov $1,$4 sub $1,$5 add $3,1 add $3,$5 add $1,$3 sub $1,3 mov $4,$3 mul $4,2 mov $5,$1 lpe trn $2,$1 add $2,5 add $1,$2 sub $1,4 mov $0,$1
// Designed by Sai Teja @ Team 11 // if(a>b) then c=a-b else c=b-a @16 // 16 refers to mem. location 16 D=M // D=a @17 // 17 refers to mem. location 17 D=D-M // D=a-b @ELSE D;JLE // If (a-b)<=0 goto ELSE @18 // 18 refers to mem. location 18 M=D // c=a-b @END-IF 0;JMP // goto END-IF (ELSE) @18 M=-D // c=b-a (END-IF) (END) @END 0;JMP // the infinite loop is a standard way to "terminate" the execution of a Hack program.
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r14 push %r15 push %r9 push %rcx push %rdi push %rsi lea addresses_normal_ht+0x15b71, %rsi lea addresses_WT_ht+0x19b91, %rdi add $54570, %r11 mov $69, %rcx rep movsl nop nop nop nop nop cmp $37455, %r10 lea addresses_WT_ht+0xcf1, %r9 clflush (%r9) cmp $31348, %r15 movups (%r9), %xmm3 vpextrq $0, %xmm3, %rcx nop nop nop nop nop sub %r10, %r10 lea addresses_WT_ht+0x174f1, %rcx nop xor $60095, %r11 mov $0x6162636465666768, %rsi movq %rsi, (%rcx) nop nop cmp %r15, %r15 lea addresses_WT_ht+0x11b21, %r9 nop nop nop nop inc %rsi mov $0x6162636465666768, %rdi movq %rdi, %xmm0 and $0xffffffffffffffc0, %r9 vmovaps %ymm0, (%r9) nop nop nop nop sub %r11, %r11 lea addresses_D_ht+0x190ae, %rdi nop nop nop nop nop cmp %rcx, %rcx mov (%rdi), %r15w nop nop nop dec %r15 lea addresses_D_ht+0x18eed, %rsi lea addresses_A_ht+0xfcf1, %rdi nop sub $46178, %r9 mov $46, %rcx rep movsl nop nop nop nop nop xor %r10, %r10 lea addresses_WC_ht+0x1b0f1, %rsi lea addresses_WC_ht+0x16bc1, %rdi sub $59720, %r15 mov $28, %rcx rep movsq nop nop cmp %rdi, %rdi lea addresses_WC_ht+0x1c2f1, %r9 nop nop nop nop xor %r15, %r15 mov $0x6162636465666768, %rdi movq %rdi, %xmm5 movups %xmm5, (%r9) nop and %r10, %r10 lea addresses_D_ht+0x15471, %rsi lea addresses_A_ht+0x1a3c9, %rdi nop nop nop inc %r14 mov $116, %rcx rep movsq nop nop nop nop cmp %r15, %r15 lea addresses_A_ht+0x1c4f1, %rsi lea addresses_normal_ht+0x1bd9, %rdi nop nop nop cmp $14641, %r10 mov $52, %rcx rep movsb nop nop nop nop nop sub %r11, %r11 lea addresses_D_ht+0x191e1, %rcx and $18926, %r14 movl $0x61626364, (%rcx) nop nop nop sub $5181, %r15 pop %rsi pop %rdi pop %rcx pop %r9 pop %r15 pop %r14 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r15 push %r8 push %rax push %rbp push %rsi // Faulty Load lea addresses_RW+0x18cf1, %r8 cmp %rbp, %rbp movb (%r8), %r15b lea oracles, %r8 and $0xff, %r15 shlq $12, %r15 mov (%r8,%r15,1), %r15 pop %rsi pop %rbp pop %rax pop %r8 pop %r15 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_RW', 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_RW', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_normal_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WT_ht', 'congruent': 10}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WT_ht', 'congruent': 11}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 32, 'type': 'addresses_WT_ht', 'congruent': 3}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_D_ht', 'congruent': 0}} {'dst': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_D_ht'}} {'dst': {'same': False, 'congruent': 4, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 8, 'type': 'addresses_WC_ht'}} {'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WC_ht', 'congruent': 7}, 'OP': 'STOR'} {'dst': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_D_ht'}} {'dst': {'same': False, 'congruent': 3, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 4, 'type': 'addresses_D_ht', 'congruent': 3}, 'OP': 'STOR'} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
// gl06.cpp : Defines the entry point for the console application. #include <stdio.h> #include <stdlib.h> // for Window // #include <GL/glut.h> // for Mac #include <GLUT/glut.h> int time = 0; void Draw(int i) { double d; glPushMatrix(); // 회전해서 그려줘!(좌표 설정) // 각각의 분마다 6도식 회전해서 그림 glRotatef(i*6, 0,0,1); // 5개마다 삼각형의 크기가 커짐 if(i%5==0) d=2.0; else d = 1.0; // 삼각형을 그림 glBegin(GL_TRIANGLES); glVertex3f(-0.01*d, 1.0, 0.0); glVertex3f( 0.01*d, 1.0, 0.0); glVertex3f( 0.0 , 1.0-0.1*d, 0.0); glEnd(); glPopMatrix(); } void changeSize(int w, int h) { if(h == 0) h = 1; float ratio = 1.0* w / h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, w, h); gluPerspective(45,ratio,1,1000); glMatrixMode(GL_MODELVIEW); } void renderScene(void) { // 깨끗하게 만듦 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); gluLookAt(0.0,0.0,5.0, 0.0,0.0,-1.0, 0.0f,1.0f,0.0f); // 핵심 // 반복문을 60번 돌며 드로우 함수 호출 for(int i=0; i<60; i++) { Draw(i); } // 바늘을 그림 glRotatef(time*-6, 0,0,1); glColor3f(0,0,0); glBegin(GL_LINES); glVertex3f(0.0,0.0,0.0); glVertex3f(0.0,1.0,0.0); glEnd(); ++time; if(time > 60){ time = 0;} glutSwapBuffers(); } void processNormalKeys(unsigned char key, int x, int y) { if (key == 27) exit(0); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100,100); glutInitWindowSize(320,320); glutCreateWindow("Animation Lecture - 00"); glutDisplayFunc(renderScene); glutIdleFunc(renderScene); glutReshapeFunc(changeSize); glutKeyboardFunc(processNormalKeys); glEnable(GL_DEPTH_TEST); glClearColor(0.8,0.8,1.0,1.0); glutMainLoop(); return 0; }
lui $1,33845 ori $1,$1,2895 lui $2,31246 ori $2,$2,63125 lui $3,57773 ori $3,$3,42625 lui $4,6612 ori $4,$4,3399 lui $5,13645 ori $5,$5,13998 lui $6,10671 ori $6,$6,18173 mthi $1 mtlo $2 sec0: nop nop nop beq $3,$2,yes0 nop no0:addiu $k1,$k1,1 yes0:addiu $k0,$k0,1 sec1: nop nop addu $2,$4,$2 beq $3,$2,yes1 nop no1:addiu $k1,$k1,1 yes1:addiu $k0,$k0,1 sec2: nop nop slti $2,$4,-4789 beq $3,$2,yes2 nop no2:addiu $k1,$k1,1 yes2:addiu $k0,$k0,1 sec3: nop nop mfhi $2 beq $3,$2,yes3 nop no3:addiu $k1,$k1,1 yes3:addiu $k0,$k0,1 sec4: nop nop lbu $2,10($0) beq $3,$2,yes4 nop no4:addiu $k1,$k1,1 yes4:addiu $k0,$k0,1 sec5: nop nor $2,$3,$0 nop beq $3,$2,yes5 nop no5:addiu $k1,$k1,1 yes5:addiu $k0,$k0,1 sec6: nop subu $2,$1,$0 slt $2,$1,$2 beq $3,$2,yes6 nop no6:addiu $k1,$k1,1 yes6:addiu $k0,$k0,1 sec7: nop addu $2,$3,$3 andi $2,$4,47188 beq $3,$2,yes7 nop no7:addiu $k1,$k1,1 yes7:addiu $k0,$k0,1 sec8: nop nor $2,$2,$4 mfhi $2 beq $3,$2,yes8 nop no8:addiu $k1,$k1,1 yes8:addiu $k0,$k0,1 sec9: nop subu $2,$3,$0 lb $2,10($0) beq $3,$2,yes9 nop no9:addiu $k1,$k1,1 yes9:addiu $k0,$k0,1 sec10: nop ori $2,$3,36208 nop beq $3,$2,yes10 nop no10:addiu $k1,$k1,1 yes10:addiu $k0,$k0,1 sec11: nop xori $2,$3,49370 xor $2,$5,$2 beq $3,$2,yes11 nop no11:addiu $k1,$k1,1 yes11:addiu $k0,$k0,1 sec12: nop andi $2,$3,27639 andi $2,$3,40185 beq $3,$2,yes12 nop no12:addiu $k1,$k1,1 yes12:addiu $k0,$k0,1 sec13: nop lui $2,37634 mflo $2 beq $3,$2,yes13 nop no13:addiu $k1,$k1,1 yes13:addiu $k0,$k0,1 sec14: nop ori $2,$2,47948 lbu $2,10($0) beq $3,$2,yes14 nop no14:addiu $k1,$k1,1 yes14:addiu $k0,$k0,1 sec15: nop mflo $2 nop beq $3,$2,yes15 nop no15:addiu $k1,$k1,1 yes15:addiu $k0,$k0,1 sec16: nop mfhi $2 and $2,$3,$2 beq $3,$2,yes16 nop no16:addiu $k1,$k1,1 yes16:addiu $k0,$k0,1 sec17: nop mflo $2 andi $2,$4,43167 beq $3,$2,yes17 nop no17:addiu $k1,$k1,1 yes17:addiu $k0,$k0,1 sec18: nop mflo $2 mflo $2 beq $3,$2,yes18 nop no18:addiu $k1,$k1,1 yes18:addiu $k0,$k0,1 sec19: nop mfhi $2 lw $2,12($0) beq $3,$2,yes19 nop no19:addiu $k1,$k1,1 yes19:addiu $k0,$k0,1 sec20: nop lb $2,10($0) nop beq $3,$2,yes20 nop no20:addiu $k1,$k1,1 yes20:addiu $k0,$k0,1 sec21: nop lw $2,8($0) xor $2,$3,$2 beq $3,$2,yes21 nop no21:addiu $k1,$k1,1 yes21:addiu $k0,$k0,1 sec22: nop lb $2,6($0) slti $2,$6,24977 beq $3,$2,yes22 nop no22:addiu $k1,$k1,1 yes22:addiu $k0,$k0,1 sec23: nop lh $2,0($0) mflo $2 beq $3,$2,yes23 nop no23:addiu $k1,$k1,1 yes23:addiu $k0,$k0,1 sec24: nop lw $2,0($0) lhu $2,10($0) beq $3,$2,yes24 nop no24:addiu $k1,$k1,1 yes24:addiu $k0,$k0,1 sec25: slt $3,$2,$3 nop nop beq $3,$2,yes25 nop no25:addiu $k1,$k1,1 yes25:addiu $k0,$k0,1 sec26: and $3,$4,$3 nop slt $2,$3,$2 beq $3,$2,yes26 nop no26:addiu $k1,$k1,1 yes26:addiu $k0,$k0,1 sec27: and $3,$6,$2 nop slti $2,$4,26814 beq $3,$2,yes27 nop no27:addiu $k1,$k1,1 yes27:addiu $k0,$k0,1 sec28: or $3,$3,$3 nop mflo $2 beq $3,$2,yes28 nop no28:addiu $k1,$k1,1 yes28:addiu $k0,$k0,1 sec29: nor $3,$3,$1 nop lbu $2,13($0) beq $3,$2,yes29 nop no29:addiu $k1,$k1,1 yes29:addiu $k0,$k0,1 sec30: nor $3,$4,$2 and $2,$5,$4 nop beq $3,$2,yes30 nop no30:addiu $k1,$k1,1 yes30:addiu $k0,$k0,1 sec31: sltu $3,$6,$2 addu $2,$0,$3 subu $2,$4,$4 beq $3,$2,yes31 nop no31:addiu $k1,$k1,1 yes31:addiu $k0,$k0,1 sec32: subu $3,$0,$3 or $2,$4,$4 addiu $2,$3,28142 beq $3,$2,yes32 nop no32:addiu $k1,$k1,1 yes32:addiu $k0,$k0,1 sec33: xor $3,$0,$0 subu $2,$2,$6 mflo $2 beq $3,$2,yes33 nop no33:addiu $k1,$k1,1 yes33:addiu $k0,$k0,1 sec34: xor $3,$4,$4 slt $2,$1,$2 lhu $2,16($0) beq $3,$2,yes34 nop no34:addiu $k1,$k1,1 yes34:addiu $k0,$k0,1 sec35: addu $3,$4,$0 slti $2,$4,22838 nop beq $3,$2,yes35 nop no35:addiu $k1,$k1,1 yes35:addiu $k0,$k0,1 sec36: xor $3,$4,$4 xori $2,$4,37863 subu $2,$4,$4 beq $3,$2,yes36 nop no36:addiu $k1,$k1,1 yes36:addiu $k0,$k0,1 sec37: xor $3,$3,$6 addiu $2,$0,-7539 lui $2,21661 beq $3,$2,yes37 nop no37:addiu $k1,$k1,1 yes37:addiu $k0,$k0,1 sec38: addu $3,$4,$4 sltiu $2,$6,-31999 mflo $2 beq $3,$2,yes38 nop no38:addiu $k1,$k1,1 yes38:addiu $k0,$k0,1 sec39: or $3,$4,$3 xori $2,$4,1987 lb $2,7($0) beq $3,$2,yes39 nop no39:addiu $k1,$k1,1 yes39:addiu $k0,$k0,1 sec40: sltu $3,$4,$1 mflo $2 nop beq $3,$2,yes40 nop no40:addiu $k1,$k1,1 yes40:addiu $k0,$k0,1 sec41: slt $3,$5,$4 mflo $2 sltu $2,$1,$4 beq $3,$2,yes41 nop no41:addiu $k1,$k1,1 yes41:addiu $k0,$k0,1 sec42: subu $3,$1,$6 mfhi $2 sltiu $2,$3,-18876 beq $3,$2,yes42 nop no42:addiu $k1,$k1,1 yes42:addiu $k0,$k0,1 sec43: xor $3,$3,$4 mfhi $2 mflo $2 beq $3,$2,yes43 nop no43:addiu $k1,$k1,1 yes43:addiu $k0,$k0,1 sec44: sltu $3,$4,$3 mfhi $2 lb $2,4($0) beq $3,$2,yes44 nop no44:addiu $k1,$k1,1 yes44:addiu $k0,$k0,1 sec45: slt $3,$4,$3 lw $2,12($0) nop beq $3,$2,yes45 nop no45:addiu $k1,$k1,1 yes45:addiu $k0,$k0,1 sec46: xor $3,$6,$3 lh $2,6($0) or $2,$3,$2 beq $3,$2,yes46 nop no46:addiu $k1,$k1,1 yes46:addiu $k0,$k0,1 sec47: or $3,$4,$0 lhu $2,10($0) ori $2,$5,3026 beq $3,$2,yes47 nop no47:addiu $k1,$k1,1 yes47:addiu $k0,$k0,1 sec48: or $3,$1,$5 lh $2,12($0) mflo $2 beq $3,$2,yes48 nop no48:addiu $k1,$k1,1 yes48:addiu $k0,$k0,1 sec49: xor $3,$3,$3 lh $2,12($0) lh $2,16($0) beq $3,$2,yes49 nop no49:addiu $k1,$k1,1 yes49:addiu $k0,$k0,1 sec50: lui $3,39660 nop nop beq $3,$2,yes50 nop no50:addiu $k1,$k1,1 yes50:addiu $k0,$k0,1 sec51: lui $3,16718 nop slt $2,$3,$4 beq $3,$2,yes51 nop no51:addiu $k1,$k1,1 yes51:addiu $k0,$k0,1 sec52: xori $3,$2,63421 nop slti $2,$1,31188 beq $3,$2,yes52 nop no52:addiu $k1,$k1,1 yes52:addiu $k0,$k0,1 sec53: ori $3,$2,39352 nop mflo $2 beq $3,$2,yes53 nop no53:addiu $k1,$k1,1 yes53:addiu $k0,$k0,1 sec54: xori $3,$0,3479 nop lh $2,6($0) beq $3,$2,yes54 nop no54:addiu $k1,$k1,1 yes54:addiu $k0,$k0,1 sec55: andi $3,$2,5222 addu $2,$1,$2 nop beq $3,$2,yes55 nop no55:addiu $k1,$k1,1 yes55:addiu $k0,$k0,1 sec56: addiu $3,$3,-24343 subu $2,$3,$5 subu $2,$2,$5 beq $3,$2,yes56 nop no56:addiu $k1,$k1,1 yes56:addiu $k0,$k0,1 sec57: slti $3,$4,8532 nor $2,$6,$4 sltiu $2,$4,-20967 beq $3,$2,yes57 nop no57:addiu $k1,$k1,1 yes57:addiu $k0,$k0,1 sec58: andi $3,$5,24525 sltu $2,$2,$5 mfhi $2 beq $3,$2,yes58 nop no58:addiu $k1,$k1,1 yes58:addiu $k0,$k0,1 sec59: ori $3,$5,49831 and $2,$2,$2 lh $2,8($0) beq $3,$2,yes59 nop no59:addiu $k1,$k1,1 yes59:addiu $k0,$k0,1 sec60: andi $3,$3,48751 addiu $2,$2,-24965 nop beq $3,$2,yes60 nop no60:addiu $k1,$k1,1 yes60:addiu $k0,$k0,1 sec61: lui $3,50796 sltiu $2,$5,17357 xor $2,$5,$1 beq $3,$2,yes61 nop no61:addiu $k1,$k1,1 yes61:addiu $k0,$k0,1 sec62: lui $3,55733 slti $2,$2,11887 lui $2,24860 beq $3,$2,yes62 nop no62:addiu $k1,$k1,1 yes62:addiu $k0,$k0,1 sec63: sltiu $3,$1,-1678 lui $2,41353 mflo $2 beq $3,$2,yes63 nop no63:addiu $k1,$k1,1 yes63:addiu $k0,$k0,1 sec64: xori $3,$2,25464 lui $2,6337 lh $2,2($0) beq $3,$2,yes64 nop no64:addiu $k1,$k1,1 yes64:addiu $k0,$k0,1 sec65: addiu $3,$3,-28859 mfhi $2 nop beq $3,$2,yes65 nop no65:addiu $k1,$k1,1 yes65:addiu $k0,$k0,1 sec66: andi $3,$3,30786 mflo $2 xor $2,$6,$5 beq $3,$2,yes66 nop no66:addiu $k1,$k1,1 yes66:addiu $k0,$k0,1 sec67: sltiu $3,$5,-1766 mflo $2 ori $2,$1,19662 beq $3,$2,yes67 nop no67:addiu $k1,$k1,1 yes67:addiu $k0,$k0,1 sec68: andi $3,$1,28705 mfhi $2 mfhi $2 beq $3,$2,yes68 nop no68:addiu $k1,$k1,1 yes68:addiu $k0,$k0,1 sec69: ori $3,$3,43077 mflo $2 lhu $2,0($0) beq $3,$2,yes69 nop no69:addiu $k1,$k1,1 yes69:addiu $k0,$k0,1 sec70: xori $3,$1,29651 lh $2,12($0) nop beq $3,$2,yes70 nop no70:addiu $k1,$k1,1 yes70:addiu $k0,$k0,1 sec71: xori $3,$5,49597 lbu $2,14($0) subu $2,$5,$5 beq $3,$2,yes71 nop no71:addiu $k1,$k1,1 yes71:addiu $k0,$k0,1 sec72: lui $3,54541 lb $2,15($0) addiu $2,$2,-5579 beq $3,$2,yes72 nop no72:addiu $k1,$k1,1 yes72:addiu $k0,$k0,1 sec73: sltiu $3,$6,14370 lhu $2,2($0) mfhi $2 beq $3,$2,yes73 nop no73:addiu $k1,$k1,1 yes73:addiu $k0,$k0,1 sec74: slti $3,$3,-19456 lw $2,16($0) lhu $2,6($0) beq $3,$2,yes74 nop no74:addiu $k1,$k1,1 yes74:addiu $k0,$k0,1 sec75: mflo $3 nop nop beq $3,$2,yes75 nop no75:addiu $k1,$k1,1 yes75:addiu $k0,$k0,1 sec76: mfhi $3 nop addu $2,$0,$3 beq $3,$2,yes76 nop no76:addiu $k1,$k1,1 yes76:addiu $k0,$k0,1 sec77: mflo $3 nop addiu $2,$3,-30203 beq $3,$2,yes77 nop no77:addiu $k1,$k1,1 yes77:addiu $k0,$k0,1 sec78: mfhi $3 nop mflo $2 beq $3,$2,yes78 nop no78:addiu $k1,$k1,1 yes78:addiu $k0,$k0,1 sec79: mflo $3 nop lh $2,16($0) beq $3,$2,yes79 nop no79:addiu $k1,$k1,1 yes79:addiu $k0,$k0,1 sec80: mflo $3 xor $2,$4,$2 nop beq $3,$2,yes80 nop no80:addiu $k1,$k1,1 yes80:addiu $k0,$k0,1 sec81: mflo $3 or $2,$2,$3 slt $2,$2,$5 beq $3,$2,yes81 nop no81:addiu $k1,$k1,1 yes81:addiu $k0,$k0,1 sec82: mflo $3 slt $2,$4,$5 slti $2,$5,-9893 beq $3,$2,yes82 nop no82:addiu $k1,$k1,1 yes82:addiu $k0,$k0,1 sec83: mflo $3 addu $2,$3,$5 mflo $2 beq $3,$2,yes83 nop no83:addiu $k1,$k1,1 yes83:addiu $k0,$k0,1 sec84: mflo $3 or $2,$4,$5 lhu $2,6($0) beq $3,$2,yes84 nop no84:addiu $k1,$k1,1 yes84:addiu $k0,$k0,1 sec85: mflo $3 ori $2,$0,37755 nop beq $3,$2,yes85 nop no85:addiu $k1,$k1,1 yes85:addiu $k0,$k0,1 sec86: mflo $3 addiu $2,$5,25622 nor $2,$3,$3 beq $3,$2,yes86 nop no86:addiu $k1,$k1,1 yes86:addiu $k0,$k0,1 sec87: mflo $3 lui $2,8546 slti $2,$4,8468 beq $3,$2,yes87 nop no87:addiu $k1,$k1,1 yes87:addiu $k0,$k0,1 sec88: mfhi $3 slti $2,$1,7421 mfhi $2 beq $3,$2,yes88 nop no88:addiu $k1,$k1,1 yes88:addiu $k0,$k0,1 sec89: mflo $3 xori $2,$4,47073 lhu $2,0($0) beq $3,$2,yes89 nop no89:addiu $k1,$k1,1 yes89:addiu $k0,$k0,1 sec90: mflo $3 mflo $2 nop beq $3,$2,yes90 nop no90:addiu $k1,$k1,1 yes90:addiu $k0,$k0,1 sec91: mflo $3 mfhi $2 addu $2,$5,$4 beq $3,$2,yes91 nop no91:addiu $k1,$k1,1 yes91:addiu $k0,$k0,1 sec92: mflo $3 mfhi $2 ori $2,$3,50262 beq $3,$2,yes92 nop no92:addiu $k1,$k1,1 yes92:addiu $k0,$k0,1 sec93: mflo $3 mfhi $2 mflo $2 beq $3,$2,yes93 nop no93:addiu $k1,$k1,1 yes93:addiu $k0,$k0,1 sec94: mflo $3 mfhi $2 lh $2,0($0) beq $3,$2,yes94 nop no94:addiu $k1,$k1,1 yes94:addiu $k0,$k0,1 sec95: mfhi $3 lhu $2,6($0) nop beq $3,$2,yes95 nop no95:addiu $k1,$k1,1 yes95:addiu $k0,$k0,1 sec96: mfhi $3 lhu $2,4($0) nor $2,$3,$3 beq $3,$2,yes96 nop no96:addiu $k1,$k1,1 yes96:addiu $k0,$k0,1 sec97: mfhi $3 lb $2,3($0) xori $2,$0,31541 beq $3,$2,yes97 nop no97:addiu $k1,$k1,1 yes97:addiu $k0,$k0,1 sec98: mflo $3 lh $2,8($0) mflo $2 beq $3,$2,yes98 nop no98:addiu $k1,$k1,1 yes98:addiu $k0,$k0,1 sec99: mflo $3 lh $2,0($0) lw $2,12($0) beq $3,$2,yes99 nop no99:addiu $k1,$k1,1 yes99:addiu $k0,$k0,1 sec100: lw $3,16($0) nop nop beq $3,$2,yes100 nop no100:addiu $k1,$k1,1 yes100:addiu $k0,$k0,1 sec101: lb $3,4($0) nop or $2,$5,$1 beq $3,$2,yes101 nop no101:addiu $k1,$k1,1 yes101:addiu $k0,$k0,1 sec102: lhu $3,0($0) nop addiu $2,$0,13015 beq $3,$2,yes102 nop no102:addiu $k1,$k1,1 yes102:addiu $k0,$k0,1 sec103: lb $3,11($0) nop mflo $2 beq $3,$2,yes103 nop no103:addiu $k1,$k1,1 yes103:addiu $k0,$k0,1 sec104: lb $3,10($0) nop lb $2,4($0) beq $3,$2,yes104 nop no104:addiu $k1,$k1,1 yes104:addiu $k0,$k0,1 sec105: lb $3,9($0) slt $2,$0,$3 nop beq $3,$2,yes105 nop no105:addiu $k1,$k1,1 yes105:addiu $k0,$k0,1 sec106: lb $3,13($0) nor $2,$2,$2 sltu $2,$3,$2 beq $3,$2,yes106 nop no106:addiu $k1,$k1,1 yes106:addiu $k0,$k0,1 sec107: lb $3,2($0) nor $2,$0,$2 slti $2,$3,20678 beq $3,$2,yes107 nop no107:addiu $k1,$k1,1 yes107:addiu $k0,$k0,1 sec108: lw $3,8($0) subu $2,$2,$1 mfhi $2 beq $3,$2,yes108 nop no108:addiu $k1,$k1,1 yes108:addiu $k0,$k0,1 sec109: lbu $3,11($0) subu $2,$5,$4 lbu $2,9($0) beq $3,$2,yes109 nop no109:addiu $k1,$k1,1 yes109:addiu $k0,$k0,1 sec110: lhu $3,2($0) slti $2,$3,-10271 nop beq $3,$2,yes110 nop no110:addiu $k1,$k1,1 yes110:addiu $k0,$k0,1 sec111: lhu $3,12($0) addiu $2,$2,-5860 slt $2,$1,$0 beq $3,$2,yes111 nop no111:addiu $k1,$k1,1 yes111:addiu $k0,$k0,1 sec112: lw $3,0($0) addiu $2,$4,-25638 addiu $2,$4,-13831 beq $3,$2,yes112 nop no112:addiu $k1,$k1,1 yes112:addiu $k0,$k0,1 sec113: lhu $3,4($0) slti $2,$2,12596 mflo $2 beq $3,$2,yes113 nop no113:addiu $k1,$k1,1 yes113:addiu $k0,$k0,1 sec114: lb $3,7($0) sltiu $2,$4,-1567 lbu $2,11($0) beq $3,$2,yes114 nop no114:addiu $k1,$k1,1 yes114:addiu $k0,$k0,1 sec115: lb $3,9($0) mfhi $2 nop beq $3,$2,yes115 nop no115:addiu $k1,$k1,1 yes115:addiu $k0,$k0,1 sec116: lbu $3,7($0) mfhi $2 and $2,$3,$1 beq $3,$2,yes116 nop no116:addiu $k1,$k1,1 yes116:addiu $k0,$k0,1 sec117: lh $3,16($0) mfhi $2 andi $2,$0,73 beq $3,$2,yes117 nop no117:addiu $k1,$k1,1 yes117:addiu $k0,$k0,1 sec118: lb $3,7($0) mflo $2 mflo $2 beq $3,$2,yes118 nop no118:addiu $k1,$k1,1 yes118:addiu $k0,$k0,1 sec119: lh $3,2($0) mfhi $2 lh $2,8($0) beq $3,$2,yes119 nop no119:addiu $k1,$k1,1 yes119:addiu $k0,$k0,1 sec120: lh $3,12($0) lb $2,16($0) nop beq $3,$2,yes120 nop no120:addiu $k1,$k1,1 yes120:addiu $k0,$k0,1 sec121: lw $3,16($0) lb $2,5($0) and $2,$6,$2 beq $3,$2,yes121 nop no121:addiu $k1,$k1,1 yes121:addiu $k0,$k0,1 sec122: lbu $3,2($0) lbu $2,9($0) ori $2,$3,9256 beq $3,$2,yes122 nop no122:addiu $k1,$k1,1 yes122:addiu $k0,$k0,1 sec123: lh $3,6($0) lb $2,14($0) mfhi $2 beq $3,$2,yes123 nop no123:addiu $k1,$k1,1 yes123:addiu $k0,$k0,1 sec124: lbu $3,6($0) lb $2,12($0) lb $2,7($0) beq $3,$2,yes124 nop no124:addiu $k1,$k1,1 yes124:addiu $k0,$k0,1
SFX_Snare5_2_Ch7: noisenote 7, 8, 4, 55 noisenote 6, 8, 4, 54 noisenote 5, 8, 3, 53 noisenote 4, 8, 3, 52 noisenote 3, 8, 2, 51 noisenote 2, 8, 1, 50 endchannel
; A283982: a(0) = 0, and for n > 0, a(n) = A070939(n) - A280700(n). ; Submitted by Jamie Morken(s2) ; 0,0,0,1,0,2,1,0,0,3,2,1,1,0,1,1,0,4,3,2,2,1,2,2,1,0,2,2,1,1,2,1,0,5,4,3,3,2,3,3,2,1,3,3,2,2,3,2,1,0,3,3,2,2,3,2,1,1,3,2,2,1,0,2,0,6,5,4,4,3,4,4,3,2,4,4,3,3,4,3,2,1,4,4,3,3,4,3,2,2,4,3,3,2,1,3,1,0,4,4 seq $0,324378 ; a(n) = A000265(1+A005187(n)). seq $0,23416 ; Number of 0's in binary expansion of n.
.ORIG x3000 ; Dedicate R6 == Stack pointer LEA R6, SP LDR R6, R6, #0 ;Main(){ LEA R5, RNG LDR R5, R5, #0 ;Load pointer to Rand() ;---------------------------------------------- ; First Call to Rand() ;---------------------------------------------- STR R7, R6, #0 ;Push R7 (Not necessary here but good practice) ADD R6, R6, #-1 JSRR R5 ;num = Rand(); ADD R1, R0, #0 ;A = num ADD R6, R6, #1 LDR R7, R6, #0 ;Pop R7 (Must pop any value we chose to push) ;---------------------------------------------- ; Second Call to Rand() ;---------------------------------------------- STR R7, R6, #0 ;Push R7 (Not necessary here but good practice) ADD R6, R6, #-1 JSRR R5 ;num = Rand(); ADD R2, R0, #0 ;A = num ADD R6, R6, #1 LDR R7, R6, #0 ;Pop R7 (Must pop any value we chose to push) ;---------------------------------------------- ; Third Call to Rand() ;---------------------------------------------- STR R7, R6, #0 ;Push R7 (Not necessary here but good practice) ADD R6, R6, #-1 JSRR R5 ;num = Rand(); ADD R3, R0, #0 ;A = num ADD R6, R6, #1 LDR R7, R6, #0 ;Pop R7 (Must pop any value we chose to push) ;---------------------------------------------- ; Fourth Call to Rand() ;---------------------------------------------- STR R7, R6, #0 ;Push R7 (Not necessary here but good practice) ADD R6, R6, #-1 JSRR R5 ;num = Rand(); ADD R4, R0, #0 ;A = num ADD R6, R6, #1 LDR R7, R6, #0 ;Pop R7 (Must pop any value we chose to push) ;---------------------------------------------- HALT ;}//End of Main RNG .FILL x3400 ;Address of Rand() routine SP .FILL xFDFF ; Stack pointer to the end of user space MEM .END
// Copyright 1996-2019 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * Description: Small graphical user interface for the OSM importer script */ #ifndef OSM_IMPORTER_WINDOW_HPP #define OSM_IMPORTER_WINDOW_HPP #include <QtCore/QString> #include <QtCore/QProcess> #include <QtWidgets/QMainWindow> class QWidget; class QGridLayout; class QGroupBox; class QRadioButton; class QLineEdit; class QLabel; class QPushButton; class QNetworkReply; class QTextEdit; class QCheckBox; class QVBoxLayout; class QHBoxLayout; class OSMImportWindow : public QMainWindow { Q_OBJECT public: OSMImportWindow(QString stringPath, QWidget *parent = 0); virtual ~OSMImportWindow(); public slots: void updateInputMethod(); void selectInputFile(); void selectConfigurationFile(); void warnAboutThirdDimension(); void generateWorld(); void setProcessFinished(int exitCode, QProcess::ExitStatus exitStatus); void readStandardOutput(); void readStandardError(); void readReply(); protected: void launchImporter(QString osmFile); QGridLayout *mMainLayout; QWidget *mCentralWidget; // script location QString mScriptFile; // input method QGroupBox *mInputGroupBox; QGridLayout *mInputLayout; QRadioButton *mFileRadioButton; QLabel *mFileLabel; QLineEdit *mFileLineEdit; QPushButton *mFilePushButton; QRadioButton *mCoordinateRadioButton; QLineEdit *mMinLatLineEdit; QLineEdit *mMaxLatLineEdit; QLineEdit *mMinLongLineEdit; QLineEdit *mMaxLongLineEdit; QLabel *mMinLatLabel; QLabel *mMaxLatLabel; QLabel *mMinLongLabel; QLabel *mMaxLongLabel; // config file QGroupBox *mConfigGroupBox; QHBoxLayout *mConfigHBoxLayout; QLineEdit *mConfigLineEdit; QPushButton *mConfigPushButton; // projection QGroupBox *mProjectionGroupBox; QHBoxLayout *mProjectionHBoxLayout; QLabel *mProjectionLabel; QLineEdit *mProjectionLineEdit; // features QGroupBox *mFeaturesGroupBox; QVBoxLayout *mFeaturesVBoxLayout; QCheckBox *mForestsCheckBox; QCheckBox *mRoadsCheckBox; QCheckBox *mAreasCheckBox; QCheckBox *mTreesCheckBox; QCheckBox *mBarriersCheckBox; QCheckBox *mRiversCheckBox; QCheckBox *mBuildingsCheckBox; QCheckBox *mEnableMultipolygonBuildings; QCheckBox *mEnable3DCheckBox; // generate QPushButton *mGeneratePushButton; // console QTextEdit *mConsoleTextEdit; // importer process QProcess *mImporterProcess; // reply for map acquisition QNetworkReply *mReply; }; #endif // OSM_IMPORTER_WINDOW_HPP
ProfOaksPC: ld hl, OakPCText1 call MenuTextbox call YesNoBox jr c, .shutdown call ProfOaksPCBoot ; player chose "yes"? .shutdown ld hl, OakPCText4 call PrintText call JoyWaitAorB call ExitMenu ret ProfOaksPCBoot: ld hl, OakPCText2 call PrintText call Rate call PlaySFX ; sfx loaded by previous Rate function call call JoyWaitAorB call WaitSFX ret ProfOaksPCRating: call Rate push de ld de, MUSIC_NONE call PlayMusic pop de call PlaySFX call JoyWaitAorB call WaitSFX ret Rate: ; calculate Seen/Owned ld hl, wPokedexSeen ld b, wEndPokedexSeen - wPokedexSeen call CountSetBits ld [wd002], a ld hl, wPokedexCaught ld b, wEndPokedexCaught - wPokedexCaught call CountSetBits ld [wd003], a ; print appropriate rating call .UpdateRatingBuffers ld hl, OakPCText3 call PrintText call JoyWaitAorB ld a, [wd003] ld hl, OakRatings call FindOakRating push de call PrintText pop de ret .UpdateRatingBuffers: ld hl, wStringBuffer3 ld de, wd002 call .UpdateRatingBuffer ld hl, wStringBuffer4 ld de, wd003 call .UpdateRatingBuffer ret .UpdateRatingBuffer: push hl ld a, "@" ld bc, ITEM_NAME_LENGTH call ByteFill pop hl lb bc, PRINTNUM_RIGHTALIGN | 1, 3 call PrintNum ret FindOakRating: ; return sound effect in de ; return text pointer in hl nop ld c, a .loop ld a, [hli] cp c jr nc, .match rept 4 inc hl endr jr .loop .match ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld h, [hl] ld l, a ret INCLUDE "data/events/pokedex_ratings.asm" OakPCText1: text_far _OakPCText1 text_end OakPCText2: text_far _OakPCText2 text_end OakPCText3: text_far _OakPCText3 text_end OakRating01: text_far _OakRating01 text_end OakRating02: text_far _OakRating02 text_end OakRating03: text_far _OakRating03 text_end OakRating04: text_far _OakRating04 text_end OakRating05: text_far _OakRating05 text_end OakRating06: text_far _OakRating06 text_end OakRating07: text_far _OakRating07 text_end OakRating08: text_far _OakRating08 text_end OakRating09: text_far _OakRating09 text_end OakRating10: text_far _OakRating10 text_end OakRating11: text_far _OakRating11 text_end OakRating12: text_far _OakRating12 text_end OakRating13: text_far _OakRating13 text_end OakRating14: text_far _OakRating14 text_end OakRating15: text_far _OakRating15 text_end OakRating16: text_far _OakRating16 text_end OakRating17: text_far _OakRating17 text_end OakRating18: text_far _OakRating18 text_end OakRating19: text_far _OakRating19 text_end OakPCText4: text_far _OakPCText4 text_end
#include "../cpudef.asm" ; put the upper 11 bits of 0xffff into r3 imm 0xffff move r3, 0 ; r3 should now equal -32 or 0xffe0 ; lets invert that xor r3, -1 ; r3 should now be 0xf or 0b1111 if.ne r3, 0b1111 error ; construct a 16 bit value in r1 without using the imm instruction move r1, 0x75 shl r1, 8 move r2, 0x49 or r1, r2 ; trigger imm to augment the if.ne instruction with a 16-bit value if.ne r1, 0x7549 error ; try imm augmentation on add in addition to if.ne move r5, 70 add r5, 128 if.ne r5, 70+128 error ; make sure 63 doesn't become -1 in the if.ne move r5, 63 if.ne r5, 63 error ; handle the special case of skipping the imm instruction ; in the first if.ne, the add instruction will have an imm prefix ; we want to skip that imm prefix and the add ; otherwise the assembler needs detect this case and perform a very ; complicated workaround that customasm doesn't support move r5, 10 if.ne r5, 10 add r5, 100 if.ne r5, 10 error move r5, 0x7e12 if.ne r5, 0x7e12 error ; grab the pc and put it in r4 call grabpc grabpc: move r4, ra ; 1 move r5, 0x7F ; 2 ; grab the pc and put it in r2 call grabpc2 ; 3 grabpc2: move r2, ra ; subtract pc values sub r2, r4 ; assert there is not a imm instruction inserted if.ne r2, 3 error move r2, 32 move r1, 0 move r4, 0x1234 ; check imm prefix is handled on load properly store [r2], r4 imm 32 load r3, [r1, 0] if.ne r3, 0x1234 error ; check imm prefix for store ; move r4, 0x5678 ; store [r1, 17], r4 ; nop ; load r3, [r2] ; nop ; if.ne r3, 0x5678 ; error halt
db 0 ; species ID placeholder db 50, 65, 107, 86, 105, 107 ; hp atk def spd sat sdf db ELECTRIC, FIRE ; type db 45 ; catch rate db 154 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_UNKNOWN ; gender ratio db 100 ; unknown 1 db 20 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/rotom_fre/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_MEDIUM_FAST ; growth rate dn EGG_INDETERMINATE, EGG_INDETERMINATE ; egg groups ; tm/hm learnset tmhm CURSE, TOXIC, PSYCH_UP, HIDDEN_POWER, SUNNY_DAY, SNORE, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, THUNDER, RETURN, SHADOW_BALL, MUD_SLAP, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SWIFT, DREAM_EATER, REST, THIEF, NIGHTMARE, FLASH ; end
; A296954: Expansion of x*(1 - x + 4*x^2) / ((1 - x)*(1 - 2*x)). ; 0,1,2,8,20,44,92,188,380,764,1532,3068,6140,12284,24572,49148,98300,196604,393212,786428,1572860,3145724,6291452,12582908,25165820,50331644,100663292,201326588,402653180,805306364,1610612732,3221225468,6442450940,12884901884,25769803772,51539607548,103079215100,206158430204,412316860412,824633720828,1649267441660,3298534883324,6597069766652,13194139533308,26388279066620,52776558133244,105553116266492,211106232532988,422212465065980,844424930131964,1688849860263932,3377699720527868,6755399441055740,13510798882111484,27021597764222972,54043195528445948,108086391056891900,216172782113783804,432345564227567612,864691128455135228,1729382256910270460,3458764513820540924,6917529027641081852,13835058055282163708,27670116110564327420,55340232221128654844,110680464442257309692,221360928884514619388,442721857769029238780,885443715538058477564,1770887431076116955132,3541774862152233910268,7083549724304467820540,14167099448608935641084,28334198897217871282172,56668397794435742564348,113336795588871485128700,226673591177742970257404,453347182355485940514812,906694364710971881029628,1813388729421943762059260,3626777458843887524118524,7253554917687775048237052,14507109835375550096474108,29014219670751100192948220,58028439341502200385896444,116056878683004400771792892,232113757366008801543585788,464227514732017603087171580,928455029464035206174343164,1856910058928070412348686332,3713820117856140824697372668,7427640235712281649394745340,14855280471424563298789490684,29710560942849126597578981372,59421121885698253195157962748,118842243771396506390315925500,237684487542793012780631851004,475368975085586025561263702012,950737950171172051122527404028 mov $1,$0 sub $1,2 lpb $1 add $0,1 mul $0,2 sub $1,1 sub $0,$1 lpe
; A082110: Array T(n,k) = k^2*n^2+5*k*n+1, read by antidiagonals. ; 1,1,1,1,7,1,1,15,15,1,1,25,37,25,1,1,37,67,67,37,1,1,51,105,127,105,51,1,1,67,151,205,205,151,67,1,1,85,205,301,337,301,205,85,1,1,105,267,415,501,501,415,267,105,1,1,127,337,547,697,751,697,547,337,127,1,1 seq $0,4247 ; Multiplication table read by antidiagonals: T(i,j) = ij (i>=0, j>=0). mov $1,$0 add $1,5 mul $0,$1 add $0,1
db DRAGONAIR ; pokedex id db 61 ; base hp db 84 ; base attack db 65 ; base defense db 70 ; base speed db 70 ; base special db DRAGON ; species type 1 db DRAGON ; species type 2 db 45 ; catch rate db 144 ; base exp yield INCBIN "pic/gsmon/dragonair.pic",0,1 ; 66, sprite dimensions dw DragonairPicFront dw DragonairPicBack ; attacks known at lvl 0 db BIND db 0 db 0 db 0 db 5 ; growth rate ; learnset tmlearn 6,7,8 tmlearn 9,10,11,13,14 tmlearn 20,23,24 tmlearn 25,31,32 tmlearn 33,34,38,39,40 tmlearn 44,45 tmlearn 50,53 db BANK(DragonairPicFront)
TITLE PROG2 {EXE} Convert a letter from uppercase to lowercase ;-------------------------------------------- .MODEL SMALL .STACK ;-------------------------------------------- .DATA INPMSG DB "Enter character: ", "$" OUTMSG DB 0DH, 0AH, "Your character in lowercase -> ", "$" ERRMSG DB 0DH, 0AH, "Character must be between A and Z", "$" ;-------------------------------------------- .CODE MAIN PROC FAR MOV AX,@data ; Initialize segment registers MOV DS,AX TLOOP: CALL PROMPT ; Display prompt CALL CHINPT ; Request input MOV AH,09H LEA DX,ERRMSG ; Load the error message CMP AL,'A' ; Check if entered character >= 'A' JGE OK INT 21H JMP TATA OK: CMP AL,'Z' ; Check if entered character <= 'Z' JLE CNVT INT 21H JMP TATA CNVT: ADD AL,20H ; Convert to lowercase CALL DISP ; Request display TATA: MOV AH,4CH ; Terminate INT 21H MAIN ENDP ; Display Prompt ; -------------- PROMPT PROC NEAR MOV AH,09H LEA DX,INPMSG INT 21H RET PROMPT ENDP ; Character Input ; --------------- CHINPT PROC NEAR MOV AH,01H INT 21H RET CHINPT ENDP ; Character display ; ----------------- DISP PROC NEAR MOV AH,09H LEA DX,OUTMSG ; Display output message INT 21H MOV AH,02H MOV DL,AL ; Display lowercase character INT 21H RET DISP ENDP END MAIN
#include "std.h" #include <cstdlib> #include "parser.h" #ifdef DEMO static const int TEXTLIMIT=16384; #else static const int TEXTLIMIT=1024*1024-1; #endif enum{ STMTS_PROG,STMTS_BLOCK,STMTS_LINE }; static bool isTerm( int c ){ return c==':' || c=='\n'; } Parser::Parser( Toker &t ):toker(&t),main_toker(&t){ } ProgNode *Parser::parse( const string &main , bool debug){ incfile=main; consts=d_new DeclSeqNode(); structs=d_new DeclSeqNode(); funcs=d_new DeclSeqNode(); datas=d_new DeclSeqNode(); StmtSeqNode *stmts=0; try{ stmts=parseStmtSeq( STMTS_PROG, debug); if( toker->curr()!=EOF ) exp( "end-of-file" ); }catch( Ex ){ delete stmts;delete datas;delete funcs;delete structs;delete consts; throw; } return d_new ProgNode( consts,structs,funcs,datas,stmts ); } void Parser::ex( const string &s ){ throw Ex( s,toker->pos(),incfile ); } void Parser::exp( const string &s ){ switch( toker->curr() ){ case NEXT:ex( "'Next' without 'For'" ); case WEND:ex( "'Wend' without 'While'" ); case ELSE:case ELSEIF:ex( "'Else' without 'If'" ); case ENDIF:ex( "'Endif' without 'If'" ); case ENDFUNCTION:ex( "'End Function' without 'Function'" ); case UNTIL:ex( "'Until' without 'Repeat'" ); case FOREVER:ex( "'Forever' without 'Repeat'" ); case CASE:ex( "'Case' without 'Select'" ); case ENDSELECT:ex( "'End Select' without 'Select'" ); } ex( "Expecting "+s ); } string Parser::parseIdent(){ if( toker->curr()!=IDENT ) exp( "identifier" ); string t=toker->text(); toker->next(); return t; } void Parser::parseChar( int c ){ if( toker->curr()!=c ) exp( string( "'" )+char(c)+string( "'" ) ); toker->next(); } StmtSeqNode *Parser::parseStmtSeq( int scope , bool debug){ a_ptr<StmtSeqNode> stmts( d_new StmtSeqNode( incfile ) ); parseStmtSeq( stmts,scope, debug); return stmts.release(); } void Parser::parseStmtSeq( StmtSeqNode *stmts,int scope, bool debug){ for(;;){ while( toker->curr()==':' || (scope!=STMTS_LINE && toker->curr()=='\n') ) toker->next(); StmtNode *result=0; int pos=toker->pos(); #ifdef DEMO if( Toker::chars_toked>TEXTLIMIT ){ ex( "Demo version source limit exceeded" ); } #endif switch( toker->curr() ){ case INCLUDE: { if( toker->next()!=STRINGCONST ) exp( "include filename" ); string inc=toker->text();toker->next(); inc=inc.substr( 1,inc.size()-2 ); //WIN32 KLUDGE// char buff[MAX_PATH],*p; if( GetFullPathName( inc.c_str(),MAX_PATH,buff,&p ) ) inc=buff; inc=tolower(inc); if( included.find( inc )!=included.end() ) break; ifstream i_stream( inc.c_str() ); if( !i_stream.good() ) ex( "Unable to open include file" ); Toker i_toker( i_stream ); string t_inc=incfile;incfile=inc; Toker *t_toker=toker;toker=&i_toker; included.insert( incfile ); a_ptr<StmtSeqNode> ss( parseStmtSeq( scope, debug) ); if( toker->curr()!=EOF ) exp( "end-of-file" ); result=d_new IncludeNode( incfile,ss.release() ); toker=t_toker; incfile=t_inc; } break; case IDENT: { string ident=toker->text(); toker->next();string tag=parseTypeTag(); if( arrayDecls.find(ident)==arrayDecls.end() && toker->curr()!='=' && toker->curr()!='\\' && toker->curr()!='[' ){ //must be a function ExprSeqNode *exprs; if( toker->curr()=='(' ){ //ugly lookahead for optional '()' around statement params int nest=1,k; for( k=1;;++k ){ int c=toker->lookAhead( k ); if( isTerm( c ) ) ex( "Mismatched brackets" ); else if( c=='(' ) ++nest; else if( c==')' && !--nest ) break; } if( isTerm( toker->lookAhead( ++k ) ) ){ toker->next(); exprs=parseExprSeq(); if( toker->curr()!=')' ) exp( "')'" ); toker->next(); }else exprs=parseExprSeq(); }else exprs=parseExprSeq(); if ((ident != "debuglog" && ident != "stop") || debug) { CallNode *call = d_new CallNode(ident, tag, exprs); result = d_new ExprStmtNode(call); }else { result = 0; } }else{ //must be a var a_ptr<VarNode> var( parseVar( ident,tag ) ); if( toker->curr()!='=' ) exp( "variable assignment" ); toker->next();ExprNode *expr=parseExpr( false ); result=d_new AssNode( var.release(),expr ); } } break; case IF: { toker->next();result=parseIf(debug); if( toker->curr()==ENDIF ) toker->next(); } break; case WHILE: { toker->next(); a_ptr<ExprNode> expr( parseExpr( false ) ); a_ptr<StmtSeqNode> stmts( parseStmtSeq( STMTS_BLOCK, debug) ); int pos=toker->pos(); if( toker->curr()!=WEND ) exp( "'Wend'" ); toker->next(); result=d_new WhileNode( expr.release(),stmts.release(),pos ); } break; case REPEAT: { toker->next();ExprNode *expr=0; a_ptr<StmtSeqNode> stmts( parseStmtSeq( STMTS_BLOCK, debug) ); int curr=toker->curr(); int pos=toker->pos(); if( curr!=UNTIL && curr!=FOREVER ) exp( "'Until' or 'Forever'" ); toker->next();if( curr==UNTIL ) expr=parseExpr( false ); result=d_new RepeatNode( stmts.release(),expr,pos ); } break; case SELECT: { toker->next();ExprNode *expr=parseExpr( false ); a_ptr<SelectNode> selNode( d_new SelectNode( expr ) ); for(;;){ while( isTerm( toker->curr() ) ) toker->next(); if( toker->curr()==CASE ){ toker->next(); a_ptr<ExprSeqNode> exprs( parseExprSeq() ); if( !exprs->size() ) exp( "expression sequence" ); a_ptr<StmtSeqNode> stmts( parseStmtSeq( STMTS_BLOCK, debug) ); selNode->push_back( d_new CaseNode( exprs.release(),stmts.release() ) ); continue; }else if( toker->curr()==DEFAULT ){ toker->next(); a_ptr<StmtSeqNode> stmts( parseStmtSeq( STMTS_BLOCK, debug) ); if( toker->curr()!=ENDSELECT ) exp( "'End Select'" ); selNode->defStmts=stmts.release(); break; }else if( toker->curr()==ENDSELECT ){ break; } exp( "'Case', 'Default' or 'End Select'" ); } toker->next(); result=selNode.release(); } break; case FOR: { a_ptr<VarNode> var; a_ptr<StmtSeqNode> stmts; toker->next();var=parseVar(); if( toker->curr()!='=' ) exp( "variable assignment" ); if( toker->next()==EACH ){ toker->next(); string ident=parseIdent(); stmts=parseStmtSeq( STMTS_BLOCK, debug); int pos=toker->pos(); if( toker->curr()!=NEXT ) exp( "'Next'" ); toker->next(); result=d_new ForEachNode( var.release(),ident,stmts.release(),pos ); }else{ a_ptr<ExprNode> from,to,step; from=parseExpr( false ); if( toker->curr()!=TO ) exp( "'TO'" ); toker->next();to=parseExpr( false ); //step... if( toker->curr()==STEP ){ toker->next();step=parseExpr( false ); }else step=d_new IntConstNode( 1 ); stmts=parseStmtSeq( STMTS_BLOCK, debug); int pos=toker->pos(); if( toker->curr()!=NEXT ) exp( "'Next'" ); toker->next(); result=d_new ForNode( var.release(),from.release(),to.release(),step.release(),stmts.release(),pos ); } } break; case EXIT: { toker->next();result=d_new ExitNode(); } break; case GOTO: { toker->next();string t=parseIdent();result=d_new GotoNode( t ); } break; case GOSUB: { toker->next();string t=parseIdent();result=d_new GosubNode( t ); } break; case RETURN: { toker->next();result=d_new ReturnNode( parseExpr( true ) ); } break; case BBDELETE: { if( toker->next()==EACH ){ toker->next();string t=parseIdent(); result=d_new DeleteEachNode( t ); }else{ ExprNode *expr=parseExpr( false ); result=d_new DeleteNode( expr ); } } break; case INSERT: { toker->next(); a_ptr<ExprNode> expr1( parseExpr( false ) ); if( toker->curr()!=BEFORE && toker->curr()!=AFTER ) exp( "'Before' or 'After'" ); bool before=toker->curr()==BEFORE;toker->next(); a_ptr<ExprNode> expr2( parseExpr( false ) ); result=d_new InsertNode( expr1.release(),expr2.release(),before ); } break; case READ: do{ toker->next();VarNode *var=parseVar(); StmtNode *stmt=d_new ReadNode( var ); stmt->pos=pos;pos=toker->pos(); stmts->push_back( stmt ); }while( toker->curr()==',' ); break; case RESTORE: if( toker->next()==IDENT ){ result=d_new RestoreNode( toker->text() );toker->next(); }else result=d_new RestoreNode( "" ); break; case DATA: if( scope!=STMTS_PROG ) ex( "'Data' can only appear in main program" ); do{ toker->next(); ExprNode *expr=parseExpr( false ); datas->push_back( d_new DataDeclNode( expr ) ); }while( toker->curr()==',' ); break; case TYPE: if( scope!=STMTS_PROG ) ex( "'Type' can only appear in main program" ); toker->next();structs->push_back( parseStructDecl() ); break; case BBCONST: if( scope!=STMTS_PROG ) ex( "'Const' can only appear in main program" ); do{ toker->next();consts->push_back( parseVarDecl( DECL_GLOBAL,true ) ); }while( toker->curr()==',' ); break; case FUNCTION: if( scope!=STMTS_PROG ) ex( "'Function' can only appear in main program" ); toker->next();funcs->push_back( parseFuncDecl(debug) ); break; case DIM: do{ toker->next(); StmtNode *stmt=parseArrayDecl(); stmt->pos=pos;pos=toker->pos(); stmts->push_back( stmt ); }while( toker->curr()==',' ); break; case LOCAL: do{ toker->next(); DeclNode *d=parseVarDecl( DECL_LOCAL,false ); StmtNode *stmt=d_new DeclStmtNode( d ); stmt->pos=pos;pos=toker->pos(); stmts->push_back( stmt ); }while( toker->curr()==',' ); break; case GLOBAL: if( scope!=STMTS_PROG ) ex( "'Global' can only appear in main program" ); do{ toker->next(); DeclNode *d=parseVarDecl( DECL_GLOBAL,false ); StmtNode *stmt=d_new DeclStmtNode( d ); stmt->pos=pos;pos=toker->pos(); stmts->push_back( stmt ); }while( toker->curr()==',' ); break; case '.': { toker->next();string t=parseIdent(); result=d_new LabelNode( t,datas->size() ); } break; default: return; } if( result ){ result->pos=pos; stmts->push_back( result ); } } } string Parser::parseTypeTag(){ switch( toker->curr() ){ case '%':toker->next();return "%"; case '#':toker->next();return "#"; case '$':toker->next();return "$"; case '.':toker->next();return parseIdent(); } return ""; } VarNode *Parser::parseVar(){ string ident=parseIdent(); string tag=parseTypeTag(); return parseVar( ident,tag ); } VarNode *Parser::parseVar( const string &ident,const string &tag ){ a_ptr<VarNode> var; if( toker->curr()=='(' ){ toker->next(); a_ptr<ExprSeqNode> exprs( parseExprSeq() ); if( toker->curr()!=')' ) exp( "')'" ); toker->next(); var=d_new ArrayVarNode( ident,tag,exprs.release() ); }else var=d_new IdentVarNode( ident,tag ); for(;;){ if( toker->curr()=='\\' ){ toker->next(); string ident=parseIdent(); string tag=parseTypeTag(); ExprNode *expr=d_new VarExprNode( var.release() ); var=d_new FieldVarNode( expr,ident,tag ); }else if( toker->curr()=='[' ){ toker->next(); a_ptr<ExprSeqNode> exprs( parseExprSeq() ); if( exprs->exprs.size()!=1 || toker->curr()!=']' ) exp( "']'" ); toker->next(); ExprNode *expr=d_new VarExprNode( var.release() ); var=d_new VectorVarNode( expr,exprs.release() ); }else{ break; } } return var.release(); } DeclNode *Parser::parseVarDecl( int kind,bool constant ){ int pos=toker->pos(); string ident=parseIdent(); string tag=parseTypeTag(); DeclNode *d; if( toker->curr()=='[' ){ if( constant ) ex( "Blitz arrays may not be constant" ); toker->next(); a_ptr<ExprSeqNode> exprs( parseExprSeq() ); if( exprs->size()!=1 || toker->curr()!=']' ) exp( "']'" ); toker->next(); d=d_new VectorDeclNode( ident,tag,exprs.release(),kind ); }else{ ExprNode *expr=0; if( toker->curr()=='=' ){ toker->next();expr=parseExpr( false ); }else if( constant ) ex( "Constants must be initialized" ); d=d_new VarDeclNode( ident,tag,kind,constant,expr ); } d->pos=pos;d->file=incfile; return d; } DimNode *Parser::parseArrayDecl(){ int pos=toker->pos(); string ident=parseIdent(); string tag=parseTypeTag(); if( toker->curr()!='(' ) exp( "'('" ); toker->next();a_ptr<ExprSeqNode> exprs( parseExprSeq() ); if( toker->curr()!=')' ) exp( "')'" ); if( !exprs->size() ) ex( "can't have a 0 dimensional array" ); toker->next(); DimNode *d=d_new DimNode( ident,tag,exprs.release() ); arrayDecls[ident]=d; d->pos=pos; return d; } DeclNode *Parser::parseFuncDecl(bool debug){ int pos=toker->pos(); string ident=parseIdent(); string tag=parseTypeTag(); if( toker->curr()!='(' ) exp( "'('" ); a_ptr<DeclSeqNode> params( d_new DeclSeqNode() ); if( toker->next()!=')' ){ for(;;){ params->push_back( parseVarDecl( DECL_PARAM,false ) ); if( toker->curr()!=',' ) break; toker->next(); } if( toker->curr()!=')' ) exp( "')'" ); } toker->next(); a_ptr<StmtSeqNode> stmts( parseStmtSeq( STMTS_BLOCK, debug) ); if( toker->curr()!=ENDFUNCTION ) exp( "'End Function'" ); StmtNode *ret=d_new ReturnNode(0);ret->pos=toker->pos(); stmts->push_back( ret );toker->next(); DeclNode *d=d_new FuncDeclNode( ident,tag,params.release(),stmts.release() ); d->pos=pos;d->file=incfile; return d; } DeclNode *Parser::parseStructDecl(){ int pos=toker->pos(); string ident=parseIdent(); while( toker->curr()=='\n' ) toker->next(); a_ptr<DeclSeqNode> fields( d_new DeclSeqNode() ); while( toker->curr()==FIELD ){ do{ toker->next(); fields->push_back( parseVarDecl( DECL_FIELD,false ) ); }while( toker->curr()==',' ); while( toker->curr()=='\n' ) toker->next(); } if( toker->curr()!=ENDTYPE ) exp( "'Field' or 'End Type'" ); toker->next(); DeclNode *d=d_new StructDeclNode( ident,fields.release() ); d->pos=pos;d->file=incfile; return d; } IfNode *Parser::parseIf(bool debug){ a_ptr<ExprNode> expr; a_ptr<StmtSeqNode> stmts,elseOpt; expr=parseExpr( false ); if( toker->curr()==THEN ) toker->next(); bool blkif=isTerm( toker->curr() ); stmts=parseStmtSeq( blkif ? STMTS_BLOCK : STMTS_LINE, debug); if( toker->curr()==ELSEIF ){ int pos=toker->pos(); toker->next(); IfNode *ifnode=parseIf(debug); ifnode->pos=pos; elseOpt=d_new StmtSeqNode( incfile ); elseOpt->push_back( ifnode ); }else if( toker->curr()==ELSE ){ toker->next(); elseOpt=parseStmtSeq( blkif ? STMTS_BLOCK : STMTS_LINE, debug); } if( blkif ){ if( toker->curr()!=ENDIF ) exp( "'EndIf'" ); }else if( toker->curr()!='\n' ) exp( "end-of-line" ); return d_new IfNode( expr.release(),stmts.release(),elseOpt.release() ); } ExprSeqNode *Parser::parseExprSeq(){ a_ptr<ExprSeqNode> exprs( d_new ExprSeqNode() ); bool opt=true; while( ExprNode *e=parseExpr( opt ) ){ exprs->push_back( e ); if( toker->curr()!=',' ) break; toker->next();opt=false; } return exprs.release(); } ExprNode *Parser::parseExpr( bool opt ){ if( toker->curr()==NOT ){ toker->next(); ExprNode *expr=parseExpr1( false ); return d_new RelExprNode( '=',expr,d_new IntConstNode( 0 ) ); } return parseExpr1( opt ); } ExprNode *Parser::parseExpr1( bool opt ){ a_ptr<ExprNode> lhs( parseExpr1AND( opt ) ); if( !lhs ) return 0; for(;;){ int c=toker->curr(); if( c!=OR && c!=LOR && c!=XOR ) return lhs.release(); toker->next();ExprNode *rhs=parseExpr1AND( false ); lhs=d_new BinExprNode( c,lhs.release(),rhs ); } } ExprNode *Parser::parseExpr1AND( bool opt ){ a_ptr<ExprNode> lhs( parseExpr2( opt ) ); if( !lhs ) return 0; for(;;){ int c=toker->curr(); if( c!=AND ) return lhs.release(); toker->next();ExprNode *rhs=parseExpr2( false ); lhs=d_new BinExprNode( c,lhs.release(),rhs ); } } ExprNode *Parser::parseExpr2( bool opt ){ a_ptr<ExprNode> lhs( parseExpr3( opt ) ); if( !lhs ) return 0; for(;;){ int c=toker->curr(); if( c!='<' && c!='>' && c!='=' && c!=LE && c!=GE && c!=NE ) return lhs.release(); toker->next();ExprNode *rhs=parseExpr3( false ); lhs=d_new RelExprNode( c,lhs.release(),rhs ); } } ExprNode *Parser::parseExpr3( bool opt ){ a_ptr<ExprNode> lhs( parseExpr4( opt ) ); if( !lhs ) return 0; for(;;){ int c=toker->curr(); if( c!='+' && c!='-' ) return lhs.release(); toker->next();ExprNode *rhs=parseExpr4( false ); lhs=d_new ArithExprNode( c,lhs.release(),rhs ); } } ExprNode *Parser::parseExpr4( bool opt ){ a_ptr<ExprNode> lhs( parseExpr5( opt ) ); if( !lhs ) return 0; for(;;){ int c=toker->curr(); if( c!=SHL && c!=SHR && c!=SAR ) return lhs.release(); toker->next();ExprNode *rhs=parseExpr5( false ); lhs=d_new BinExprNode( c,lhs.release(),rhs ); } } ExprNode *Parser::parseExpr5( bool opt ){ a_ptr<ExprNode> lhs( parseExpr6( opt ) ); if( !lhs ) return 0; for(;;){ int c=toker->curr(); if( c!='*' && c!='/' && c!=MOD ) return lhs.release(); toker->next();ExprNode *rhs=parseExpr6( false ); lhs=d_new ArithExprNode( c,lhs.release(),rhs ); } } ExprNode *Parser::parseExpr6( bool opt ){ a_ptr<ExprNode> lhs( parseUniExpr( opt ) ); if( !lhs ) return 0; for(;;){ int c=toker->curr(); if( c!='^' ) return lhs.release(); toker->next();ExprNode *rhs=parseUniExpr( false ); lhs=d_new ArithExprNode( c,lhs.release(),rhs ); } } ExprNode *Parser::parseUniExpr( bool opt ){ ExprNode *result=0; string t; int c=toker->curr(); switch( c ){ case BBINT: if( toker->next()=='%' ) toker->next(); result=parseUniExpr( false ); result=d_new CastNode( result,Type::int_type ); break; case BBFLOAT: if( toker->next()=='#' ) toker->next(); result=parseUniExpr( false ); result=d_new CastNode( result,Type::float_type ); break; case BBSTR: if( toker->next()=='$' ) toker->next(); result=parseUniExpr( false ); result=d_new CastNode( result,Type::string_type ); break; case OBJECT: if( toker->next()=='.' ) toker->next(); t=parseIdent(); result=parseUniExpr( false ); result=d_new ObjectCastNode( result,t ); break; case BBHANDLE: toker->next(); result=parseUniExpr( false ); result=d_new ObjectHandleNode( result ); break; case BEFORE: toker->next(); result=parseUniExpr( false ); result=d_new BeforeNode( result ); break; case AFTER: toker->next(); result=parseUniExpr( false ); result=d_new AfterNode( result ); break; case '+':case '-':case '~':case ABS:case SGN: toker->next(); result=parseUniExpr( false ); if( c=='~' ){ result=d_new BinExprNode( XOR,result,d_new IntConstNode( -1 ) ); }else{ result=d_new UniExprNode( c,result ); } break; default: result=parsePrimary( opt ); } return result; } // Don't ask me what this does. Thanks Juan! float stuff(unsigned int i){ return *((float*)(void*)&i); } ExprNode *Parser::parsePrimary( bool opt ){ a_ptr<ExprNode> expr; string t,ident,tag; ExprNode *result=0; int n,k; switch( toker->curr() ){ case '(': toker->next(); expr=parseExpr( false ); if( toker->curr()!=')' ) exp( "')'" ); toker->next(); result=expr.release(); break; case BBNEW: toker->next();t=parseIdent(); result=d_new NewNode( t ); break; case FIRST: toker->next();t=parseIdent(); result=d_new FirstNode( t ); break; case LAST: toker->next();t=parseIdent(); result=d_new LastNode( t ); break; case NULLCONST: result=d_new NullConstNode(); toker->next(); break; case INTCONST: result=d_new IntConstNode( atoi( toker->text() ) ); toker->next(); break; case FLOATCONST: result=d_new FloatConstNode( atof( toker->text() ) ); toker->next(); break; case STRINGCONST: t=toker->text(); result=d_new StringConstNode( t.substr( 1,t.size()-2 ) ); toker->next(); break; case BINCONST: n=0;t=toker->text(); for( k=1;k<t.size();++k ) n=(n<<1)|(t[k]=='1'); result=d_new IntConstNode( n ); toker->next(); break; case HEXCONST: n=0;t=toker->text(); for( k=1;k<t.size();++k ) n=(n<<4)|( isdigit(t[k]) ? t[k]&0xf : (t[k]&7)+9 ); result=d_new IntConstNode( n ); toker->next(); break; case PI: result=d_new FloatConstNode( 3.1415926535897932384626433832795f ); toker->next();break; case INFINITY: result=d_new FloatConstNode( stuff(0x7F800000) ); toker->next();break; case NANCONST: result=d_new FloatConstNode( stuff(0x7FFFFFFF) ); toker->next();break; case BBTRUE: result=d_new IntConstNode( 1 ); toker->next();break; case BBFALSE: result=d_new IntConstNode( 0 ); toker->next();break; case IDENT: ident=toker->text(); toker->next();tag=parseTypeTag(); if( toker->curr()=='(' && arrayDecls.find(ident)==arrayDecls.end() ){ //must be a func toker->next(); a_ptr<ExprSeqNode> exprs( parseExprSeq() ); if( toker->curr()!=')' ) exp( "')'" ); toker->next(); result=d_new CallNode( ident,tag,exprs.release() ); }else{ //must be a var VarNode *var=parseVar( ident,tag ); result=d_new VarExprNode( var ); } break; default: if( !opt ) exp( "expression" ); } return result; }
; ; Copyright (c) 2020 Phillip Stevens ; ; This Source Code Form is subject to the terms of the Mozilla Public ; License, v. 2.0. If a copy of the MPL was not distributed with this ; file, You can obtain one at http://mozilla.org/MPL/2.0/. ; ; feilipu, August 2020 ; ;------------------------------------------------------------------------- ; asm_am9511_1_pushf - am9511 APU push float ;------------------------------------------------------------------------- ; ; Load IEEE-754 float into Am9511 APU stack ; ;------------------------------------------------------------------------- SECTION code_fp_am9511 IFDEF __CLASSIC INCLUDE "../../_DEVELOPMENT/target/am9511/config_am9511_private.inc" ELSE INCLUDE "target/am9511/config_am9511_private.inc" ENDIF PUBLIC asm_am9511_1_pushf_hl PUBLIC asm_am9511_1_pushf_fastcall EXTERN asm_am9511_pushf_zero EXTERN asm_am9511_pushf_max EXTERN asm_am9511_pushf_rejoin_fastcall EXTERN asm_am9511_pushf_zero_fastcall EXTERN asm_am9511_pushf_max_fastcall .am9511_1_pushf_hl_wait ex (sp),hl ex (sp),hl .asm_am9511_1_pushf_hl ; float primitive ; push a IEEE-754 floating point into Am9511 stack. ; ; Convert from IEEE_float to am9511_float. ; ; enter : stack = IEEE_float, ret1, ret0 ; : hl = pointer to IEEE_float ; ; exit : stack = IEEE_float, ret1 ; ; uses : af, bc, hl in a,(__IO_APU1_STATUS) ; read the APU status register rlca ; busy? and __IO_APU_STATUS_BUSY jr C,am9511_1_pushf_hl_wait ld bc,__IO_APU1_DATA ; the address of the APU data port in bc outi ; load LSW into APU inc b outi inc b ld a,(hl) ; get mantissa MSB rla ; get exponent least significant bit to carry inc hl ld a,(hl) ; get exponent to a rl a ; get all exponent to a, set flags jp Z,asm_am9511_pushf_zero ; check for zero cp 127+63 ; check for overflow jp NC,asm_am9511_pushf_max cp 127-64 ; check for underflow jp C,asm_am9511_pushf_zero sub 127-1 ; bias including shift binary point dec hl set 7,(hl) ; set mantissa MSB outi ; load mantissa MSB into APU inc b rla ; position exponent for sign rl (hl) ; get sign rra out (c),a ; load exponent into APU ret .am9511_1_pushf_fastcall_wait ex (sp),hl ex (sp),hl .asm_am9511_1_pushf_fastcall ; float primitive ; push a IEEE-754 floating point into Am9511 stack. ; ; Convert from IEEE_float to am9511_float. ; ; enter : stack = ret1, ret0 ; : dehl = IEEE_float ; ; exit : stack = ret1 ; ; uses : af, bc, de, hl in a,(__IO_APU1_STATUS) ; read the APU status register rlca ; busy? and __IO_APU_STATUS_BUSY jr C,am9511_1_pushf_fastcall_wait ld bc,__IO_APU1_DATA ; the address of the APU data port in bc ld a,d ; capture exponent sla e ; position exponent in a rl a ; check for zero jp Z,asm_am9511_pushf_zero_fastcall cp 127+63 ; check for overflow jp NC,asm_am9511_pushf_max_fastcall cp 127-64 ; check for underflow jp C,asm_am9511_pushf_zero_fastcall sub 127-1 ; bias including shift binary point rla ; position exponent for sign rl d ; get sign rra ld d,a ; restore exponent scf ; set mantissa leading 1 rr e ; restore mantissa jp asm_am9511_pushf_rejoin_fastcall
; $Id: CPUMR0A.asm $ ;; @file ; CPUM - Ring-0 Assembly Routines (supporting HM and IEM). ; ; ; Copyright (C) 2006-2015 Oracle Corporation ; ; This file is part of VirtualBox Open Source Edition (OSE), as ; available from http://www.virtualbox.org. This file is free software; ; you can redistribute it and/or modify it under the terms of the GNU ; General Public License (GPL) as published by the Free Software ; Foundation, in version 2 as it comes in the "COPYING" file of the ; VirtualBox OSE distribution. VirtualBox OSE is distributed in the ; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. ; ;******************************************************************************* ;* Header Files * ;******************************************************************************* %include "VBox/asmdefs.mac" %include "VBox/vmm/vm.mac" %include "VBox/err.mac" %include "VBox/vmm/stam.mac" %include "CPUMInternal.mac" %include "iprt/x86.mac" %include "VBox/vmm/cpum.mac" %ifdef IN_RING3 %error "The jump table doesn't link on leopard." %endif ;******************************************************************************* ;* Defined Constants And Macros * ;******************************************************************************* ;; The offset of the XMM registers in X86FXSTATE. ; Use define because I'm too lazy to convert the struct. %define XMM_OFF_IN_X86FXSTATE 160 %define IP_OFF_IN_X86FXSTATE 08h %define CS_OFF_IN_X86FXSTATE 0ch %define DS_OFF_IN_X86FXSTATE 14h ;; For numeric expressions %ifdef RT_ARCH_AMD64 %define CPUMR0_IS_AMD64 1 %else %define CPUMR0_IS_AMD64 0 %endif ;******************************************************************************* ;* External Symbols * ;******************************************************************************* %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL extern NAME(SUPR0AbsIs64bit) extern NAME(SUPR0Abs64bitKernelCS) extern NAME(SUPR0Abs64bitKernelSS) extern NAME(SUPR0Abs64bitKernelDS) extern NAME(SUPR0AbsKernelCS) %endif ;******************************************************************************* ;* Global Variables * ;******************************************************************************* %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL BEGINDATA %if 0 ; Currently not used. g_r32_Zero: dd 0.0 %endif ;; ; Store the SUPR0AbsIs64bit absolute value here so we can cmp/test without ; needing to clobber a register. (This trick doesn't quite work for PE btw. ; but that's not relevant atm.) GLOBALNAME g_fCPUMIs64bitHost dd NAME(SUPR0AbsIs64bit) %endif BEGINCODE %if 0 ; Currently not used anywhere. ;; ; Macro for FXSAVE/FXRSTOR leaky behaviour on AMD CPUs, see cpumR3CheckLeakyFpu(). ; ; Cleans the FPU state, if necessary, before restoring the FPU. ; ; This macro ASSUMES CR0.TS is not set! ; ; @param xDX Pointer to CPUMCPU. ; @uses xAX, EFLAGS ; ; Changes here should also be reflected in CPUMRCA.asm's copy! ; %macro CLEANFPU 0 test dword [xDX + CPUMCPU.fUseFlags], CPUM_USE_FFXSR_LEAKY jz .nothing_to_clean xor eax, eax fnstsw ax ; FSW -> AX. test eax, RT_BIT(7) ; If FSW.ES (bit 7) is set, clear it to not cause FPU exceptions ; while clearing & loading the FPU bits in 'clean_fpu' below. jz .clean_fpu fnclex .clean_fpu: ffree st7 ; Clear FPU stack register(7)'s tag entry to prevent overflow if a wraparound occurs. ; for the upcoming push (load) fild dword [g_r32_Zero xWrtRIP] ; Explicit FPU load to overwrite FIP, FOP, FDP registers in the FPU. .nothing_to_clean: %endmacro %endif ; Unused. ;; ; Clears CR0.TS and CR0.EM if necessary, saving the previous result. ; ; This is used to avoid FPU exceptions when touching the FPU state. ; ; @param %1 Register to save the old CR0 in (pass to RESTORE_CR0). ; @param %2 Temporary scratch register. ; @uses EFLAGS, CR0 ; %macro SAVE_CR0_CLEAR_FPU_TRAPS 2 xor %1, %1 mov %2, cr0 test %2, X86_CR0_TS | X86_CR0_EM ; Make sure its safe to access the FPU state. jz %%skip_cr0_write mov %1, %2 ; Save old CR0 and %2, ~(X86_CR0_TS | X86_CR0_EM) mov cr0, %2 %%skip_cr0_write: %endmacro ;; ; Restore CR0.TS and CR0.EM state if SAVE_CR0_CLEAR_FPU_TRAPS change it. ; ; @param %1 The register that SAVE_CR0_CLEAR_FPU_TRAPS saved the old CR0 in. ; %macro RESTORE_CR0 1 cmp %1, 0 je %%skip_cr0_restore mov cr0, %1 %%skip_cr0_restore: %endmacro ;; ; Saves the host state. ; ; @uses rax, rdx ; @param pCpumCpu Define for the register containing the CPUMCPU pointer. ; @param pXState Define for the regsiter containing the extended state pointer. ; %macro CPUMR0_SAVE_HOST 0 ; ; Load a couple of registers we'll use later in all branches. ; mov pXState, [pCpumCpu + CPUMCPU.Host.pXStateR0] mov eax, [pCpumCpu + CPUMCPU.Host.fXStateMask] %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL ; The joy of 32-bit darwin kernels that runs the CPU in 64-bit mode. cmp byte [NAME(g_fCPUMIs64bitHost)], 0 jz %%host_legacy_mode db 0xea ; jmp far .sixtyfourbit_mode dd %%host_sixtyfourbit_mode, NAME(SUPR0Abs64bitKernelCS) BITS 64 %%host_sixtyfourbit_mode: or eax, eax jz %%host_sixtyfourbit_fxsave ; XSAVE mov edx, [pCpumCpu + CPUMCPU.Host.fXStateMask + 4] o64 xsave [pXState] jmp %%host_sixtyfourbit_done ; FXSAVE %%host_sixtyfourbit_fxsave: o64 fxsave [pXState] %%host_sixtyfourbit_done: jmp far [%%host_fpret wrt rip] %%host_fpret: ; 16:32 Pointer to %%host_done. dd %%host_done, NAME(SUPR0AbsKernelCS) BITS 32 %%host_legacy_mode: %endif ; ; XSAVE or FXSAVE? ; or eax, eax jz %%host_fxsave ; XSAVE mov edx, [pCpumCpu + CPUMCPU.Host.fXStateMask + 4] %ifdef RT_ARCH_AMD64 o64 xsave [pXState] %else xsave [pXState] %endif jmp %%host_done ; FXSAVE %%host_fxsave: %ifdef RT_ARCH_AMD64 o64 fxsave [pXState] ; Use explicit REX prefix. See @bugref{6398}. %else fxsave [pXState] %endif %%host_done: %endmacro ; CPUMR0_SAVE_HOST ;; ; Loads the host state. ; ; @uses rax, rdx ; @param pCpumCpu Define for the register containing the CPUMCPU pointer. ; @param pXState Define for the regsiter containing the extended state pointer. ; %macro CPUMR0_LOAD_HOST 0 ; ; Load a couple of registers we'll use later in all branches. ; mov pXState, [pCpumCpu + CPUMCPU.Host.pXStateR0] mov eax, [pCpumCpu + CPUMCPU.Host.fXStateMask] %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL ; The joy of 32-bit darwin kernels that runs the CPU in 64-bit mode. cmp byte [NAME(g_fCPUMIs64bitHost)], 0 jz %%host_legacy_mode db 0xea ; jmp far .sixtyfourbit_mode dd %%host_sixtyfourbit_mode, NAME(SUPR0Abs64bitKernelCS) BITS 64 %%host_sixtyfourbit_mode: or eax, eax jz %%host_sixtyfourbit_fxrstor ; XRSTOR mov edx, [pCpumCpu + CPUMCPU.Host.fXStateMask + 4] o64 xrstor [pXState] jmp %%host_sixtyfourbit_done ; FXRSTOR %%host_sixtyfourbit_fxrstor: o64 fxrstor [pXState] %%host_sixtyfourbit_done: jmp far [%%host_fpret wrt rip] %%host_fpret: ; 16:32 Pointer to %%host_done. dd %%host_done, NAME(SUPR0AbsKernelCS) BITS 32 %%host_legacy_mode: %endif ; ; XRSTOR or FXRSTOR? ; or eax, eax jz %%host_fxrstor ; XRSTOR mov edx, [pCpumCpu + CPUMCPU.Host.fXStateMask + 4] %ifdef RT_ARCH_AMD64 o64 xrstor [pXState] %else xrstor [pXState] %endif jmp %%host_done ; FXRSTOR %%host_fxrstor: %ifdef RT_ARCH_AMD64 o64 fxrstor [pXState] ; Use explicit REX prefix. See @bugref{6398}. %else fxrstor [pXState] %endif %%host_done: %endmacro ; CPUMR0_LOAD_HOST ;; Macro for FXSAVE for the guest FPU but tries to figure out whether to ; save the 32-bit FPU state or 64-bit FPU state. ; ; @param %1 Pointer to CPUMCPU. ; @param %2 Pointer to XState. ; @param %3 Force AMD64 ; @uses xAX, xDX, EFLAGS, 20h of stack. ; %macro SAVE_32_OR_64_FPU 3 %if CPUMR0_IS_AMD64 || %3 ; Save the guest FPU (32-bit or 64-bit), preserves existing broken state. See @bugref{7138}. test dword [pCpumCpu + CPUMCPU.fUseFlags], CPUM_USE_SUPPORTS_LONGMODE jnz short %%save_long_mode_guest %endif fxsave [pXState] %if CPUMR0_IS_AMD64 || %3 jmp %%save_done_32bit_cs_ds %%save_long_mode_guest: o64 fxsave [pXState] xor edx, edx cmp dword [pXState + CS_OFF_IN_X86FXSTATE], 0 jne short %%save_done sub rsp, 20h ; Only need 1ch bytes but keep stack aligned otherwise we #GP(0). fnstenv [rsp] movzx eax, word [rsp + 10h] mov [pXState + CS_OFF_IN_X86FXSTATE], eax movzx eax, word [rsp + 18h] add rsp, 20h mov [pXState + DS_OFF_IN_X86FXSTATE], eax %endif %%save_done_32bit_cs_ds: mov edx, X86_FXSTATE_RSVD_32BIT_MAGIC %%save_done: mov dword [pXState + X86_OFF_FXSTATE_RSVD], edx %endmacro ; SAVE_32_OR_64_FPU ;; ; Save the guest state. ; ; @uses rax, rdx ; @param pCpumCpu Define for the register containing the CPUMCPU pointer. ; @param pXState Define for the regsiter containing the extended state pointer. ; %macro CPUMR0_SAVE_GUEST 0 ; ; Load a couple of registers we'll use later in all branches. ; mov pXState, [pCpumCpu + CPUMCPU.Guest.pXStateR0] mov eax, [pCpumCpu + CPUMCPU.Guest.fXStateMask] %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL ; The joy of 32-bit darwin kernels that runs the CPU in 64-bit mode. cmp byte [NAME(g_fCPUMIs64bitHost)], 0 jz %%guest_legacy_mode db 0xea ; jmp far .sixtyfourbit_mode dd %%guest_sixtyfourbit_mode, NAME(SUPR0Abs64bitKernelCS) BITS 64 %%guest_sixtyfourbit_mode: or eax, eax jz %%guest_sixtyfourbit_fxsave ; XSAVE mov edx, [pCpumCpu + CPUMCPU.Guest.fXStateMask + 4] o64 xsave [pXState] jmp %%guest_sixtyfourbit_done ; FXSAVE %%guest_sixtyfourbit_fxsave: SAVE_32_OR_64_FPU pCpumCpu, pXState, 1 %%guest_sixtyfourbit_done: jmp far [%%guest_fpret wrt rip] %%guest_fpret: ; 16:32 Pointer to %%guest_done. dd %%guest_done, NAME(SUPR0AbsKernelCS) BITS 32 %%guest_legacy_mode: %endif ; ; XSAVE or FXSAVE? ; or eax, eax jz %%guest_fxsave ; XSAVE mov edx, [pCpumCpu + CPUMCPU.Guest.fXStateMask + 4] %ifdef VBOX_WITH_KERNEL_USING_XMM and eax, ~CPUM_VOLATILE_XSAVE_GUEST_COMPONENTS ; Already saved in HMR0A.asm. %endif %ifdef RT_ARCH_AMD64 o64 xsave [pXState] %else xsave [pXState] %endif jmp %%guest_done ; FXSAVE %%guest_fxsave: SAVE_32_OR_64_FPU pCpumCpu, pXState, 0 %%guest_done: %endmacro ; CPUMR0_SAVE_GUEST ;; ; Wrapper for selecting 32-bit or 64-bit FXRSTOR according to what SAVE_32_OR_64_FPU did. ; ; @param %1 Pointer to CPUMCPU. ; @param %2 Pointer to XState. ; @param %3 Force AMD64. ; @uses xAX, xDX, EFLAGS ; %macro RESTORE_32_OR_64_FPU 3 %if CPUMR0_IS_AMD64 || %3 ; Restore the guest FPU (32-bit or 64-bit), preserves existing broken state. See @bugref{7138}. test dword [pCpumCpu + CPUMCPU.fUseFlags], CPUM_USE_SUPPORTS_LONGMODE jz %%restore_32bit_fpu cmp dword [pXState + X86_OFF_FXSTATE_RSVD], X86_FXSTATE_RSVD_32BIT_MAGIC jne short %%restore_64bit_fpu %%restore_32bit_fpu: %endif fxrstor [pXState] %if CPUMR0_IS_AMD64 || %3 ; TODO: Restore XMM8-XMM15! jmp short %%restore_fpu_done %%restore_64bit_fpu: o64 fxrstor [pXState] %%restore_fpu_done: %endif %endmacro ; RESTORE_32_OR_64_FPU ;; ; Loads the guest state. ; ; @uses rax, rdx ; @param pCpumCpu Define for the register containing the CPUMCPU pointer. ; @param pXState Define for the regsiter containing the extended state pointer. ; %macro CPUMR0_LOAD_GUEST 0 ; ; Load a couple of registers we'll use later in all branches. ; mov pXState, [pCpumCpu + CPUMCPU.Guest.pXStateR0] mov eax, [pCpumCpu + CPUMCPU.Guest.fXStateMask] %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL ; The joy of 32-bit darwin kernels that runs the CPU in 64-bit mode. cmp byte [NAME(g_fCPUMIs64bitHost)], 0 jz %%guest_legacy_mode db 0xea ; jmp far .sixtyfourbit_mode dd %%guest_sixtyfourbit_mode, NAME(SUPR0Abs64bitKernelCS) BITS 64 %%guest_sixtyfourbit_mode: or eax, eax jz %%guest_sixtyfourbit_fxrstor ; XRSTOR mov edx, [pCpumCpu + CPUMCPU.Guest.fXStateMask + 4] o64 xrstor [pXState] jmp %%guest_sixtyfourbit_done ; FXRSTOR %%guest_sixtyfourbit_fxrstor: RESTORE_32_OR_64_FPU pCpumCpu, pXState, 1 %%guest_sixtyfourbit_done: jmp far [%%guest_fpret wrt rip] %%guest_fpret: ; 16:32 Pointer to %%guest_done. dd %%guest_done, NAME(SUPR0AbsKernelCS) BITS 32 %%guest_legacy_mode: %endif ; ; XRSTOR or FXRSTOR? ; or eax, eax jz %%guest_fxrstor ; XRSTOR mov edx, [pCpumCpu + CPUMCPU.Guest.fXStateMask + 4] %ifdef VBOX_WITH_KERNEL_USING_XMM and eax, ~CPUM_VOLATILE_XSAVE_GUEST_COMPONENTS ; Will be loaded by HMR0A.asm. %endif %ifdef RT_ARCH_AMD64 o64 xrstor [pXState] %else xrstor [pXState] %endif jmp %%guest_done ; FXRSTOR %%guest_fxrstor: RESTORE_32_OR_64_FPU pCpumCpu, pXState, 0 %%guest_done: %endmacro ; CPUMR0_LOAD_GUEST ;; ; Saves the host FPU/SSE/AVX state and restores the guest FPU/SSE/AVX state. ; ; @returns 0 ; @param pCpumCpu x86:[ebp+8] gcc:rdi msc:rcx CPUMCPU pointer ; align 16 BEGINPROC cpumR0SaveHostRestoreGuestFPUState ; ; Prologue - xAX+xDX must be free for XSAVE/XRSTOR input. ; %ifdef RT_ARCH_AMD64 %ifdef RT_OS_WINDOWS mov r11, rcx %else mov r11, rdi %endif %define pCpumCpu r11 %define pXState r10 %else push ebp mov ebp, esp push ebx push esi mov ebx, dword [ebp + 8] %define pCpumCpu ebx %define pXState esi %endif pushf ; The darwin kernel can get upset or upset things if an cli ; interrupt occurs while we're doing fxsave/fxrstor/cr0. SAVE_CR0_CLEAR_FPU_TRAPS xCX, xAX ; xCX is now old CR0 value, don't use! CPUMR0_SAVE_HOST CPUMR0_LOAD_GUEST %ifdef VBOX_WITH_KERNEL_USING_XMM ; Restore the non-volatile xmm registers. ASSUMING 64-bit host. mov pXState, [pCpumCpu + CPUMCPU.Host.pXStateR0] movdqa xmm6, [pXState + XMM_OFF_IN_X86FXSTATE + 060h] movdqa xmm7, [pXState + XMM_OFF_IN_X86FXSTATE + 070h] movdqa xmm8, [pXState + XMM_OFF_IN_X86FXSTATE + 080h] movdqa xmm9, [pXState + XMM_OFF_IN_X86FXSTATE + 090h] movdqa xmm10, [pXState + XMM_OFF_IN_X86FXSTATE + 0a0h] movdqa xmm11, [pXState + XMM_OFF_IN_X86FXSTATE + 0b0h] movdqa xmm12, [pXState + XMM_OFF_IN_X86FXSTATE + 0c0h] movdqa xmm13, [pXState + XMM_OFF_IN_X86FXSTATE + 0d0h] movdqa xmm14, [pXState + XMM_OFF_IN_X86FXSTATE + 0e0h] movdqa xmm15, [pXState + XMM_OFF_IN_X86FXSTATE + 0f0h] %endif RESTORE_CR0 xCX or dword [pCpumCpu + CPUMCPU.fUseFlags], (CPUM_USED_FPU | CPUM_USED_FPU_SINCE_REM) popf %ifdef RT_ARCH_X86 pop esi pop ebx leave %endif xor eax, eax ret ENDPROC cpumR0SaveHostRestoreGuestFPUState %ifndef RT_ARCH_AMD64 %ifdef VBOX_WITH_64_BITS_GUESTS %ifndef VBOX_WITH_HYBRID_32BIT_KERNEL ;; ; Saves the host FPU/SSE/AVX state. ; ; @returns VINF_SUCCESS (0) in EAX ; @param pCpumCpu x86:[ebp+8] gcc:rdi msc:rcx CPUMCPU pointer ; align 16 BEGINPROC cpumR0SaveHostFPUState ; ; Prologue - xAX+xDX must be free for XSAVE/XRSTOR input. ; %ifdef RT_ARCH_AMD64 %ifdef RT_OS_WINDOWS mov r11, rcx %else mov r11, rdi %endif %define pCpumCpu r11 %define pXState r10 %else push ebp mov ebp, esp push ebx push esi mov ebx, dword [ebp + 8] %define pCpumCpu ebx %define pXState esi %endif pushf ; The darwin kernel can get upset or upset things if an cli ; interrupt occurs while we're doing fxsave/fxrstor/cr0. SAVE_CR0_CLEAR_FPU_TRAPS xCX, xAX ; xCX is now old CR0 value, don't use! CPUMR0_SAVE_HOST RESTORE_CR0 xCX or dword [pCpumCpu + CPUMCPU.fUseFlags], (CPUM_USED_FPU | CPUM_USED_FPU_SINCE_REM) popf %ifdef RT_ARCH_X86 pop esi pop ebx leave %endif xor eax, eax ret %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL_IN_R0 ALIGNCODE(16) BITS 64 .sixtyfourbit_mode: ; Save the guest FPU (32-bit or 64-bit), preserves existing broken state. See @bugref{7138}. o64 fxsave [pXstate] jmp far [.fpret wrt rip] .fpret: ; 16:32 Pointer to .the_end. dd .done, NAME(SUPR0AbsKernelCS) BITS 32 %endif %undef pCpumCpu %undef pXState ENDPROC cpumR0SaveHostFPUState %endif %endif %endif ;; ; Saves the guest FPU/SSE/AVX state and restores the host FPU/SSE/AVX state. ; ; @returns VINF_SUCCESS (0) in eax. ; @param pCpumCpu x86:[ebp+8] gcc:rdi msc:rcx CPUMCPU pointer ; align 16 BEGINPROC cpumR0SaveGuestRestoreHostFPUState ; ; Prologue - xAX+xDX must be free for XSAVE/XRSTOR input. ; %ifdef RT_ARCH_AMD64 %ifdef RT_OS_WINDOWS mov r11, rcx %else mov r11, rdi %endif %define pCpumCpu r11 %define pXState r10 %else push ebp mov ebp, esp push ebx push esi mov ebx, dword [ebp + 8] %define pCpumCpu ebx %define pXState esi %endif ; ; Only restore FPU if guest has used it. ; test dword [pCpumCpu + CPUMCPU.fUseFlags], CPUM_USED_FPU jz .fpu_not_used pushf ; The darwin kernel can get upset or upset things if an cli ; interrupt occurs while we're doing fxsave/fxrstor/cr0. SAVE_CR0_CLEAR_FPU_TRAPS xCX, xAX ; xCX is now old CR0 value, don't use! CPUMR0_SAVE_GUEST CPUMR0_LOAD_HOST RESTORE_CR0 xCX and dword [pCpumCpu + CPUMCPU.fUseFlags], ~CPUM_USED_FPU popf .fpu_not_used: %ifdef RT_ARCH_X86 pop esi pop ebx leave %endif xor eax, eax ret %undef pCpumCpu %undef pXState ENDPROC cpumR0SaveGuestRestoreHostFPUState ;; ; Restores the host's FPU/SSE/AVX state from pCpumCpu->Host. ; ; @returns 0 ; @param pCpumCpu x86:[ebp+8] gcc:rdi msc:rcx CPUMCPU pointer ; align 16 BEGINPROC cpumR0RestoreHostFPUState ; ; Prologue - xAX+xDX must be free for XSAVE/XRSTOR input. ; %ifdef RT_ARCH_AMD64 %ifdef RT_OS_WINDOWS mov r11, rcx %else mov r11, rdi %endif %define pCpumCpu r11 %define pXState r10 %else push ebp mov ebp, esp push ebx push esi mov ebx, dword [ebp + 8] %define pCpumCpu ebx %define pXState esi %endif ; ; Restore FPU if guest has used it. ; test dword [pCpumCpu + CPUMCPU.fUseFlags], CPUM_USED_FPU jz short .fpu_not_used pushf ; The darwin kernel can get upset or upset things if an cli ; interrupt occurs while we're doing fxsave/fxrstor/cr0. SAVE_CR0_CLEAR_FPU_TRAPS xCX, xAX ; xCX is now old CR0 value, don't use! CPUMR0_LOAD_HOST RESTORE_CR0 xCX and dword [pCpumCpu + CPUMCPU.fUseFlags], ~CPUM_USED_FPU popf .fpu_not_used: %ifdef RT_ARCH_X86 pop esi pop ebx leave %endif xor eax, eax ret %undef pCpumCPu %undef pXState ENDPROC cpumR0RestoreHostFPUState %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL_IN_R0 ;; ; DECLASM(void) cpumR0SaveDRx(uint64_t *pa4Regs); ; ALIGNCODE(16) BEGINPROC cpumR0SaveDRx %ifdef RT_ARCH_AMD64 %ifdef ASM_CALL64_GCC mov xCX, rdi %endif %else mov xCX, dword [esp + 4] %endif pushf ; Just to be on the safe side. cli %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL cmp byte [NAME(g_fCPUMIs64bitHost)], 0 jz .legacy_mode db 0xea ; jmp far .sixtyfourbit_mode dd .sixtyfourbit_mode, NAME(SUPR0Abs64bitKernelCS) .legacy_mode: %endif ; VBOX_WITH_HYBRID_32BIT_KERNEL ; ; Do the job. ; mov xAX, dr0 mov xDX, dr1 mov [xCX], xAX mov [xCX + 8 * 1], xDX mov xAX, dr2 mov xDX, dr3 mov [xCX + 8 * 2], xAX mov [xCX + 8 * 3], xDX .done: popf ret %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL_IN_R0 ALIGNCODE(16) BITS 64 .sixtyfourbit_mode: and ecx, 0ffffffffh mov rax, dr0 mov rdx, dr1 mov r8, dr2 mov r9, dr3 mov [rcx], rax mov [rcx + 8 * 1], rdx mov [rcx + 8 * 2], r8 mov [rcx + 8 * 3], r9 jmp far [.fpret wrt rip] .fpret: ; 16:32 Pointer to .the_end. dd .done, NAME(SUPR0AbsKernelCS) BITS 32 %endif ENDPROC cpumR0SaveDRx ;; ; DECLASM(void) cpumR0LoadDRx(uint64_t const *pa4Regs); ; ALIGNCODE(16) BEGINPROC cpumR0LoadDRx %ifdef RT_ARCH_AMD64 %ifdef ASM_CALL64_GCC mov xCX, rdi %endif %else mov xCX, dword [esp + 4] %endif pushf ; Just to be on the safe side. cli %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL cmp byte [NAME(g_fCPUMIs64bitHost)], 0 jz .legacy_mode db 0xea ; jmp far .sixtyfourbit_mode dd .sixtyfourbit_mode, NAME(SUPR0Abs64bitKernelCS) .legacy_mode: %endif ; VBOX_WITH_HYBRID_32BIT_KERNEL ; ; Do the job. ; mov xAX, [xCX] mov xDX, [xCX + 8 * 1] mov dr0, xAX mov dr1, xDX mov xAX, [xCX + 8 * 2] mov xDX, [xCX + 8 * 3] mov dr2, xAX mov dr3, xDX .done: popf ret %ifdef VBOX_WITH_HYBRID_32BIT_KERNEL_IN_R0 ALIGNCODE(16) BITS 64 .sixtyfourbit_mode: and ecx, 0ffffffffh mov rax, [rcx] mov rdx, [rcx + 8 * 1] mov r8, [rcx + 8 * 2] mov r9, [rcx + 8 * 3] mov dr0, rax mov dr1, rdx mov dr2, r8 mov dr3, r9 jmp far [.fpret wrt rip] .fpret: ; 16:32 Pointer to .the_end. dd .done, NAME(SUPR0AbsKernelCS) BITS 32 %endif ENDPROC cpumR0LoadDRx %endif ; VBOX_WITH_HYBRID_32BIT_KERNEL_IN_R0
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %r15 push %r8 push %rcx push %rdi push %rsi lea addresses_D_ht+0xb3c, %rcx nop nop nop nop nop and %r15, %r15 vmovups (%rcx), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $1, %xmm6, %r8 nop nop nop nop xor %r10, %r10 lea addresses_UC_ht+0xf5c4, %rsi lea addresses_A_ht+0xe5ac, %rdi nop nop nop nop nop sub %r13, %r13 mov $99, %rcx rep movsq nop nop and %r13, %r13 lea addresses_A_ht+0x11e94, %rsi lea addresses_A_ht+0x15dc4, %rdi nop nop cmp $53791, %r12 mov $11, %rcx rep movsl nop nop nop nop nop cmp $41564, %r13 lea addresses_UC_ht+0x143a3, %r12 nop nop nop cmp $62642, %r8 movl $0x61626364, (%r12) nop cmp %r10, %r10 lea addresses_A_ht+0xaf9b, %rsi lea addresses_D_ht+0x6544, %rdi nop nop nop nop and %r8, %r8 mov $37, %rcx rep movsl nop nop xor %r13, %r13 lea addresses_D_ht+0x19944, %rdi nop nop cmp $8544, %r10 movl $0x61626364, (%rdi) nop nop and %r8, %r8 lea addresses_D_ht+0x1ad44, %rsi lea addresses_D_ht+0x1d204, %rdi nop nop nop nop add %r10, %r10 mov $124, %rcx rep movsw nop nop nop nop dec %r13 lea addresses_WT_ht+0x32e4, %r13 nop xor %rdi, %rdi movl $0x61626364, (%r13) nop nop nop cmp %r12, %r12 lea addresses_A_ht+0x6394, %r10 nop nop nop nop cmp $34925, %r13 mov (%r10), %si nop nop nop nop nop xor $44048, %rsi lea addresses_WT_ht+0xedc4, %rsi lea addresses_normal_ht+0x193d6, %rdi nop nop nop nop nop add %r12, %r12 mov $84, %rcx rep movsl nop nop nop nop nop sub %rsi, %rsi lea addresses_D_ht+0x108a4, %rcx nop nop nop nop nop inc %r12 movw $0x6162, (%rcx) nop nop nop nop nop inc %r13 lea addresses_WC_ht+0x7c4, %r13 nop nop nop lfence mov (%r13), %r15 inc %r8 pop %rsi pop %rdi pop %rcx pop %r8 pop %r15 pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r9 push %rax push %rcx push %rsi // Store lea addresses_PSE+0x169c4, %rcx nop nop nop nop nop xor $55847, %r13 mov $0x5152535455565758, %r9 movq %r9, %xmm7 movntdq %xmm7, (%rcx) nop xor %rsi, %rsi // Store lea addresses_normal+0x777e, %rax nop nop add $24337, %r12 movb $0x51, (%rax) nop nop nop and %rax, %rax // Faulty Load lea addresses_A+0x3dc4, %r13 nop nop nop and %r9, %r9 mov (%r13), %r11d lea oracles, %rcx and $0xff, %r11 shlq $12, %r11 mov (%rcx,%r11,1), %r11 pop %rsi pop %rcx pop %rax pop %r9 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'AVXalign': True, 'size': 2, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 16, 'NT': True, 'same': False, 'congruent': 7}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'size': 1, 'NT': True, 'same': False, 'congruent': 1}} [Faulty Load] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 4, 'NT': True, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 3}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}} {'src': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 0}} {'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 7}} {'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4, 'NT': True, 'same': False, 'congruent': 2}} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2, 'NT': True, 'same': False, 'congruent': 3}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 5}} {'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'00': 4} 00 00 00 00 */
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: BeatmapDifficultyMask #include "GlobalNamespace/BeatmapDifficultyMask.hpp" // Including type: GameplayModifierMask #include "GlobalNamespace/GameplayModifierMask.hpp" // Including type: SongPackMask #include "GlobalNamespace/SongPackMask.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: namespace GlobalNamespace { // Forward declaring type: GameServersFilter class GameServersFilter; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(GlobalNamespace::GameServersFilter); DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::GameServersFilter*, "", "GameServersFilter"); // Type namespace: namespace GlobalNamespace { // Size: 0x2B #pragma pack(push, 1) // Autogenerated type: GameServersFilter // [TokenAttribute] Offset: FFFFFFFF class GameServersFilter : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // public System.Boolean filterByDifficulty // Size: 0x1 // Offset: 0x10 bool filterByDifficulty; // Field size check static_assert(sizeof(bool) == 0x1); // public BeatmapDifficultyMask filteredDifficulty // Size: 0x1 // Offset: 0x11 GlobalNamespace::BeatmapDifficultyMask filteredDifficulty; // Field size check static_assert(sizeof(GlobalNamespace::BeatmapDifficultyMask) == 0x1); // public System.Boolean filterByModifiers // Size: 0x1 // Offset: 0x12 bool filterByModifiers; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: filterByModifiers and: filteredModifiers char __padding2[0x1] = {}; // public GameplayModifierMask filteredModifiers // Size: 0x2 // Offset: 0x14 GlobalNamespace::GameplayModifierMask filteredModifiers; // Field size check static_assert(sizeof(GlobalNamespace::GameplayModifierMask) == 0x2); // public System.Boolean filterBySongPacks // Size: 0x1 // Offset: 0x16 bool filterBySongPacks; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: filterBySongPacks and: filteredSongPacks char __padding4[0x1] = {}; // public SongPackMask filteredSongPacks // Size: 0x10 // Offset: 0x18 GlobalNamespace::SongPackMask filteredSongPacks; // Field size check static_assert(sizeof(GlobalNamespace::SongPackMask) == 0x10); // public System.Boolean showFull // Size: 0x1 // Offset: 0x28 bool showFull; // Field size check static_assert(sizeof(bool) == 0x1); // public System.Boolean showProtected // Size: 0x1 // Offset: 0x29 bool showProtected; // Field size check static_assert(sizeof(bool) == 0x1); // public System.Boolean showInternetGames // Size: 0x1 // Offset: 0x2A bool showInternetGames; // Field size check static_assert(sizeof(bool) == 0x1); public: // Get instance field reference: public System.Boolean filterByDifficulty bool& dyn_filterByDifficulty(); // Get instance field reference: public BeatmapDifficultyMask filteredDifficulty GlobalNamespace::BeatmapDifficultyMask& dyn_filteredDifficulty(); // Get instance field reference: public System.Boolean filterByModifiers bool& dyn_filterByModifiers(); // Get instance field reference: public GameplayModifierMask filteredModifiers GlobalNamespace::GameplayModifierMask& dyn_filteredModifiers(); // Get instance field reference: public System.Boolean filterBySongPacks bool& dyn_filterBySongPacks(); // Get instance field reference: public SongPackMask filteredSongPacks GlobalNamespace::SongPackMask& dyn_filteredSongPacks(); // Get instance field reference: public System.Boolean showFull bool& dyn_showFull(); // Get instance field reference: public System.Boolean showProtected bool& dyn_showProtected(); // Get instance field reference: public System.Boolean showInternetGames bool& dyn_showInternetGames(); // public System.Void .ctor() // Offset: 0x11B3ED8 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static GameServersFilter* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::GameServersFilter::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<GameServersFilter*, creationType>())); } }; // GameServersFilter #pragma pack(pop) static check_size<sizeof(GameServersFilter), 42 + sizeof(bool)> __GlobalNamespace_GameServersFilterSizeCheck; static_assert(sizeof(GameServersFilter) == 0x2B); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::GameServersFilter::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/window.h" #include "ui/display/manager/display_manager.h" #include "ui/display/scoped_display_for_new_windows.h" namespace ash { using ScreenAshTest = AshTestBase; // Tests that ScreenAsh::GetWindowAtScreenPoint() returns the correct window on // the correct display. TEST_F(ScreenAshTest, TestGetWindowAtScreenPoint) { UpdateDisplay("200x200,400x400"); aura::test::TestWindowDelegate delegate; std::unique_ptr<aura::Window> win1(CreateTestWindowInShellWithDelegate( &delegate, 0, gfx::Rect(0, 0, 200, 200))); std::unique_ptr<aura::Window> win2(CreateTestWindowInShellWithDelegate( &delegate, 1, gfx::Rect(200, 200, 100, 100))); ASSERT_NE(win1->GetRootWindow(), win2->GetRootWindow()); EXPECT_EQ(win1.get(), display::Screen::GetScreen()->GetWindowAtScreenPoint( gfx::Point(50, 60))); EXPECT_EQ(win2.get(), display::Screen::GetScreen()->GetWindowAtScreenPoint( gfx::Point(250, 260))); } TEST_F(ScreenAshTest, GetDisplayForNewWindows) { UpdateDisplay("200x200,400x400"); display::Screen* screen = display::Screen::GetScreen(); const std::vector<display::Display> displays = screen->GetAllDisplays(); ASSERT_EQ(2u, displays.size()); // The display for new windows defaults to primary display. EXPECT_EQ(displays[0].id(), screen->GetDisplayForNewWindows().id()); // The display for new windows is updated when the root window for new windows // changes. display::ScopedDisplayForNewWindows scoped_display( Shell::GetAllRootWindows()[1]); EXPECT_EQ(displays[1].id(), screen->GetDisplayForNewWindows().id()); } namespace { // Simulates an observer that tries to get the primary display when notified of // displays addition or removal when switching to or from the Unified Desktop // mode. class TestDisplayRemoveObserver : public display::DisplayObserver { public: TestDisplayRemoveObserver() = default; ~TestDisplayRemoveObserver() override = default; int added_displays() const { return added_displays_; } int removed_displays() const { return removed_displays_; } // display::DisplayObserver: void OnDisplayAdded(const display::Display& new_display) override { TestPrimaryDisplay(); ++added_displays_; } void OnDisplayRemoved(const display::Display& old_display) override { TestPrimaryDisplay(); ++removed_displays_; } private: void TestPrimaryDisplay() const { auto display = display::Screen::GetScreen()->GetPrimaryDisplay(); DCHECK_NE(display.id(), display::kInvalidDisplayId); } int added_displays_ = 0; int removed_displays_ = 0; DISALLOW_COPY_AND_ASSIGN(TestDisplayRemoveObserver); }; } // namespace // Switching to Unified Desktop removes all current displays (including primary // display) and replaces them with the unified display. The display manager // notifies observers of display removals before display additions. At this // point if an observer tries to get the primary display, it could lead to a // crash because all displays have been removed. This test makes sure doesn't // happen anymore. https://crbug.com/866714. TEST_F(ScreenAshTest, TestNoCrashesOnGettingPrimaryDisplayOnDisplayRemoved) { UpdateDisplay("400x500,300x200"); TestDisplayRemoveObserver observer; display_manager()->AddObserver(&observer); // Enter Unified Mode. display_manager()->SetUnifiedDesktopEnabled(true); EXPECT_TRUE(display_manager()->IsInUnifiedMode()); EXPECT_EQ(observer.added_displays(), 1); EXPECT_EQ(observer.removed_displays(), 2); // Exit Unified Mode, there shouldn't be any crashes either. display_manager()->SetUnifiedDesktopEnabled(false); EXPECT_FALSE(display_manager()->IsInUnifiedMode()); EXPECT_EQ(observer.added_displays(), 3); EXPECT_EQ(observer.removed_displays(), 3); display_manager()->RemoveObserver(&observer); } } // namespace ash
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node.h" #include "node_buffer.h" #include "node_constants.h" #include "node_file.h" #include "node_http_parser.h" #include "node_javascript.h" #include "node_version.h" #if defined HAVE_PERFCTR #include "node_counters.h" #endif #if HAVE_OPENSSL #include "node_crypto.h" #endif #if defined HAVE_DTRACE || defined HAVE_ETW #include "node_dtrace.h" #endif #include "ares.h" #include "async-wrap.h" #include "async-wrap-inl.h" #include "env.h" #include "env-inl.h" #include "handle_wrap.h" #include "req_wrap.h" #include "string_bytes.h" #include "uv.h" #include "v8-debug.h" #include "v8-profiler.h" #include "zlib.h" #include <assert.h> #include <errno.h> #include <limits.h> // PATH_MAX #include <locale.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #if defined(_MSC_VER) #include <direct.h> #include <io.h> #include <process.h> #define strcasecmp _stricmp #define getpid _getpid #define umask _umask typedef int mode_t; #else #include <sys/resource.h> // getrlimit, setrlimit #include <unistd.h> // setuid, getuid #endif #if defined(__POSIX__) && !defined(__ANDROID__) #include <pwd.h> // getpwnam() #include <grp.h> // getgrnam() #endif #ifdef __APPLE__ #include <crt_externs.h> #define environ (*_NSGetEnviron()) #elif !defined(_MSC_VER) extern char **environ; #endif namespace node { using v8::Array; using v8::ArrayBuffer; using v8::Boolean; using v8::Context; using v8::EscapableHandleScope; using v8::Exception; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Handle; using v8::HandleScope; using v8::HeapStatistics; using v8::Integer; using v8::Isolate; using v8::Local; using v8::Locker; using v8::Message; using v8::Number; using v8::Object; using v8::ObjectTemplate; using v8::PropertyCallbackInfo; using v8::String; using v8::TryCatch; using v8::Uint32; using v8::V8; using v8::Value; using v8::kExternalUnsignedIntArray; // FIXME(bnoordhuis) Make these per-context? QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue }; QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue }; static bool print_eval = false; static bool force_repl = false; static bool trace_deprecation = false; static bool throw_deprecation = false; static const char* eval_string = NULL; static bool use_debug_agent = false; static bool debug_wait_connect = false; static int debug_port = 5858; static bool v8_is_profiling = false; static node_module* modpending; static node_module* modlist_builtin; static node_module* modlist_addon; // used by C++ modules as well bool no_deprecation = false; // process-relative uptime base, initialized at start-up static double prog_start_time; static bool debugger_running; static uv_async_t dispatch_debug_messages_async; static Isolate* node_isolate = NULL; class ArrayBufferAllocator : public ArrayBuffer::Allocator { public: // Impose an upper limit to avoid out of memory errors that bring down // the process. static const size_t kMaxLength = 0x3fffffff; static ArrayBufferAllocator the_singleton; virtual ~ArrayBufferAllocator() {} virtual void* Allocate(size_t length); virtual void* AllocateUninitialized(size_t length); virtual void Free(void* data, size_t length); private: ArrayBufferAllocator() {} ArrayBufferAllocator(const ArrayBufferAllocator&); void operator=(const ArrayBufferAllocator&); }; ArrayBufferAllocator ArrayBufferAllocator::the_singleton; void* ArrayBufferAllocator::Allocate(size_t length) { if (length > kMaxLength) return NULL; char* data = new char[length]; memset(data, 0, length); return data; } void* ArrayBufferAllocator::AllocateUninitialized(size_t length) { if (length > kMaxLength) return NULL; return new char[length]; } void ArrayBufferAllocator::Free(void* data, size_t length) { delete[] static_cast<char*>(data); } static void CheckImmediate(uv_check_t* handle) { Environment* env = Environment::from_immediate_check_handle(handle); HandleScope scope(env->isolate()); Context::Scope context_scope(env->context()); MakeCallback(env, env->process_object(), env->immediate_callback_string()); } static void IdleImmediateDummy(uv_idle_t* handle) { // Do nothing. Only for maintaining event loop. // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks. } static inline const char *errno_string(int errorno) { #define ERRNO_CASE(e) case e: return #e; switch (errorno) { #ifdef EACCES ERRNO_CASE(EACCES); #endif #ifdef EADDRINUSE ERRNO_CASE(EADDRINUSE); #endif #ifdef EADDRNOTAVAIL ERRNO_CASE(EADDRNOTAVAIL); #endif #ifdef EAFNOSUPPORT ERRNO_CASE(EAFNOSUPPORT); #endif #ifdef EAGAIN ERRNO_CASE(EAGAIN); #endif #ifdef EWOULDBLOCK # if EAGAIN != EWOULDBLOCK ERRNO_CASE(EWOULDBLOCK); # endif #endif #ifdef EALREADY ERRNO_CASE(EALREADY); #endif #ifdef EBADF ERRNO_CASE(EBADF); #endif #ifdef EBADMSG ERRNO_CASE(EBADMSG); #endif #ifdef EBUSY ERRNO_CASE(EBUSY); #endif #ifdef ECANCELED ERRNO_CASE(ECANCELED); #endif #ifdef ECHILD ERRNO_CASE(ECHILD); #endif #ifdef ECONNABORTED ERRNO_CASE(ECONNABORTED); #endif #ifdef ECONNREFUSED ERRNO_CASE(ECONNREFUSED); #endif #ifdef ECONNRESET ERRNO_CASE(ECONNRESET); #endif #ifdef EDEADLK ERRNO_CASE(EDEADLK); #endif #ifdef EDESTADDRREQ ERRNO_CASE(EDESTADDRREQ); #endif #ifdef EDOM ERRNO_CASE(EDOM); #endif #ifdef EDQUOT ERRNO_CASE(EDQUOT); #endif #ifdef EEXIST ERRNO_CASE(EEXIST); #endif #ifdef EFAULT ERRNO_CASE(EFAULT); #endif #ifdef EFBIG ERRNO_CASE(EFBIG); #endif #ifdef EHOSTUNREACH ERRNO_CASE(EHOSTUNREACH); #endif #ifdef EIDRM ERRNO_CASE(EIDRM); #endif #ifdef EILSEQ ERRNO_CASE(EILSEQ); #endif #ifdef EINPROGRESS ERRNO_CASE(EINPROGRESS); #endif #ifdef EINTR ERRNO_CASE(EINTR); #endif #ifdef EINVAL ERRNO_CASE(EINVAL); #endif #ifdef EIO ERRNO_CASE(EIO); #endif #ifdef EISCONN ERRNO_CASE(EISCONN); #endif #ifdef EISDIR ERRNO_CASE(EISDIR); #endif #ifdef ELOOP ERRNO_CASE(ELOOP); #endif #ifdef EMFILE ERRNO_CASE(EMFILE); #endif #ifdef EMLINK ERRNO_CASE(EMLINK); #endif #ifdef EMSGSIZE ERRNO_CASE(EMSGSIZE); #endif #ifdef EMULTIHOP ERRNO_CASE(EMULTIHOP); #endif #ifdef ENAMETOOLONG ERRNO_CASE(ENAMETOOLONG); #endif #ifdef ENETDOWN ERRNO_CASE(ENETDOWN); #endif #ifdef ENETRESET ERRNO_CASE(ENETRESET); #endif #ifdef ENETUNREACH ERRNO_CASE(ENETUNREACH); #endif #ifdef ENFILE ERRNO_CASE(ENFILE); #endif #ifdef ENOBUFS ERRNO_CASE(ENOBUFS); #endif #ifdef ENODATA ERRNO_CASE(ENODATA); #endif #ifdef ENODEV ERRNO_CASE(ENODEV); #endif #ifdef ENOENT ERRNO_CASE(ENOENT); #endif #ifdef ENOEXEC ERRNO_CASE(ENOEXEC); #endif #ifdef ENOLINK ERRNO_CASE(ENOLINK); #endif #ifdef ENOLCK # if ENOLINK != ENOLCK ERRNO_CASE(ENOLCK); # endif #endif #ifdef ENOMEM ERRNO_CASE(ENOMEM); #endif #ifdef ENOMSG ERRNO_CASE(ENOMSG); #endif #ifdef ENOPROTOOPT ERRNO_CASE(ENOPROTOOPT); #endif #ifdef ENOSPC ERRNO_CASE(ENOSPC); #endif #ifdef ENOSR ERRNO_CASE(ENOSR); #endif #ifdef ENOSTR ERRNO_CASE(ENOSTR); #endif #ifdef ENOSYS ERRNO_CASE(ENOSYS); #endif #ifdef ENOTCONN ERRNO_CASE(ENOTCONN); #endif #ifdef ENOTDIR ERRNO_CASE(ENOTDIR); #endif #ifdef ENOTEMPTY ERRNO_CASE(ENOTEMPTY); #endif #ifdef ENOTSOCK ERRNO_CASE(ENOTSOCK); #endif #ifdef ENOTSUP ERRNO_CASE(ENOTSUP); #else # ifdef EOPNOTSUPP ERRNO_CASE(EOPNOTSUPP); # endif #endif #ifdef ENOTTY ERRNO_CASE(ENOTTY); #endif #ifdef ENXIO ERRNO_CASE(ENXIO); #endif #ifdef EOVERFLOW ERRNO_CASE(EOVERFLOW); #endif #ifdef EPERM ERRNO_CASE(EPERM); #endif #ifdef EPIPE ERRNO_CASE(EPIPE); #endif #ifdef EPROTO ERRNO_CASE(EPROTO); #endif #ifdef EPROTONOSUPPORT ERRNO_CASE(EPROTONOSUPPORT); #endif #ifdef EPROTOTYPE ERRNO_CASE(EPROTOTYPE); #endif #ifdef ERANGE ERRNO_CASE(ERANGE); #endif #ifdef EROFS ERRNO_CASE(EROFS); #endif #ifdef ESPIPE ERRNO_CASE(ESPIPE); #endif #ifdef ESRCH ERRNO_CASE(ESRCH); #endif #ifdef ESTALE ERRNO_CASE(ESTALE); #endif #ifdef ETIME ERRNO_CASE(ETIME); #endif #ifdef ETIMEDOUT ERRNO_CASE(ETIMEDOUT); #endif #ifdef ETXTBSY ERRNO_CASE(ETXTBSY); #endif #ifdef EXDEV ERRNO_CASE(EXDEV); #endif default: return ""; } } const char *signo_string(int signo) { #define SIGNO_CASE(e) case e: return #e; switch (signo) { #ifdef SIGHUP SIGNO_CASE(SIGHUP); #endif #ifdef SIGINT SIGNO_CASE(SIGINT); #endif #ifdef SIGQUIT SIGNO_CASE(SIGQUIT); #endif #ifdef SIGILL SIGNO_CASE(SIGILL); #endif #ifdef SIGTRAP SIGNO_CASE(SIGTRAP); #endif #ifdef SIGABRT SIGNO_CASE(SIGABRT); #endif #ifdef SIGIOT # if SIGABRT != SIGIOT SIGNO_CASE(SIGIOT); # endif #endif #ifdef SIGBUS SIGNO_CASE(SIGBUS); #endif #ifdef SIGFPE SIGNO_CASE(SIGFPE); #endif #ifdef SIGKILL SIGNO_CASE(SIGKILL); #endif #ifdef SIGUSR1 SIGNO_CASE(SIGUSR1); #endif #ifdef SIGSEGV SIGNO_CASE(SIGSEGV); #endif #ifdef SIGUSR2 SIGNO_CASE(SIGUSR2); #endif #ifdef SIGPIPE SIGNO_CASE(SIGPIPE); #endif #ifdef SIGALRM SIGNO_CASE(SIGALRM); #endif SIGNO_CASE(SIGTERM); #ifdef SIGCHLD SIGNO_CASE(SIGCHLD); #endif #ifdef SIGSTKFLT SIGNO_CASE(SIGSTKFLT); #endif #ifdef SIGCONT SIGNO_CASE(SIGCONT); #endif #ifdef SIGSTOP SIGNO_CASE(SIGSTOP); #endif #ifdef SIGTSTP SIGNO_CASE(SIGTSTP); #endif #ifdef SIGBREAK SIGNO_CASE(SIGBREAK); #endif #ifdef SIGTTIN SIGNO_CASE(SIGTTIN); #endif #ifdef SIGTTOU SIGNO_CASE(SIGTTOU); #endif #ifdef SIGURG SIGNO_CASE(SIGURG); #endif #ifdef SIGXCPU SIGNO_CASE(SIGXCPU); #endif #ifdef SIGXFSZ SIGNO_CASE(SIGXFSZ); #endif #ifdef SIGVTALRM SIGNO_CASE(SIGVTALRM); #endif #ifdef SIGPROF SIGNO_CASE(SIGPROF); #endif #ifdef SIGWINCH SIGNO_CASE(SIGWINCH); #endif #ifdef SIGIO SIGNO_CASE(SIGIO); #endif #ifdef SIGPOLL # if SIGPOLL != SIGIO SIGNO_CASE(SIGPOLL); # endif #endif #ifdef SIGLOST SIGNO_CASE(SIGLOST); #endif #ifdef SIGPWR # if SIGPWR != SIGLOST SIGNO_CASE(SIGPWR); # endif #endif #ifdef SIGSYS SIGNO_CASE(SIGSYS); #endif default: return ""; } } // Convenience methods void ThrowError(v8::Isolate* isolate, const char* errmsg) { Environment::GetCurrent(isolate)->ThrowError(errmsg); } void ThrowTypeError(v8::Isolate* isolate, const char* errmsg) { Environment::GetCurrent(isolate)->ThrowTypeError(errmsg); } void ThrowRangeError(v8::Isolate* isolate, const char* errmsg) { Environment::GetCurrent(isolate)->ThrowRangeError(errmsg); } void ThrowErrnoException(v8::Isolate* isolate, int errorno, const char* syscall, const char* message, const char* path) { Environment::GetCurrent(isolate)->ThrowErrnoException(errorno, syscall, message, path); } void ThrowUVException(v8::Isolate* isolate, int errorno, const char* syscall, const char* message, const char* path) { Environment::GetCurrent(isolate)->ThrowErrnoException(errorno, syscall, message, path); } Local<Value> ErrnoException(Isolate* isolate, int errorno, const char *syscall, const char *msg, const char *path) { Environment* env = Environment::GetCurrent(isolate); Local<Value> e; Local<String> estring = OneByteString(env->isolate(), errno_string(errorno)); if (msg == NULL || msg[0] == '\0') { msg = strerror(errorno); } Local<String> message = OneByteString(env->isolate(), msg); Local<String> cons1 = String::Concat(estring, FIXED_ONE_BYTE_STRING(env->isolate(), ", ")); Local<String> cons2 = String::Concat(cons1, message); if (path) { Local<String> cons3 = String::Concat(cons2, FIXED_ONE_BYTE_STRING(env->isolate(), " '")); Local<String> cons4 = String::Concat(cons3, String::NewFromUtf8(env->isolate(), path)); Local<String> cons5 = String::Concat(cons4, FIXED_ONE_BYTE_STRING(env->isolate(), "'")); e = Exception::Error(cons5); } else { e = Exception::Error(cons2); } Local<Object> obj = e->ToObject(); obj->Set(env->errno_string(), Integer::New(env->isolate(), errorno)); obj->Set(env->code_string(), estring); if (path != NULL) { obj->Set(env->path_string(), String::NewFromUtf8(env->isolate(), path)); } if (syscall != NULL) { obj->Set(env->syscall_string(), OneByteString(env->isolate(), syscall)); } return e; } // hack alert! copy of ErrnoException, tuned for uv errors Local<Value> UVException(Isolate* isolate, int errorno, const char *syscall, const char *msg, const char *path) { Environment* env = Environment::GetCurrent(isolate); if (!msg || !msg[0]) msg = uv_strerror(errorno); Local<String> estring = OneByteString(env->isolate(), uv_err_name(errorno)); Local<String> message = OneByteString(env->isolate(), msg); Local<String> cons1 = String::Concat(estring, FIXED_ONE_BYTE_STRING(env->isolate(), ", ")); Local<String> cons2 = String::Concat(cons1, message); Local<Value> e; Local<String> path_str; if (path) { #ifdef _WIN32 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) { path_str = String::Concat(FIXED_ONE_BYTE_STRING(env->isolate(), "\\\\"), String::NewFromUtf8(env->isolate(), path + 8)); } else if (strncmp(path, "\\\\?\\", 4) == 0) { path_str = String::NewFromUtf8(env->isolate(), path + 4); } else { path_str = String::NewFromUtf8(env->isolate(), path); } #else path_str = String::NewFromUtf8(env->isolate(), path); #endif Local<String> cons3 = String::Concat(cons2, FIXED_ONE_BYTE_STRING(env->isolate(), " '")); Local<String> cons4 = String::Concat(cons3, path_str); Local<String> cons5 = String::Concat(cons4, FIXED_ONE_BYTE_STRING(env->isolate(), "'")); e = Exception::Error(cons5); } else { e = Exception::Error(cons2); } Local<Object> obj = e->ToObject(); // TODO(piscisaureus) errno should probably go obj->Set(env->errno_string(), Integer::New(env->isolate(), errorno)); obj->Set(env->code_string(), estring); if (path != NULL) { obj->Set(env->path_string(), path_str); } if (syscall != NULL) { obj->Set(env->syscall_string(), OneByteString(env->isolate(), syscall)); } return e; } #ifdef _WIN32 // Does about the same as strerror(), // but supports all windows error messages static const char *winapi_strerror(const int errorno) { char *errmsg = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL); if (errmsg) { // Remove trailing newlines for (int i = strlen(errmsg) - 1; i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) { errmsg[i] = '\0'; } return errmsg; } else { // FormatMessage failed return "Unknown error"; } } Local<Value> WinapiErrnoException(Isolate* isolate, int errorno, const char* syscall, const char* msg, const char* path) { Environment* env = Environment::GetCurrent(isolate); Local<Value> e; if (!msg || !msg[0]) { msg = winapi_strerror(errorno); } Local<String> message = OneByteString(env->isolate(), msg); if (path) { Local<String> cons1 = String::Concat(message, FIXED_ONE_BYTE_STRING(isolate, " '")); Local<String> cons2 = String::Concat(cons1, String::NewFromUtf8(isolate, path)); Local<String> cons3 = String::Concat(cons2, FIXED_ONE_BYTE_STRING(isolate, "'")); e = Exception::Error(cons3); } else { e = Exception::Error(message); } Local<Object> obj = e->ToObject(); obj->Set(env->errno_string(), Integer::New(isolate, errorno)); if (path != NULL) { obj->Set(env->path_string(), String::NewFromUtf8(isolate, path)); } if (syscall != NULL) { obj->Set(env->syscall_string(), OneByteString(isolate, syscall)); } return e; } #endif void SetupAsyncListener(const FunctionCallbackInfo<Value>& args) { HandleScope handle_scope(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate()); assert(args[0]->IsObject()); assert(args[1]->IsFunction()); assert(args[2]->IsFunction()); assert(args[3]->IsFunction()); env->set_async_listener_run_function(args[1].As<Function>()); env->set_async_listener_load_function(args[2].As<Function>()); env->set_async_listener_unload_function(args[3].As<Function>()); Local<Object> async_listener_flag_obj = args[0].As<Object>(); Environment::AsyncListener* async_listener = env->async_listener(); async_listener_flag_obj->SetIndexedPropertiesToExternalArrayData( async_listener->fields(), kExternalUnsignedIntArray, async_listener->fields_count()); // Do a little housekeeping. env->process_object()->Delete( FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupAsyncListener")); } void SetupDomainUse(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); if (env->using_domains()) return; env->set_using_domains(true); HandleScope scope(env->isolate()); Local<Object> process_object = env->process_object(); Local<String> tick_callback_function_key = env->tick_domain_cb_string(); Local<Function> tick_callback_function = process_object->Get(tick_callback_function_key).As<Function>(); if (!tick_callback_function->IsFunction()) { fprintf(stderr, "process._tickDomainCallback assigned to non-function\n"); abort(); } process_object->Set(env->tick_callback_string(), tick_callback_function); env->set_tick_callback_function(tick_callback_function); assert(args[0]->IsArray()); assert(args[1]->IsObject()); env->set_domain_array(args[0].As<Array>()); Local<Object> domain_flag_obj = args[1].As<Object>(); Environment::DomainFlag* domain_flag = env->domain_flag(); domain_flag_obj->SetIndexedPropertiesToExternalArrayData( domain_flag->fields(), kExternalUnsignedIntArray, domain_flag->fields_count()); // Do a little housekeeping. env->process_object()->Delete( FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupDomainUse")); } void SetupNextTick(const FunctionCallbackInfo<Value>& args) { HandleScope handle_scope(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate()); assert(args[0]->IsObject()); assert(args[1]->IsFunction()); // Values use to cross communicate with processNextTick. Local<Object> tick_info_obj = args[0].As<Object>(); tick_info_obj->SetIndexedPropertiesToExternalArrayData( env->tick_info()->fields(), kExternalUnsignedIntArray, env->tick_info()->fields_count()); env->set_tick_callback_function(args[1].As<Function>()); // Do a little housekeeping. env->process_object()->Delete( FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupNextTick")); } Handle<Value> MakeDomainCallback(Environment* env, Handle<Value> recv, const Handle<Function> callback, int argc, Handle<Value> argv[]) { // If you hit this assertion, you forgot to enter the v8::Context first. assert(env->context() == env->isolate()->GetCurrentContext()); Local<Object> process = env->process_object(); Local<Object> object, domain; Local<Value> domain_v; TryCatch try_catch; try_catch.SetVerbose(true); bool has_async_queue = false; if (recv->IsObject()) { object = recv.As<Object>(); // TODO(trevnorris): This is sucky for performance. Fix it. has_async_queue = object->Has(env->async_queue_string()); if (has_async_queue) { env->async_listener_load_function()->Call(process, 1, &recv); if (try_catch.HasCaught()) return Undefined(env->isolate()); } } bool has_domain = false; if (!object.IsEmpty()) { domain_v = object->Get(env->domain_string()); has_domain = domain_v->IsObject(); if (has_domain) { domain = domain_v.As<Object>(); if (domain->Get(env->disposed_string())->IsTrue()) { // domain has been disposed of. return Undefined(env->isolate()); } Local<Function> enter = domain->Get(env->enter_string()).As<Function>(); assert(enter->IsFunction()); enter->Call(domain, 0, NULL); if (try_catch.HasCaught()) { return Undefined(env->isolate()); } } } Local<Value> ret = callback->Call(recv, argc, argv); if (try_catch.HasCaught()) { return Undefined(env->isolate()); } if (has_domain) { Local<Function> exit = domain->Get(env->exit_string()).As<Function>(); assert(exit->IsFunction()); exit->Call(domain, 0, NULL); if (try_catch.HasCaught()) { return Undefined(env->isolate()); } } if (has_async_queue) { env->async_listener_unload_function()->Call(process, 1, &recv); if (try_catch.HasCaught()) return Undefined(env->isolate()); } Environment::TickInfo* tick_info = env->tick_info(); if (tick_info->last_threw() == 1) { tick_info->set_last_threw(0); return ret; } if (tick_info->in_tick()) { return ret; } if (tick_info->length() == 0) { tick_info->set_index(0); return ret; } tick_info->set_in_tick(true); env->tick_callback_function()->Call(process, 0, NULL); tick_info->set_in_tick(false); if (try_catch.HasCaught()) { tick_info->set_last_threw(true); return Undefined(env->isolate()); } return ret; } Handle<Value> MakeCallback(Environment* env, Handle<Value> recv, const Handle<Function> callback, int argc, Handle<Value> argv[]) { if (env->using_domains()) return MakeDomainCallback(env, recv, callback, argc, argv); // If you hit this assertion, you forgot to enter the v8::Context first. assert(env->context() == env->isolate()->GetCurrentContext()); Local<Object> process = env->process_object(); TryCatch try_catch; try_catch.SetVerbose(true); // TODO(trevnorris): This is sucky for performance. Fix it. bool has_async_queue = recv->IsObject() && recv.As<Object>()->Has(env->async_queue_string()); if (has_async_queue) { env->async_listener_load_function()->Call(process, 1, &recv); if (try_catch.HasCaught()) return Undefined(env->isolate()); } Local<Value> ret = callback->Call(recv, argc, argv); if (try_catch.HasCaught()) { return Undefined(env->isolate()); } if (has_async_queue) { env->async_listener_unload_function()->Call(process, 1, &recv); if (try_catch.HasCaught()) return Undefined(env->isolate()); } Environment::TickInfo* tick_info = env->tick_info(); if (tick_info->in_tick()) { return ret; } if (tick_info->length() == 0) { tick_info->set_index(0); return ret; } tick_info->set_in_tick(true); // process nextTicks after call env->tick_callback_function()->Call(process, 0, NULL); tick_info->set_in_tick(false); if (try_catch.HasCaught()) { tick_info->set_last_threw(true); return Undefined(env->isolate()); } return ret; } // Internal only. Handle<Value> MakeCallback(Environment* env, Handle<Object> recv, uint32_t index, int argc, Handle<Value> argv[]) { Local<Function> callback = recv->Get(index).As<Function>(); assert(callback->IsFunction()); return MakeCallback(env, recv.As<Value>(), callback, argc, argv); } Handle<Value> MakeCallback(Environment* env, Handle<Object> recv, Handle<String> symbol, int argc, Handle<Value> argv[]) { Local<Function> callback = recv->Get(symbol).As<Function>(); assert(callback->IsFunction()); return MakeCallback(env, recv.As<Value>(), callback, argc, argv); } Handle<Value> MakeCallback(Environment* env, Handle<Object> recv, const char* method, int argc, Handle<Value> argv[]) { Local<String> method_string = OneByteString(env->isolate(), method); return MakeCallback(env, recv, method_string, argc, argv); } Handle<Value> MakeCallback(Isolate* isolate, Handle<Object> recv, const char* method, int argc, Handle<Value> argv[]) { EscapableHandleScope handle_scope(isolate); Local<Context> context = recv->CreationContext(); Environment* env = Environment::GetCurrent(context); Context::Scope context_scope(context); return handle_scope.Escape( Local<Value>::New(isolate, MakeCallback(env, recv, method, argc, argv))); } Handle<Value> MakeCallback(Isolate* isolate, Handle<Object> recv, Handle<String> symbol, int argc, Handle<Value> argv[]) { EscapableHandleScope handle_scope(isolate); Local<Context> context = recv->CreationContext(); Environment* env = Environment::GetCurrent(context); Context::Scope context_scope(context); return handle_scope.Escape( Local<Value>::New(isolate, MakeCallback(env, recv, symbol, argc, argv))); } Handle<Value> MakeCallback(Isolate* isolate, Handle<Object> recv, Handle<Function> callback, int argc, Handle<Value> argv[]) { EscapableHandleScope handle_scope(isolate); Local<Context> context = recv->CreationContext(); Environment* env = Environment::GetCurrent(context); Context::Scope context_scope(context); return handle_scope.Escape(Local<Value>::New( isolate, MakeCallback(env, recv.As<Value>(), callback, argc, argv))); } Handle<Value> MakeDomainCallback(Handle<Object> recv, Handle<Function> callback, int argc, Handle<Value> argv[]) { Local<Context> context = recv->CreationContext(); Environment* env = Environment::GetCurrent(context); Context::Scope context_scope(context); EscapableHandleScope handle_scope(env->isolate()); return handle_scope.Escape(Local<Value>::New( env->isolate(), MakeDomainCallback(env, recv, callback, argc, argv))); } enum encoding ParseEncoding(Isolate* isolate, Handle<Value> encoding_v, enum encoding _default) { HandleScope scope(isolate); if (!encoding_v->IsString()) return _default; String::Utf8Value encoding(encoding_v); if (strcasecmp(*encoding, "utf8") == 0) { return UTF8; } else if (strcasecmp(*encoding, "utf-8") == 0) { return UTF8; } else if (strcasecmp(*encoding, "ascii") == 0) { return ASCII; } else if (strcasecmp(*encoding, "base64") == 0) { return BASE64; } else if (strcasecmp(*encoding, "ucs2") == 0) { return UCS2; } else if (strcasecmp(*encoding, "ucs-2") == 0) { return UCS2; } else if (strcasecmp(*encoding, "utf16le") == 0) { return UCS2; } else if (strcasecmp(*encoding, "utf-16le") == 0) { return UCS2; } else if (strcasecmp(*encoding, "binary") == 0) { return BINARY; } else if (strcasecmp(*encoding, "buffer") == 0) { return BUFFER; } else if (strcasecmp(*encoding, "hex") == 0) { return HEX; } else if (strcasecmp(*encoding, "raw") == 0) { if (!no_deprecation) { fprintf(stderr, "'raw' (array of integers) has been removed. " "Use 'binary'.\n"); } return BINARY; } else if (strcasecmp(*encoding, "raws") == 0) { if (!no_deprecation) { fprintf(stderr, "'raws' encoding has been renamed to 'binary'. " "Please update your code.\n"); } return BINARY; } else { return _default; } } Local<Value> Encode(Isolate* isolate, const void* buf, size_t len, enum encoding encoding) { return StringBytes::Encode(isolate, static_cast<const char*>(buf), len, encoding); } // Returns -1 if the handle was not valid for decoding ssize_t DecodeBytes(Isolate* isolate, Handle<Value> val, enum encoding encoding) { HandleScope scope(isolate); if (val->IsArray()) { fprintf(stderr, "'raw' encoding (array of integers) has been removed. " "Use 'binary'.\n"); assert(0); return -1; } return StringBytes::Size(isolate, val, encoding); } #ifndef MIN # define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif // Returns number of bytes written. ssize_t DecodeWrite(Isolate* isolate, char* buf, size_t buflen, Handle<Value> val, enum encoding encoding) { return StringBytes::Write(isolate, buf, buflen, val, encoding, NULL); } void AppendExceptionLine(Environment* env, Handle<Value> er, Handle<Message> message) { if (message.IsEmpty()) return; HandleScope scope(env->isolate()); Local<Object> err_obj; if (!er.IsEmpty() && er->IsObject()) { err_obj = er.As<Object>(); // Do it only once per message if (!err_obj->GetHiddenValue(env->processed_string()).IsEmpty()) return; err_obj->SetHiddenValue(env->processed_string(), True(env->isolate())); } static char arrow[1024]; // Print (filename):(line number): (message). String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = *filename; int linenum = message->GetLineNumber(); // Print line of source code. String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = *sourceline; // Because of how node modules work, all scripts are wrapped with a // "function (module, exports, __filename, ...) {" // to provide script local variables. // // When reporting errors on the first line of a script, this wrapper // function is leaked to the user. There used to be a hack here to // truncate off the first 62 characters, but it caused numerous other // problems when vm.runIn*Context() methods were used for non-module // code. // // If we ever decide to re-instate such a hack, the following steps // must be taken: // // 1. Pass a flag around to say "this code was wrapped" // 2. Update the stack frame output so that it is also correct. // // It would probably be simpler to add a line rather than add some // number of characters to the first line, since V8 truncates the // sourceline to 78 characters, and we end up not providing very much // useful debugging info to the user if we remove 62 characters. int start = message->GetStartColumn(); int end = message->GetEndColumn(); int off = snprintf(arrow, sizeof(arrow), "%s:%i\n%s\n", filename_string, linenum, sourceline_string); assert(off >= 0); // Print wavy underline (GetUnderline is deprecated). for (int i = 0; i < start; i++) { assert(static_cast<size_t>(off) < sizeof(arrow)); arrow[off++] = (sourceline_string[i] == '\t') ? '\t' : ' '; } for (int i = start; i < end; i++) { assert(static_cast<size_t>(off) < sizeof(arrow)); arrow[off++] = '^'; } assert(static_cast<size_t>(off) < sizeof(arrow) - 1); arrow[off++] = '\n'; arrow[off] = '\0'; Local<String> arrow_str = String::NewFromUtf8(env->isolate(), arrow); Local<Value> msg; Local<Value> stack; // Allocation failed, just print it out if (arrow_str.IsEmpty() || err_obj.IsEmpty() || !err_obj->IsNativeError()) goto print; msg = err_obj->Get(env->message_string()); stack = err_obj->Get(env->stack_string()); if (msg.IsEmpty() || stack.IsEmpty()) goto print; err_obj->Set(env->message_string(), String::Concat(arrow_str, msg->ToString())); err_obj->Set(env->stack_string(), String::Concat(arrow_str, stack->ToString())); return; print: if (env->printed_error()) return; env->set_printed_error(true); uv_tty_reset_mode(); fprintf(stderr, "\n%s", arrow); } static void ReportException(Environment* env, Handle<Value> er, Handle<Message> message) { HandleScope scope(env->isolate()); AppendExceptionLine(env, er, message); Local<Value> trace_value; if (er->IsUndefined() || er->IsNull()) trace_value = Undefined(env->isolate()); else trace_value = er->ToObject()->Get(env->stack_string()); String::Utf8Value trace(trace_value); // range errors have a trace member set to undefined if (trace.length() > 0 && !trace_value->IsUndefined()) { fprintf(stderr, "%s\n", *trace); } else { // this really only happens for RangeErrors, since they're the only // kind that won't have all this info in the trace, or when non-Error // objects are thrown manually. Local<Value> message; Local<Value> name; if (er->IsObject()) { Local<Object> err_obj = er.As<Object>(); message = err_obj->Get(env->message_string()); name = err_obj->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "name")); } if (message.IsEmpty() || message->IsUndefined() || name.IsEmpty() || name->IsUndefined()) { // Not an error object. Just print as-is. String::Utf8Value message(er); fprintf(stderr, "%s\n", *message); } else { String::Utf8Value name_string(name); String::Utf8Value message_string(message); fprintf(stderr, "%s: %s\n", *name_string, *message_string); } } fflush(stderr); } static void ReportException(Environment* env, const TryCatch& try_catch) { ReportException(env, try_catch.Exception(), try_catch.Message()); } // Executes a str within the current v8 context. static Local<Value> ExecuteString(Environment* env, Handle<String> source, Handle<String> filename) { EscapableHandleScope scope(env->isolate()); TryCatch try_catch; // try_catch must be nonverbose to disable FatalException() handler, // we will handle exceptions ourself. try_catch.SetVerbose(false); Local<v8::Script> script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(env, try_catch); exit(3); } Local<Value> result = script->Run(); if (result.IsEmpty()) { ReportException(env, try_catch); exit(4); } return scope.Escape(result); } static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) { HandleScope scope(args.GetIsolate()); Local<Array> ary = Array::New(args.GetIsolate()); QUEUE* q = NULL; int i = 0; QUEUE_FOREACH(q, &req_wrap_queue) { ReqWrap<uv_req_t>* w = CONTAINER_OF(q, ReqWrap<uv_req_t>, req_wrap_queue_); if (w->persistent().IsEmpty()) continue; ary->Set(i++, w->object()); } args.GetReturnValue().Set(ary); } // Non-static, friend of HandleWrap. Could have been a HandleWrap method but // implemented here for consistency with GetActiveRequests(). void GetActiveHandles(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); Local<Array> ary = Array::New(env->isolate()); QUEUE* q = NULL; int i = 0; Local<String> owner_sym = env->owner_string(); QUEUE_FOREACH(q, &handle_wrap_queue) { HandleWrap* w = CONTAINER_OF(q, HandleWrap, handle_wrap_queue_); if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue; Local<Object> object = w->object(); Local<Value> owner = object->Get(owner_sym); if (owner->IsUndefined()) owner = object; ary->Set(i++, owner); } args.GetReturnValue().Set(ary); } static void Abort(const FunctionCallbackInfo<Value>& args) { abort(); } static void Chdir(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); if (args.Length() != 1 || !args[0]->IsString()) { // FIXME(bnoordhuis) ThrowTypeError? return env->ThrowError("Bad argument."); } String::Utf8Value path(args[0]); int err = uv_chdir(*path); if (err) { return env->ThrowUVException(err, "uv_chdir"); } } static void Cwd(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); #ifdef _WIN32 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */ char buf[MAX_PATH * 4]; #else char buf[PATH_MAX]; #endif size_t cwd_len = sizeof(buf); int err = uv_cwd(buf, &cwd_len); if (err) { return env->ThrowUVException(err, "uv_cwd"); } Local<String> cwd = String::NewFromUtf8(env->isolate(), buf, String::kNormalString, cwd_len - 1); args.GetReturnValue().Set(cwd); } static void Umask(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); uint32_t old; if (args.Length() < 1 || args[0]->IsUndefined()) { old = umask(0); umask(static_cast<mode_t>(old)); } else if (!args[0]->IsInt32() && !args[0]->IsString()) { return env->ThrowTypeError("argument must be an integer or octal string."); } else { int oct; if (args[0]->IsInt32()) { oct = args[0]->Uint32Value(); } else { oct = 0; String::Utf8Value str(args[0]); // Parse the octal string. for (int i = 0; i < str.length(); i++) { char c = (*str)[i]; if (c > '7' || c < '0') { return env->ThrowTypeError("invalid octal string"); } oct *= 8; oct += c - '0'; } } old = umask(static_cast<mode_t>(oct)); } args.GetReturnValue().Set(old); } #if defined(__POSIX__) && !defined(__ANDROID__) static const uid_t uid_not_found = static_cast<uid_t>(-1); static const gid_t gid_not_found = static_cast<gid_t>(-1); static uid_t uid_by_name(const char* name) { struct passwd pwd; struct passwd* pp; char buf[8192]; errno = 0; pp = NULL; if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) { return pp->pw_uid; } return uid_not_found; } static char* name_by_uid(uid_t uid) { struct passwd pwd; struct passwd* pp; char buf[8192]; int rc; errno = 0; pp = NULL; if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) { return strdup(pp->pw_name); } if (rc == 0) { errno = ENOENT; } return NULL; } static gid_t gid_by_name(const char* name) { struct group pwd; struct group* pp; char buf[8192]; errno = 0; pp = NULL; if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) { return pp->gr_gid; } return gid_not_found; } #if 0 // For future use. static const char* name_by_gid(gid_t gid) { struct group pwd; struct group* pp; char buf[8192]; int rc; errno = 0; pp = NULL; if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) { return strdup(pp->gr_name); } if (rc == 0) { errno = ENOENT; } return NULL; } #endif static uid_t uid_by_name(Handle<Value> value) { if (value->IsUint32()) { return static_cast<uid_t>(value->Uint32Value()); } else { String::Utf8Value name(value); return uid_by_name(*name); } } static gid_t gid_by_name(Handle<Value> value) { if (value->IsUint32()) { return static_cast<gid_t>(value->Uint32Value()); } else { String::Utf8Value name(value); return gid_by_name(*name); } } static void GetUid(const FunctionCallbackInfo<Value>& args) { // uid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast<uint32_t>(getuid())); } static void GetGid(const FunctionCallbackInfo<Value>& args) { // gid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast<uint32_t>(getgid())); } static void SetGid(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); if (!args[0]->IsUint32() && !args[0]->IsString()) { return env->ThrowTypeError("setgid argument must be a number or a string"); } gid_t gid = gid_by_name(args[0]); if (gid == gid_not_found) { return env->ThrowError("setgid group id does not exist"); } if (setgid(gid)) { return env->ThrowErrnoException(errno, "setgid"); } } static void SetUid(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); if (!args[0]->IsUint32() && !args[0]->IsString()) { return env->ThrowTypeError("setuid argument must be a number or a string"); } uid_t uid = uid_by_name(args[0]); if (uid == uid_not_found) { return env->ThrowError("setuid user id does not exist"); } if (setuid(uid)) { return env->ThrowErrnoException(errno, "setuid"); } } static void GetGroups(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); int ngroups = getgroups(0, NULL); if (ngroups == -1) { return env->ThrowErrnoException(errno, "getgroups"); } gid_t* groups = new gid_t[ngroups]; ngroups = getgroups(ngroups, groups); if (ngroups == -1) { delete[] groups; return env->ThrowErrnoException(errno, "getgroups"); } Local<Array> groups_list = Array::New(env->isolate(), ngroups); bool seen_egid = false; gid_t egid = getegid(); for (int i = 0; i < ngroups; i++) { groups_list->Set(i, Integer::New(env->isolate(), groups[i])); if (groups[i] == egid) seen_egid = true; } delete[] groups; if (seen_egid == false) { groups_list->Set(ngroups, Integer::New(env->isolate(), egid)); } args.GetReturnValue().Set(groups_list); } static void SetGroups(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); if (!args[0]->IsArray()) { return env->ThrowTypeError("argument 1 must be an array"); } Local<Array> groups_list = args[0].As<Array>(); size_t size = groups_list->Length(); gid_t* groups = new gid_t[size]; for (size_t i = 0; i < size; i++) { gid_t gid = gid_by_name(groups_list->Get(i)); if (gid == gid_not_found) { delete[] groups; return env->ThrowError("group name not found"); } groups[i] = gid; } int rc = setgroups(size, groups); delete[] groups; if (rc == -1) { return env->ThrowErrnoException(errno, "setgroups"); } } static void InitGroups(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); if (!args[0]->IsUint32() && !args[0]->IsString()) { return env->ThrowTypeError("argument 1 must be a number or a string"); } if (!args[1]->IsUint32() && !args[1]->IsString()) { return env->ThrowTypeError("argument 2 must be a number or a string"); } String::Utf8Value arg0(args[0]); gid_t extra_group; bool must_free; char* user; if (args[0]->IsUint32()) { user = name_by_uid(args[0]->Uint32Value()); must_free = true; } else { user = *arg0; must_free = false; } if (user == NULL) { return env->ThrowError("initgroups user not found"); } extra_group = gid_by_name(args[1]); if (extra_group == gid_not_found) { if (must_free) free(user); return env->ThrowError("initgroups extra group not found"); } int rc = initgroups(user, extra_group); if (must_free) { free(user); } if (rc) { return env->ThrowErrnoException(errno, "initgroups"); } } #endif // __POSIX__ && !defined(__ANDROID__) void Exit(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); exit(args[0]->IntegerValue()); } static void Uptime(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); double uptime; uv_update_time(uv_default_loop()); uptime = uv_now(uv_default_loop()) - prog_start_time; args.GetReturnValue().Set(Number::New(env->isolate(), uptime / 1000)); } void MemoryUsage(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); size_t rss; int err = uv_resident_set_memory(&rss); if (err) { return env->ThrowUVException(err, "uv_resident_set_memory"); } // V8 memory usage HeapStatistics v8_heap_stats; env->isolate()->GetHeapStatistics(&v8_heap_stats); Local<Integer> heap_total = Integer::NewFromUnsigned(env->isolate(), v8_heap_stats.total_heap_size()); Local<Integer> heap_used = Integer::NewFromUnsigned(env->isolate(), v8_heap_stats.used_heap_size()); Local<Object> info = Object::New(env->isolate()); info->Set(env->rss_string(), Number::New(env->isolate(), rss)); info->Set(env->heap_total_string(), heap_total); info->Set(env->heap_used_string(), heap_used); args.GetReturnValue().Set(info); } void Kill(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); if (args.Length() != 2) { return env->ThrowError("Bad argument."); } int pid = args[0]->IntegerValue(); int sig = args[1]->Int32Value(); int err = uv_kill(pid, sig); args.GetReturnValue().Set(err); } // used in Hrtime() below #define NANOS_PER_SEC 1000000000 // Hrtime exposes libuv's uv_hrtime() high-resolution timer. // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds, // so this function instead returns an Array with 2 entries representing seconds // and nanoseconds, to avoid any integer overflow possibility. // Pass in an Array from a previous hrtime() call to instead get a time diff. void Hrtime(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); uint64_t t = uv_hrtime(); if (args.Length() > 0) { // return a time diff tuple if (!args[0]->IsArray()) { return env->ThrowTypeError( "process.hrtime() only accepts an Array tuple."); } Local<Array> inArray = Local<Array>::Cast(args[0]); uint64_t seconds = inArray->Get(0)->Uint32Value(); uint64_t nanos = inArray->Get(1)->Uint32Value(); t -= (seconds * NANOS_PER_SEC) + nanos; } Local<Array> tuple = Array::New(env->isolate(), 2); tuple->Set(0, Integer::NewFromUnsigned(env->isolate(), t / NANOS_PER_SEC)); tuple->Set(1, Integer::NewFromUnsigned(env->isolate(), t % NANOS_PER_SEC)); args.GetReturnValue().Set(tuple); } extern "C" void node_module_register(void* m) { struct node_module* mp = reinterpret_cast<struct node_module*>(m); if (mp->nm_flags & NM_F_BUILTIN) { mp->nm_link = modlist_builtin; modlist_builtin = mp; } else { assert(modpending == NULL); modpending = mp; } } struct node_module* get_builtin_module(const char* name) { struct node_module* mp; for (mp = modlist_builtin; mp != NULL; mp = mp->nm_link) { if (strcmp(mp->nm_modname, name) == 0) break; } assert(mp == NULL || (mp->nm_flags & NM_F_BUILTIN) != 0); return (mp); } typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports); // DLOpen is process.dlopen(module, filename). // Used to load 'module.node' dynamically shared objects. // // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict // when two contexts try to load the same shared object. Maybe have a shadow // cache that's a plain C list or hash table that's shared across contexts? void DLOpen(const FunctionCallbackInfo<Value>& args) { HandleScope handle_scope(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate()); struct node_module* mp; uv_lib_t lib; if (args.Length() < 2) { env->ThrowError("process.dlopen takes exactly 2 arguments."); return; } Local<Object> module = args[0]->ToObject(); // Cast String::Utf8Value filename(args[1]); // Cast Local<String> exports_string = env->exports_string(); Local<Object> exports = module->Get(exports_string)->ToObject(); if (uv_dlopen(*filename, &lib)) { Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib)); #ifdef _WIN32 // Windows needs to add the filename into the error message errmsg = String::Concat(errmsg, args[1]->ToString()); #endif // _WIN32 env->isolate()->ThrowException(Exception::Error(errmsg)); return; } /* * Objects containing v14 or later modules will have registered themselves * on the pending list. Activate all of them now. At present, only one * module per object is supported. */ mp = modpending; modpending = NULL; if (mp == NULL) { env->ThrowError("Module did not self-register."); return; } if (mp->nm_version != NODE_MODULE_VERSION) { char errmsg[1024]; snprintf(errmsg, sizeof(errmsg), "Module version mismatch. Expected %d, got %d.", NODE_MODULE_VERSION, mp->nm_version); env->ThrowError(errmsg); return; } if (mp->nm_flags & NM_F_BUILTIN) { env->ThrowError("Built-in module self-registered."); return; } mp->nm_dso_handle = lib.handle; mp->nm_link = modlist_addon; modlist_addon = mp; if (mp->nm_context_register_func != NULL) { mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv); } else if (mp->nm_register_func != NULL) { mp->nm_register_func(exports, module, mp->nm_priv); } else { env->ThrowError("Module has no declared entry point."); return; } // Tell coverity that 'handle' should not be freed when we return. // coverity[leaked_storage] } static void OnFatalError(const char* location, const char* message) { if (location) { fprintf(stderr, "FATAL ERROR: %s %s\n", location, message); } else { fprintf(stderr, "FATAL ERROR: %s\n", message); } fflush(stderr); abort(); } NO_RETURN void FatalError(const char* location, const char* message) { OnFatalError(location, message); // to supress compiler warning abort(); } void FatalException(Isolate* isolate, Handle<Value> error, Handle<Message> message) { HandleScope scope(isolate); Environment* env = Environment::GetCurrent(isolate); Local<Object> process_object = env->process_object(); Local<String> fatal_exception_string = env->fatal_exception_string(); Local<Function> fatal_exception_function = process_object->Get(fatal_exception_string).As<Function>(); if (!fatal_exception_function->IsFunction()) { // failed before the process._fatalException function was added! // this is probably pretty bad. Nothing to do but report and exit. ReportException(env, error, message); exit(6); } TryCatch fatal_try_catch; // Do not call FatalException when _fatalException handler throws fatal_try_catch.SetVerbose(false); // this will return true if the JS layer handled it, false otherwise Local<Value> caught = fatal_exception_function->Call(process_object, 1, &error); if (fatal_try_catch.HasCaught()) { // the fatal exception function threw, so we must exit ReportException(env, fatal_try_catch); exit(7); } if (false == caught->BooleanValue()) { ReportException(env, error, message); exit(1); } } void FatalException(Isolate* isolate, const TryCatch& try_catch) { HandleScope scope(isolate); // TODO(bajtos) do not call FatalException if try_catch is verbose // (requires V8 API to expose getter for try_catch.is_verbose_) FatalException(isolate, try_catch.Exception(), try_catch.Message()); } void OnMessage(Handle<Message> message, Handle<Value> error) { // The current version of V8 sends messages for errors only // (thus `error` is always set). FatalException(Isolate::GetCurrent(), error, message); } static void Binding(const FunctionCallbackInfo<Value>& args) { HandleScope handle_scope(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate()); Local<String> module = args[0]->ToString(); String::Utf8Value module_v(module); Local<Object> cache = env->binding_cache_object(); Local<Object> exports; if (cache->Has(module)) { exports = cache->Get(module)->ToObject(); args.GetReturnValue().Set(exports); return; } // Append a string to process.moduleLoadList char buf[1024]; snprintf(buf, sizeof(buf), "Binding %s", *module_v); Local<Array> modules = env->module_load_list_array(); uint32_t l = modules->Length(); modules->Set(l, OneByteString(env->isolate(), buf)); node_module* mod = get_builtin_module(*module_v); if (mod != NULL) { exports = Object::New(env->isolate()); // Internal bindings don't have a "module" object, only exports. assert(mod->nm_register_func == NULL); assert(mod->nm_context_register_func != NULL); Local<Value> unused = Undefined(env->isolate()); mod->nm_context_register_func(exports, unused, env->context(), mod->nm_priv); cache->Set(module, exports); } else if (!strcmp(*module_v, "constants")) { exports = Object::New(env->isolate()); DefineConstants(exports); cache->Set(module, exports); } else if (!strcmp(*module_v, "natives")) { exports = Object::New(env->isolate()); DefineJavaScript(env, exports); cache->Set(module, exports); } else { return env->ThrowError("No such module"); } args.GetReturnValue().Set(exports); } static void ProcessTitleGetter(Local<String> property, const PropertyCallbackInfo<Value>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); char buffer[512]; uv_get_process_title(buffer, sizeof(buffer)); info.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), buffer)); } static void ProcessTitleSetter(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); String::Utf8Value title(value); // TODO(piscisaureus): protect with a lock uv_set_process_title(*title); } static void EnvGetter(Local<String> property, const PropertyCallbackInfo<Value>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); #ifdef __POSIX__ String::Utf8Value key(property); const char* val = getenv(*key); if (val) { return info.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), val)); } #else // _WIN32 String::Value key(property); WCHAR buffer[32767]; // The maximum size allowed for environment variables. DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key), buffer, ARRAY_SIZE(buffer)); // If result >= sizeof buffer the buffer was too small. That should never // happen. If result == 0 and result != ERROR_SUCCESS the variable was not // not found. if ((result > 0 || GetLastError() == ERROR_SUCCESS) && result < ARRAY_SIZE(buffer)) { const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer); Local<String> rc = String::NewFromTwoByte(env->isolate(), two_byte_buffer); return info.GetReturnValue().Set(rc); } #endif // Not found. Fetch from prototype. info.GetReturnValue().Set( info.Data().As<Object>()->Get(property)); } static void EnvSetter(Local<String> property, Local<Value> value, const PropertyCallbackInfo<Value>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); #ifdef __POSIX__ String::Utf8Value key(property); String::Utf8Value val(value); setenv(*key, *val, 1); #else // _WIN32 String::Value key(property); String::Value val(value); WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key); // Environment variables that start with '=' are read-only. if (key_ptr[0] != L'=') { SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val)); } #endif // Whether it worked or not, always return rval. info.GetReturnValue().Set(value); } static void EnvQuery(Local<String> property, const PropertyCallbackInfo<Integer>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); int32_t rc = -1; // Not found unless proven otherwise. #ifdef __POSIX__ String::Utf8Value key(property); if (getenv(*key)) rc = 0; #else // _WIN32 String::Value key(property); WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key); if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 || GetLastError() == ERROR_SUCCESS) { rc = 0; if (key_ptr[0] == L'=') { // Environment variables that start with '=' are hidden and read-only. rc = static_cast<int32_t>(v8::ReadOnly) | static_cast<int32_t>(v8::DontDelete) | static_cast<int32_t>(v8::DontEnum); } } #endif if (rc != -1) info.GetReturnValue().Set(rc); } static void EnvDeleter(Local<String> property, const PropertyCallbackInfo<Boolean>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); bool rc = true; #ifdef __POSIX__ String::Utf8Value key(property); rc = getenv(*key) != NULL; if (rc) unsetenv(*key); #else String::Value key(property); WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key); if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) { // Deletion failed. Return true if the key wasn't there in the first place, // false if it is still there. rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 && GetLastError() != ERROR_SUCCESS; } #endif info.GetReturnValue().Set(rc); } static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); #ifdef __POSIX__ int size = 0; while (environ[size]) size++; Local<Array> envarr = Array::New(env->isolate(), size); for (int i = 0; i < size; ++i) { const char* var = environ[i]; const char* s = strchr(var, '='); const int length = s ? s - var : strlen(var); Local<String> name = String::NewFromUtf8(env->isolate(), var, String::kNormalString, length); envarr->Set(i, name); } #else // _WIN32 WCHAR* environment = GetEnvironmentStringsW(); if (environment == NULL) return; // This should not happen. Local<Array> envarr = Array::New(env->isolate()); WCHAR* p = environment; int i = 0; while (*p != NULL) { WCHAR *s; if (*p == L'=') { // If the key starts with '=' it is a hidden environment variable. p += wcslen(p) + 1; continue; } else { s = wcschr(p, L'='); } if (!s) { s = p + wcslen(p); } const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p); const size_t two_byte_buffer_len = s - p; Local<String> value = String::NewFromTwoByte(env->isolate(), two_byte_buffer, String::kNormalString, two_byte_buffer_len); envarr->Set(i++, value); p = s + wcslen(s) + 1; } FreeEnvironmentStringsW(environment); #endif info.GetReturnValue().Set(envarr); } static Handle<Object> GetFeatures(Environment* env) { EscapableHandleScope scope(env->isolate()); Local<Object> obj = Object::New(env->isolate()); #if defined(DEBUG) && DEBUG Local<Value> debug = True(env->isolate()); #else Local<Value> debug = False(env->isolate()); #endif // defined(DEBUG) && DEBUG obj->Set(env->debug_string(), debug); obj->Set(env->uv_string(), True(env->isolate())); // TODO(bnoordhuis) ping libuv obj->Set(env->ipv6_lc_string(), True(env->isolate())); #ifdef OPENSSL_NPN_NEGOTIATED Local<Boolean> tls_npn = True(env->isolate()); #else Local<Boolean> tls_npn = False(env->isolate()); #endif obj->Set(env->tls_npn_string(), tls_npn); #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB Local<Boolean> tls_sni = True(env->isolate()); #else Local<Boolean> tls_sni = False(env->isolate()); #endif obj->Set(env->tls_sni_string(), tls_sni); #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_set_tlsext_status_cb) Local<Boolean> tls_ocsp = True(env->isolate()); #else Local<Boolean> tls_ocsp = False(env->isolate()); #endif // !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_set_tlsext_status_cb) obj->Set(env->tls_ocsp_string(), tls_ocsp); obj->Set(env->tls_string(), Boolean::New(env->isolate(), get_builtin_module("crypto") != NULL)); return scope.Escape(obj); } static void DebugPortGetter(Local<String> property, const PropertyCallbackInfo<Value>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); info.GetReturnValue().Set(debug_port); } static void DebugPortSetter(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) { Environment* env = Environment::GetCurrent(info.GetIsolate()); HandleScope scope(env->isolate()); debug_port = value->NumberValue(); } static void DebugProcess(const FunctionCallbackInfo<Value>& args); static void DebugPause(const FunctionCallbackInfo<Value>& args); static void DebugEnd(const FunctionCallbackInfo<Value>& args); void NeedImmediateCallbackGetter(Local<String> property, const PropertyCallbackInfo<Value>& info) { HandleScope handle_scope(info.GetIsolate()); Environment* env = Environment::GetCurrent(info.GetIsolate()); const uv_check_t* immediate_check_handle = env->immediate_check_handle(); bool active = uv_is_active( reinterpret_cast<const uv_handle_t*>(immediate_check_handle)); info.GetReturnValue().Set(active); } static void NeedImmediateCallbackSetter( Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) { HandleScope handle_scope(info.GetIsolate()); Environment* env = Environment::GetCurrent(info.GetIsolate()); uv_check_t* immediate_check_handle = env->immediate_check_handle(); bool active = uv_is_active( reinterpret_cast<const uv_handle_t*>(immediate_check_handle)); if (active == value->BooleanValue()) return; uv_idle_t* immediate_idle_handle = env->immediate_idle_handle(); if (active) { uv_check_stop(immediate_check_handle); uv_idle_stop(immediate_idle_handle); } else { uv_check_start(immediate_check_handle, CheckImmediate); // Idle handle is needed only to stop the event loop from blocking in poll. uv_idle_start(immediate_idle_handle, IdleImmediateDummy); } } void SetIdle(uv_prepare_t* handle) { Environment* env = Environment::from_idle_prepare_handle(handle); env->isolate()->GetCpuProfiler()->SetIdle(true); } void ClearIdle(uv_check_t* handle) { Environment* env = Environment::from_idle_check_handle(handle); env->isolate()->GetCpuProfiler()->SetIdle(false); } void StartProfilerIdleNotifier(Environment* env) { uv_prepare_start(env->idle_prepare_handle(), SetIdle); uv_check_start(env->idle_check_handle(), ClearIdle); } void StopProfilerIdleNotifier(Environment* env) { uv_prepare_stop(env->idle_prepare_handle()); uv_check_stop(env->idle_check_handle()); } void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) { HandleScope handle_scope(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate()); StartProfilerIdleNotifier(env); } void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) { HandleScope handle_scope(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate()); StopProfilerIdleNotifier(env); } #define READONLY_PROPERTY(obj, str, var) \ do { \ obj->Set(OneByteString(env->isolate(), str), var, v8::ReadOnly); \ } while (0) void SetupProcessObject(Environment* env, int argc, const char* const* argv, int exec_argc, const char* const* exec_argv) { HandleScope scope(env->isolate()); Local<Object> process = env->process_object(); process->SetAccessor(env->title_string(), ProcessTitleGetter, ProcessTitleSetter); // process.version READONLY_PROPERTY(process, "version", FIXED_ONE_BYTE_STRING(env->isolate(), NODE_VERSION)); // process.moduleLoadList READONLY_PROPERTY(process, "moduleLoadList", env->module_load_list_array()); // process.versions Local<Object> versions = Object::New(env->isolate()); READONLY_PROPERTY(process, "versions", versions); const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "." NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR); READONLY_PROPERTY(versions, "http_parser", FIXED_ONE_BYTE_STRING(env->isolate(), http_parser_version)); // +1 to get rid of the leading 'v' READONLY_PROPERTY(versions, "node", OneByteString(env->isolate(), NODE_VERSION + 1)); READONLY_PROPERTY(versions, "v8", OneByteString(env->isolate(), V8::GetVersion())); READONLY_PROPERTY(versions, "uv", OneByteString(env->isolate(), uv_version_string())); READONLY_PROPERTY(versions, "zlib", FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION)); const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION); READONLY_PROPERTY( versions, "modules", FIXED_ONE_BYTE_STRING(env->isolate(), node_modules_version)); #if HAVE_OPENSSL // Stupid code to slice out the version string. { // NOLINT(whitespace/braces) size_t i, j, k; int c; for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) { c = OPENSSL_VERSION_TEXT[i]; if ('0' <= c && c <= '9') { for (j = i + 1; j < k; ++j) { c = OPENSSL_VERSION_TEXT[j]; if (c == ' ') break; } break; } } READONLY_PROPERTY( versions, "openssl", OneByteString(env->isolate(), &OPENSSL_VERSION_TEXT[i], j - i)); } #endif // process.arch READONLY_PROPERTY(process, "arch", OneByteString(env->isolate(), ARCH)); // process.platform READONLY_PROPERTY(process, "platform", OneByteString(env->isolate(), PLATFORM)); // process.argv Local<Array> arguments = Array::New(env->isolate(), argc); for (int i = 0; i < argc; ++i) { arguments->Set(i, String::NewFromUtf8(env->isolate(), argv[i])); } process->Set(env->argv_string(), arguments); // process.execArgv Local<Array> exec_arguments = Array::New(env->isolate(), exec_argc); for (int i = 0; i < exec_argc; ++i) { exec_arguments->Set(i, String::NewFromUtf8(env->isolate(), exec_argv[i])); } process->Set(env->exec_argv_string(), exec_arguments); // create process.env Local<ObjectTemplate> process_env_template = ObjectTemplate::New(env->isolate()); process_env_template->SetNamedPropertyHandler(EnvGetter, EnvSetter, EnvQuery, EnvDeleter, EnvEnumerator, Object::New(env->isolate())); Local<Object> process_env = process_env_template->NewInstance(); process->Set(env->env_string(), process_env); READONLY_PROPERTY(process, "pid", Integer::New(env->isolate(), getpid())); READONLY_PROPERTY(process, "features", GetFeatures(env)); process->SetAccessor(env->need_imm_cb_string(), NeedImmediateCallbackGetter, NeedImmediateCallbackSetter); // -e, --eval if (eval_string) { READONLY_PROPERTY(process, "_eval", String::NewFromUtf8(env->isolate(), eval_string)); } // -p, --print if (print_eval) { READONLY_PROPERTY(process, "_print_eval", True(env->isolate())); } // -i, --interactive if (force_repl) { READONLY_PROPERTY(process, "_forceRepl", True(env->isolate())); } // --no-deprecation if (no_deprecation) { READONLY_PROPERTY(process, "noDeprecation", True(env->isolate())); } // --throw-deprecation if (throw_deprecation) { READONLY_PROPERTY(process, "throwDeprecation", True(env->isolate())); } // --trace-deprecation if (trace_deprecation) { READONLY_PROPERTY(process, "traceDeprecation", True(env->isolate())); } size_t exec_path_len = 2 * PATH_MAX; char* exec_path = new char[exec_path_len]; Local<String> exec_path_value; if (uv_exepath(exec_path, &exec_path_len) == 0) { exec_path_value = String::NewFromUtf8(env->isolate(), exec_path, String::kNormalString, exec_path_len); } else { exec_path_value = String::NewFromUtf8(env->isolate(), argv[0]); } process->Set(env->exec_path_string(), exec_path_value); delete[] exec_path; process->SetAccessor(env->debug_port_string(), DebugPortGetter, DebugPortSetter); // define various internal methods NODE_SET_METHOD(process, "_startProfilerIdleNotifier", StartProfilerIdleNotifier); NODE_SET_METHOD(process, "_stopProfilerIdleNotifier", StopProfilerIdleNotifier); NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests); NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles); NODE_SET_METHOD(process, "reallyExit", Exit); NODE_SET_METHOD(process, "abort", Abort); NODE_SET_METHOD(process, "chdir", Chdir); NODE_SET_METHOD(process, "cwd", Cwd); NODE_SET_METHOD(process, "umask", Umask); #if defined(__POSIX__) && !defined(__ANDROID__) NODE_SET_METHOD(process, "getuid", GetUid); NODE_SET_METHOD(process, "setuid", SetUid); NODE_SET_METHOD(process, "setgid", SetGid); NODE_SET_METHOD(process, "getgid", GetGid); NODE_SET_METHOD(process, "getgroups", GetGroups); NODE_SET_METHOD(process, "setgroups", SetGroups); NODE_SET_METHOD(process, "initgroups", InitGroups); #endif // __POSIX__ && !defined(__ANDROID__) NODE_SET_METHOD(process, "_kill", Kill); NODE_SET_METHOD(process, "_debugProcess", DebugProcess); NODE_SET_METHOD(process, "_debugPause", DebugPause); NODE_SET_METHOD(process, "_debugEnd", DebugEnd); NODE_SET_METHOD(process, "hrtime", Hrtime); NODE_SET_METHOD(process, "dlopen", DLOpen); NODE_SET_METHOD(process, "uptime", Uptime); NODE_SET_METHOD(process, "memoryUsage", MemoryUsage); NODE_SET_METHOD(process, "binding", Binding); NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener); NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick); NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse); // values use to cross communicate with processNextTick Local<Object> tick_info_obj = Object::New(env->isolate()); tick_info_obj->SetIndexedPropertiesToExternalArrayData( env->tick_info()->fields(), kExternalUnsignedIntArray, env->tick_info()->fields_count()); process->Set(env->tick_info_string(), tick_info_obj); // pre-set _events object for faster emit checks process->Set(env->events_string(), Object::New(env->isolate())); } #undef READONLY_PROPERTY static void AtExit() { uv_tty_reset_mode(); } static void SignalExit(int signo) { uv_tty_reset_mode(); raise(signo); } // Most of the time, it's best to use `console.error` to write // to the process.stderr stream. However, in some cases, such as // when debugging the stream.Writable class or the process.nextTick // function, it is useful to bypass JavaScript entirely. static void RawDebug(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); assert(args.Length() == 1 && args[0]->IsString() && "must be called with a single string"); String::Utf8Value message(args[0]); fprintf(stderr, "%s\n", *message); fflush(stderr); } void Load(Environment* env) { HandleScope handle_scope(env->isolate()); // Compile, execute the src/node.js file. (Which was included as static C // string in node_natives.h. 'natve_node' is the string containing that // source code.) // The node.js file returns a function 'f' atexit(AtExit); TryCatch try_catch; // Disable verbose mode to stop FatalException() handler from trying // to handle the exception. Errors this early in the start-up phase // are not safe to ignore. try_catch.SetVerbose(false); Local<String> script_name = FIXED_ONE_BYTE_STRING(env->isolate(), "node.js"); Local<Value> f_value = ExecuteString(env, MainSource(env), script_name); if (try_catch.HasCaught()) { ReportException(env, try_catch); exit(10); } assert(f_value->IsFunction()); Local<Function> f = Local<Function>::Cast(f_value); // Now we call 'f' with the 'process' variable that we've built up with // all our bindings. Inside node.js we'll take care of assigning things to // their places. // We start the process this way in order to be more modular. Developers // who do not like how 'src/node.js' setups the module system but do like // Node's I/O bindings may want to replace 'f' with their own function. // Add a reference to the global object Local<Object> global = env->context()->Global(); #if defined HAVE_DTRACE || defined HAVE_ETW InitDTrace(env, global); #endif #if defined HAVE_PERFCTR InitPerfCounters(env, global); #endif // Enable handling of uncaught exceptions // (FatalException(), break on uncaught exception in debugger) // // This is not strictly necessary since it's almost impossible // to attach the debugger fast enought to break on exception // thrown during process startup. try_catch.SetVerbose(true); NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug); Local<Value> arg = env->process_object(); f->Call(global, 1, &arg); } static void PrintHelp(); static bool ParseDebugOpt(const char* arg) { const char* port = NULL; if (!strcmp(arg, "--debug")) { use_debug_agent = true; } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) { use_debug_agent = true; port = arg + sizeof("--debug=") - 1; } else if (!strcmp(arg, "--debug-brk")) { use_debug_agent = true; debug_wait_connect = true; } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) { use_debug_agent = true; debug_wait_connect = true; port = arg + sizeof("--debug-brk=") - 1; } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) { port = arg + sizeof("--debug-port=") - 1; } else { return false; } if (port != NULL) { debug_port = atoi(port); if (debug_port < 1024 || debug_port > 65535) { fprintf(stderr, "Debug port must be in range 1024 to 65535.\n"); PrintHelp(); exit(12); } } return true; } static void PrintHelp() { printf("Usage: node [options] [ -e script | script.js ] [arguments] \n" " node debug script.js [arguments] \n" "\n" "Options:\n" " -v, --version print node's version\n" " -e, --eval script evaluate script\n" " -p, --print evaluate script and print result\n" " -i, --interactive always enter the REPL even if stdin\n" " does not appear to be a terminal\n" " --no-deprecation silence deprecation warnings\n" " --trace-deprecation show stack traces on deprecations\n" " --v8-options print v8 command line options\n" " --max-stack-size=val set max v8 stack size (bytes)\n" "\n" "Environment variables:\n" #ifdef _WIN32 "NODE_PATH ';'-separated list of directories\n" #else "NODE_PATH ':'-separated list of directories\n" #endif " prefixed to the module search path.\n" "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n" " global contexts.\n" "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n" "\n" "Documentation can be found at http://nodejs.org/\n"); } // Parse command line arguments. // // argv is modified in place. exec_argv and v8_argv are out arguments that // ParseArgs() allocates memory for and stores a pointer to the output // vector in. The caller should free them with delete[]. // // On exit: // // * argv contains the arguments with node and V8 options filtered out. // * exec_argv contains both node and V8 options and nothing else. // * v8_argv contains argv[0] plus any V8 options static void ParseArgs(int* argc, const char** argv, int* exec_argc, const char*** exec_argv, int* v8_argc, const char*** v8_argv) { const unsigned int nargs = static_cast<unsigned int>(*argc); const char** new_exec_argv = new const char*[nargs]; const char** new_v8_argv = new const char*[nargs]; const char** new_argv = new const char*[nargs]; for (unsigned int i = 0; i < nargs; ++i) { new_exec_argv[i] = NULL; new_v8_argv[i] = NULL; new_argv[i] = NULL; } // exec_argv starts with the first option, the other two start with argv[0]. unsigned int new_exec_argc = 0; unsigned int new_v8_argc = 1; unsigned int new_argc = 1; new_v8_argv[0] = argv[0]; new_argv[0] = argv[0]; unsigned int index = 1; while (index < nargs && argv[index][0] == '-') { const char* const arg = argv[index]; unsigned int args_consumed = 1; if (ParseDebugOpt(arg)) { // Done, consumed by ParseDebugOpt(). } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) { printf("%s\n", NODE_VERSION); exit(0); } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) { PrintHelp(); exit(0); } else if (strcmp(arg, "--eval") == 0 || strcmp(arg, "-e") == 0 || strcmp(arg, "--print") == 0 || strcmp(arg, "-pe") == 0 || strcmp(arg, "-p") == 0) { bool is_eval = strchr(arg, 'e') != NULL; bool is_print = strchr(arg, 'p') != NULL; print_eval = print_eval || is_print; // --eval, -e and -pe always require an argument. if (is_eval == true) { args_consumed += 1; eval_string = argv[index + 1]; if (eval_string == NULL) { fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg); exit(9); } } else if ((index + 1 < nargs) && argv[index + 1] != NULL && argv[index + 1][0] != '-') { args_consumed += 1; eval_string = argv[index + 1]; if (strncmp(eval_string, "\\-", 2) == 0) { // Starts with "\\-": escaped expression, drop the backslash. eval_string += 1; } } } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) { force_repl = true; } else if (strcmp(arg, "--no-deprecation") == 0) { no_deprecation = true; } else if (strcmp(arg, "--trace-deprecation") == 0) { trace_deprecation = true; } else if (strcmp(arg, "--throw-deprecation") == 0) { throw_deprecation = true; } else if (strcmp(arg, "--v8-options") == 0) { new_v8_argv[new_v8_argc] = "--help"; new_v8_argc += 1; } else { // V8 option. Pass through as-is. new_v8_argv[new_v8_argc] = arg; new_v8_argc += 1; } memcpy(new_exec_argv + new_exec_argc, argv + index, args_consumed * sizeof(*argv)); new_exec_argc += args_consumed; index += args_consumed; } // Copy remaining arguments. const unsigned int args_left = nargs - index; memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv)); new_argc += args_left; *exec_argc = new_exec_argc; *exec_argv = new_exec_argv; *v8_argc = new_v8_argc; *v8_argv = new_v8_argv; // Copy new_argv over argv and update argc. memcpy(argv, new_argv, new_argc * sizeof(*argv)); delete[] new_argv; *argc = static_cast<int>(new_argc); } // Called from V8 Debug Agent TCP thread. static void DispatchMessagesDebugAgentCallback() { uv_async_send(&dispatch_debug_messages_async); } // Called from the main thread. static void EnableDebug(Isolate* isolate, bool wait_connect) { assert(debugger_running == false); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback, false); debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION, debug_port, wait_connect); if (debugger_running == false) { fprintf(stderr, "Starting debugger on port %d failed\n", debug_port); fflush(stderr); return; } fprintf(stderr, "Debugger listening on port %d\n", debug_port); fflush(stderr); Environment* env = Environment::GetCurrentChecked(isolate); if (env == NULL) return; // Still starting up. // Assign environment to the debugger's context env->AssignToContext(v8::Debug::GetDebugContext()); Context::Scope context_scope(env->context()); Local<Object> message = Object::New(env->isolate()); message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"), FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED")); Local<Value> argv[] = { FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"), message }; MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv); } // Called from the main thread. static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle) { if (debugger_running == false) { fprintf(stderr, "Starting debugger agent.\n"); EnableDebug(node_isolate, false); } Isolate::Scope isolate_scope(node_isolate); v8::Debug::ProcessDebugMessages(); } #ifdef __POSIX__ static volatile sig_atomic_t caught_early_debug_signal; static void EarlyDebugSignalHandler(int signo) { caught_early_debug_signal = 1; } static void InstallEarlyDebugSignalHandler() { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = EarlyDebugSignalHandler; sigaction(SIGUSR1, &sa, NULL); } static void EnableDebugSignalHandler(int signo) { // Call only async signal-safe functions here! v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate)); uv_async_send(&dispatch_debug_messages_async); } static void RegisterSignalHandler(int signal, void (*handler)(int signal), bool reset_handler = false) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = handler; sa.sa_flags = reset_handler ? SA_RESETHAND : 0; sigfillset(&sa.sa_mask); CHECK_EQ(sigaction(signal, &sa, NULL), 0); } void DebugProcess(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); if (args.Length() != 1) { return env->ThrowError("Invalid number of arguments."); } pid_t pid; int r; pid = args[0]->IntegerValue(); r = kill(pid, SIGUSR1); if (r != 0) { return env->ThrowErrnoException(errno, "kill"); } } static int RegisterDebugSignalHandler() { // FIXME(bnoordhuis) Should be per-isolate or per-context, not global. RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler); // If we caught a SIGUSR1 during the bootstrap process, re-raise it // now that the debugger infrastructure is in place. if (caught_early_debug_signal) raise(SIGUSR1); return 0; } #endif // __POSIX__ #ifdef _WIN32 DWORD WINAPI EnableDebugThreadProc(void* arg) { v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate)); uv_async_send(&dispatch_debug_messages_async); return 0; } static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf, size_t buf_len) { return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid); } static int RegisterDebugSignalHandler() { wchar_t mapping_name[32]; HANDLE mapping_handle; DWORD pid; LPTHREAD_START_ROUTINE* handler; pid = GetCurrentProcessId(); if (GetDebugSignalHandlerMappingName(pid, mapping_name, ARRAY_SIZE(mapping_name)) < 0) { return -1; } mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof *handler, mapping_name); if (mapping_handle == NULL) { return -1; } handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>( MapViewOfFile(mapping_handle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof *handler)); if (handler == NULL) { CloseHandle(mapping_handle); return -1; } *handler = EnableDebugThreadProc; UnmapViewOfFile(static_cast<void*>(handler)); return 0; } static void DebugProcess(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Environment* env = Environment::GetCurrent(isolate); HandleScope scope(isolate); DWORD pid; HANDLE process = NULL; HANDLE thread = NULL; HANDLE mapping = NULL; wchar_t mapping_name[32]; LPTHREAD_START_ROUTINE* handler = NULL; if (args.Length() != 1) { env->ThrowError("Invalid number of arguments."); goto out; } pid = (DWORD) args[0]->IntegerValue(); process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, pid); if (process == NULL) { isolate->ThrowException( WinapiErrnoException(isolate, GetLastError(), "OpenProcess")); goto out; } if (GetDebugSignalHandlerMappingName(pid, mapping_name, ARRAY_SIZE(mapping_name)) < 0) { env->ThrowErrnoException(errno, "sprintf"); goto out; } mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name); if (mapping == NULL) { isolate->ThrowException(WinapiErrnoException(isolate, GetLastError(), "OpenFileMappingW")); goto out; } handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>( MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, sizeof *handler)); if (handler == NULL || *handler == NULL) { isolate->ThrowException( WinapiErrnoException(isolate, GetLastError(), "MapViewOfFile")); goto out; } thread = CreateRemoteThread(process, NULL, 0, *handler, NULL, 0, NULL); if (thread == NULL) { isolate->ThrowException(WinapiErrnoException(isolate, GetLastError(), "CreateRemoteThread")); goto out; } // Wait for the thread to terminate if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) { isolate->ThrowException(WinapiErrnoException(isolate, GetLastError(), "WaitForSingleObject")); goto out; } out: if (process != NULL) CloseHandle(process); if (thread != NULL) CloseHandle(thread); if (handler != NULL) UnmapViewOfFile(handler); if (mapping != NULL) CloseHandle(mapping); } #endif // _WIN32 static void DebugPause(const FunctionCallbackInfo<Value>& args) { v8::Debug::DebugBreak(args.GetIsolate()); } static void DebugEnd(const FunctionCallbackInfo<Value>& args) { if (debugger_running) { v8::Debug::DisableAgent(); debugger_running = false; } } void Init(int* argc, const char** argv, int* exec_argc, const char*** exec_argv) { // Initialize prog_start_time to get relative uptime. prog_start_time = uv_now(uv_default_loop()); // Make inherited handles noninheritable. uv_disable_stdio_inheritance(); // init async debug messages dispatching // FIXME(bnoordhuis) Should be per-isolate or per-context, not global. uv_async_init(uv_default_loop(), &dispatch_debug_messages_async, DispatchDebugMessagesAsyncCallback); uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async)); #if defined(NODE_V8_OPTIONS) // Should come before the call to V8::SetFlagsFromCommandLine() // so the user can disable a flag --foo at run-time by passing // --no_foo from the command line. V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1); #endif // Parse a few arguments which are specific to Node. int v8_argc; const char** v8_argv; ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv); // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler // manually? That would give us a little more control over its runtime // behavior but it could also interfere with the user's intentions in ways // we fail to anticipate. Dillema. for (int i = 1; i < v8_argc; ++i) { if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) { v8_is_profiling = true; break; } } // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify // the argv array or the elements it points to. V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true); // Anything that's still in v8_argv is not a V8 or a node option. for (int i = 1; i < v8_argc; i++) { fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]); } delete[] v8_argv; v8_argv = NULL; if (v8_argc > 1) { exit(9); } if (debug_wait_connect) { const char expose_debug_as[] = "--expose_debug_as=v8debug"; V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1); } V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton); // Fetch a reference to the main isolate, so we have a reference to it // even when we need it to access it from another (debugger) thread. node_isolate = Isolate::GetCurrent(); #ifdef __POSIX__ // Raise the open file descriptor limit. { // NOLINT (whitespace/braces) struct rlimit lim; if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) { // Do a binary search for the limit. rlim_t min = lim.rlim_cur; rlim_t max = 1 << 20; // But if there's a defined upper bound, don't search, just set it. if (lim.rlim_max != RLIM_INFINITY) { min = lim.rlim_max; max = lim.rlim_max; } do { lim.rlim_cur = min + (max - min) / 2; if (setrlimit(RLIMIT_NOFILE, &lim)) { max = lim.rlim_cur; } else { min = lim.rlim_cur; } } while (min + 1 < max); } } // Ignore SIGPIPE RegisterSignalHandler(SIGPIPE, SIG_IGN); RegisterSignalHandler(SIGINT, SignalExit, true); RegisterSignalHandler(SIGTERM, SignalExit, true); #endif // __POSIX__ V8::SetFatalErrorHandler(node::OnFatalError); V8::AddMessageListener(OnMessage); // If the --debug flag was specified then initialize the debug thread. if (use_debug_agent) { EnableDebug(node_isolate, debug_wait_connect); } else { RegisterDebugSignalHandler(); } } struct AtExitCallback { AtExitCallback* next_; void (*cb_)(void* arg); void* arg_; }; static AtExitCallback* at_exit_functions_; // TODO(bnoordhuis) Turn into per-context event. void RunAtExit(Environment* env) { AtExitCallback* p = at_exit_functions_; at_exit_functions_ = NULL; while (p) { AtExitCallback* q = p->next_; p->cb_(p->arg_); delete p; p = q; } } void AtExit(void (*cb)(void* arg), void* arg) { AtExitCallback* p = new AtExitCallback; p->cb_ = cb; p->arg_ = arg; p->next_ = at_exit_functions_; at_exit_functions_ = p; } void EmitBeforeExit(Environment* env) { Context::Scope context_scope(env->context()); HandleScope handle_scope(env->isolate()); Local<Object> process_object = env->process_object(); Local<String> exit_code = FIXED_ONE_BYTE_STRING(env->isolate(), "exitCode"); Local<Value> args[] = { FIXED_ONE_BYTE_STRING(env->isolate(), "beforeExit"), process_object->Get(exit_code)->ToInteger() }; MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args); } int EmitExit(Environment* env) { // process.emit('exit') HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); Local<Object> process_object = env->process_object(); process_object->Set(env->exiting_string(), True(env->isolate())); Handle<String> exitCode = env->exit_code_string(); int code = process_object->Get(exitCode)->IntegerValue(); Local<Value> args[] = { env->exit_string(), Integer::New(env->isolate(), code) }; MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args); // Reload exit code, it may be changed by `emit('exit')` return process_object->Get(exitCode)->IntegerValue(); } Environment* CreateEnvironment(Isolate* isolate, int argc, const char* const* argv, int exec_argc, const char* const* exec_argv) { HandleScope handle_scope(isolate); Local<Context> context = Context::New(isolate); Context::Scope context_scope(context); Environment* env = Environment::New(context); uv_check_init(env->event_loop(), env->immediate_check_handle()); uv_unref( reinterpret_cast<uv_handle_t*>(env->immediate_check_handle())); uv_idle_init(env->event_loop(), env->immediate_idle_handle()); // Inform V8's CPU profiler when we're idle. The profiler is sampling-based // but not all samples are created equal; mark the wall clock time spent in // epoll_wait() and friends so profiling tools can filter it out. The samples // still end up in v8.log but with state=IDLE rather than state=EXTERNAL. // TODO(bnoordhuis) Depends on a libuv implementation detail that we should // probably fortify in the API contract, namely that the last started prepare // or check watcher runs first. It's not 100% foolproof; if an add-on starts // a prepare or check watcher after us, any samples attributed to its callback // will be recorded with state=IDLE. uv_prepare_init(env->event_loop(), env->idle_prepare_handle()); uv_check_init(env->event_loop(), env->idle_check_handle()); uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle())); uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle())); if (v8_is_profiling) { StartProfilerIdleNotifier(env); } Local<FunctionTemplate> process_template = FunctionTemplate::New(isolate); process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process")); Local<Object> process_object = process_template->GetFunction()->NewInstance(); env->set_process_object(process_object); SetupProcessObject(env, argc, argv, exec_argc, exec_argv); Load(env); return env; } int Start(int argc, char** argv) { #if !defined(_WIN32) // Try hard not to lose SIGUSR1 signals during the bootstrap process. InstallEarlyDebugSignalHandler(); #endif assert(argc > 0); // Hack around with the argv pointer. Used for process.title = "blah". argv = uv_setup_args(argc, argv); // This needs to run *before* V8::Initialize(). The const_cast is not // optional, in case you're wondering. int exec_argc; const char** exec_argv; Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv); #if HAVE_OPENSSL // V8 on Windows doesn't have a good source of entropy. Seed it from // OpenSSL's pool. V8::SetEntropySource(crypto::EntropySource); #endif int code; V8::Initialize(); { Locker locker(node_isolate); Environment* env = CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv); // Assign env to the debugger's context if (debugger_running) { HandleScope scope(env->isolate()); env->AssignToContext(v8::Debug::GetDebugContext()); } // This Context::Scope is here so EnableDebug() can look up the current // environment with Environment::GetCurrentChecked(). // TODO(bnoordhuis) Reorder the debugger initialization logic so it can // be removed. { Context::Scope context_scope(env->context()); bool more; do { more = uv_run(env->event_loop(), UV_RUN_ONCE); if (more == false) { EmitBeforeExit(env); // Emit `beforeExit` if the loop became alive either after emitting // event, or after running some callbacks. more = uv_loop_alive(env->event_loop()); if (uv_run(env->event_loop(), UV_RUN_NOWAIT) != 0) more = true; } } while (more == true); code = EmitExit(env); RunAtExit(env); } env->Dispose(); env = NULL; } #ifndef NDEBUG // Clean up. Not strictly necessary. V8::Dispose(); #endif // NDEBUG delete[] exec_argv; exec_argv = NULL; return code; } } // namespace node
; A337730: a(n) = (4*n+3)! * Sum_{k=0..n} 1 / (4*k+3)!. ; Submitted by Christian Krause ; 1,841,6660721,218205219961,20298322381652065,4313799472548696853801,1816972337837511114820981201,1372104830641374893468212163747161,1724241814377177346127894133451232399041,3403694723384093133512770088891935585284510985 mul $0,4 add $0,3 seq $0,330045 ; Expansion of e.g.f. exp(x) / (1 - x^4).
match ,{ include 'macro/struct.inc' } match -,{ else include 'selfhost.inc' end match _ equ } include '../version.inc' BUFFER_SIZE = 4000h STACK_SIZE = 4000h format MZ heap 0 stack stack_segment:stack_top-stack_bottom entry loader:startup segment loader use16 startup: mov ax,1687h int 2Fh or ax,ax ; DPMI installed? jnz short no_dpmi test bl,1 ; 32-bit programs supported? jz short no_dpmi mov word [cs:mode_switch],di mov word [cs:mode_switch+2],es mov bx,si ; allocate memory for DPMI data mov ah,48h int 21h jnc switch_to_protected_mode init_failed: call startup_error db 'DPMI initialization failed.',0Dh,0Ah,0 no_dpmi: call startup_error db '32-bit DPMI services are not available.',0Dh,0Ah,0 startup_error: pop si push cs pop ds show_message: lodsb test al,al jz message_shown mov dl,al mov ah,2 int 21h jmp show_message message_shown: mov ax,4CFFh int 21h switch_to_protected_mode: mov es,ax mov ds,[ds:2Ch] mov ax,1 call far [cs:mode_switch] ; switch to protected mode jc init_failed mov cx,1 xor ax,ax int 31h ; allocate descriptor for code jc init_failed mov si,ax xor ax,ax int 31h ; allocate descriptor for data jc init_failed mov di,ax mov dx,cs lar cx,dx shr cx,8 or cx,0C000h mov bx,si mov ax,9 int 31h ; set code descriptor access rights jc init_failed mov dx,ds lar cx,dx shr cx,8 or cx,0C000h mov bx,di int 31h ; set data descriptor access rights jc init_failed mov ecx,main shl ecx,4 mov dx,cx shr ecx,16 mov ax,7 int 31h ; set data descriptor base address jc init_failed mov bx,si int 31h ; set code descriptor base address jc init_failed mov cx,0FFFFh mov dx,0FFFFh mov ax,8 ; set segment limit to 4 GB int 31h jc init_failed mov bx,di int 31h jc init_failed mov ax,ds mov ds,di mov [main_selector],di mov [psp_selector],es mov gs,ax ; environment selector in GS cli mov ss,di mov esp,stack_top sti mov es,di mov cx,1 xor ax,ax int 31h ; allocate descriptor for BIOS data segment jc init_failed mov bx,ax mov ax,gs lar cx,ax shr cx,8 mov ax,9 int 31h ; set descriptor access rights jc init_failed xor cx,cx mov dx,400h mov ax,7 int 31h ; set base address of BIOS data segment jc init_failed xor cx,cx mov dx,0FFh mov ax,8 int 31h ; set limit of BIOS data segment jc init_failed mov fs,bx ; BIOS data selector in FS push si push start retf mode_switch dd ? segment main use32 start: call system_init call get_arguments mov bl,al cmp [no_logo],0 jne logo_ok mov esi,_logo xor ecx,ecx call display_string logo_ok: test bl,bl jnz display_usage_information xor al,al mov ecx,[verbosity_level] jecxz init or al,TRACE_ERROR_STACK dec ecx jz init or al,TRACE_DISPLAY init: call assembly_init mov eax,[fs:6Ch] mov [timer],eax assemble: mov esi,[initial_commands] mov edx,[source_path] call assembly_pass jc assembly_done mov eax,[current_pass] cmp eax,[maximum_number_of_passes] jb assemble call show_display_data mov esi,_error_prefix xor ecx,ecx call display_error_string mov esi,_code_cannot_be_generated xor ecx,ecx call display_error_string mov esi,_message_suffix xor ecx,ecx call display_error_string jmp assembly_failed assembly_done: call show_display_data cmp [first_error],0 jne assembly_failed cmp [no_logo],0 jne summary_done mov eax,[current_pass] xor edx,edx call itoa call display_string mov esi,_passes cmp [current_pass],1 jne display_passes_suffix mov esi,_pass display_passes_suffix: xor ecx,ecx call display_string mov eax,[fs:6Ch] sub eax,[timer] mov ecx,36000 mul ecx shrd eax,edx,16 shr edx,16 mov ecx,10 div ecx mov [timer],edx or edx,eax jz display_output_length xor edx,edx call itoa call display_string mov esi,_message_suffix mov ecx,1 call display_string mov eax,[timer] xor edx,edx call itoa call display_string mov esi,_seconds xor ecx,ecx call display_string display_output_length: call get_output_length push eax edx call itoa call display_string pop edx eax mov esi,_bytes cmp eax,1 jne display_bytes_suffix test edx,edx jnz display_bytes_suffix mov esi,_byte display_bytes_suffix: xor ecx,ecx call display_string mov esi,_new_line xor ecx,ecx call display_string summary_done: mov ebx,[source_path] mov edi,[output_path] call write_output_file jc write_failed call assembly_shutdown call system_shutdown mov ax,4C00h int 21h assembly_failed: call show_errors call assembly_shutdown call system_shutdown mov ax,4C02h int 21h write_failed: mov ebx,_write_failed jmp fatal_error out_of_memory: mov ebx,_out_of_memory jmp fatal_error fatal_error: mov esi,_error_prefix xor ecx,ecx call display_error_string mov esi,ebx xor ecx,ecx call display_error_string mov esi,_message_suffix xor ecx,ecx call display_error_string call assembly_shutdown call system_shutdown mov ax,4C03h int 21h display_usage_information: mov esi,_usage xor ecx,ecx call display_string call system_shutdown mov ax,4C01h int 21h get_arguments: push ds mov ds,[psp_selector] mov esi,81h mov edi,command_line mov ecx,7Fh move_command_line: lodsb cmp al,0Dh je command_line_moved stosb loop move_command_line command_line_moved: pop ds xor eax,eax stosb mov [initial_commands],eax mov [source_path],eax mov [output_path],eax mov [no_logo],al mov [verbosity_level],eax mov [maximum_number_of_passes],100 mov [maximum_number_of_errors],1 mov [maximum_depth_of_stack],10000 mov [maximum_depth_of_stack],10000 mov esi,command_line mov edi,parameters get_argument: xor ah,ah read_character: lodsb test al,al jz no_more_arguments cmp al,22h je switch_quote cmp ax,20h je end_argument stosb jmp read_character end_argument: xor al,al stosb find_next_argument: mov al,[esi] test al,al jz no_more_arguments cmp al,20h jne next_argument_found inc esi jmp find_next_argument switch_quote: xor ah,1 jmp read_character next_argument_found: cmp al,'-' je get_option cmp al,'/' je get_option cmp [source_path],0 je get_source_path cmp [output_path],0 je get_output_path error_in_arguments: or al,-1 retn get_source_path: mov [source_path],edi jmp get_argument get_output_path: mov [output_path],edi jmp get_argument no_more_arguments: cmp [source_path],0 je error_in_arguments xor al,al stosb retn get_option: inc esi lodsb cmp al,'e' je set_errors_limit cmp al,'E' je set_errors_limit cmp al,'i' je insert_initial_command cmp al,'I' je insert_initial_command cmp al,'p' je set_passes_limit cmp al,'P' je set_passes_limit cmp al,'r' je set_recursion_limit cmp al,'R' je set_recursion_limit cmp al,'v' je set_verbose_mode cmp al,'V' je set_verbose_mode cmp al,'n' je set_no_logo cmp al,'N' jne error_in_arguments set_no_logo: or [no_logo],-1 mov al,[esi] cmp al,20h je find_next_argument test al,al jnz error_in_arguments jmp find_next_argument set_verbose_mode: call get_option_value jc error_in_arguments cmp edx,2 ja error_in_arguments mov [verbosity_level],edx jmp find_next_argument set_errors_limit: call get_option_value jc error_in_arguments test edx,edx jz error_in_arguments mov [maximum_number_of_errors],edx jmp find_next_argument set_recursion_limit: call get_option_value jc error_in_arguments test edx,edx jz error_in_arguments mov [maximum_depth_of_stack],edx jmp find_next_argument set_passes_limit: call get_option_value jc error_in_arguments test edx,edx jz error_in_arguments mov [maximum_number_of_passes],edx jmp find_next_argument get_option_value: xor eax,eax mov edx,eax find_option_value: cmp byte [esi],20h jne get_option_digit inc esi jmp find_option_value get_option_digit: lodsb cmp al,20h je option_value_ok test al,al jz option_value_ok sub al,30h jc invalid_option_value cmp al,9 ja invalid_option_value imul edx,10 jo invalid_option_value add edx,eax jc invalid_option_value jmp get_option_digit option_value_ok: dec esi clc ret invalid_option_value: stc ret insert_initial_command: push edi find_command_segment: cmp byte [esi],20h jne command_segment_found inc esi jmp find_command_segment command_segment_found: xor ah,ah cmp byte [esi],22h jne measure_command_segment inc esi inc ah measure_command_segment: mov ebx,esi scan_command_segment: mov ecx,esi mov al,[esi] test al,al jz command_segment_measured cmp ax,20h je command_segment_measured cmp ax,22h je command_segment_measured inc esi cmp al,22h jne scan_command_segment command_segment_measured: sub ecx,ebx mov edi,[initial_commands] lea eax,[ecx+2] test edi,edi jz allocate_initial_commands_buffer mov edx,[initial_commands_length] add edi,edx add eax,edx cmp eax,[initial_commands_maximum_length] ja grow_initial_commands_buffer copy_initial_command: xchg esi,ebx rep movsb mov esi,ebx sub edi,[initial_commands] mov [initial_commands_length],edi mov al,[esi] test al,al jz initial_command_ready cmp al,20h jne command_segment_found initial_command_ready: mov edi,[initial_commands] add edi,[initial_commands_length] mov ax,0Ah stosw inc [initial_commands_length] pop edi jmp find_next_argument allocate_initial_commands_buffer: push ecx mov ecx,eax call malloc mov [initial_commands],eax mov [initial_commands_maximum_length],ecx mov edi,eax pop ecx jmp copy_initial_command grow_initial_commands_buffer: push ecx mov ecx,eax mov eax,[initial_commands] call realloc mov [initial_commands],eax mov [initial_commands_maximum_length],ecx mov edi,eax add edi,[initial_commands_length] pop ecx jmp copy_initial_command include 'system.inc' include '../assembler.inc' include '../symbols.inc' include '../expressions.inc' include '../conditions.inc' include '../floats.inc' include '../directives.inc' include '../calm.inc' include '../errors.inc' include '../map.inc' include '../reader.inc' include '../output.inc' include '../console.inc' _logo db 'flat assembler version g.',VERSION,13,10,0 _usage db 'Usage: fasmg source [output]',13,10 db 'Optional settings:',13,10 db ' -e limit Set the maximum number of displayed errors (default 1)',13,10 db ' -p limit Set the maximum allowed number of passes (default 100)',13,10 db ' -r limit Set the maximum depth of the stack (default 10000)',13,10 db ' -v flag Enable or disable showing all lines from the stack (default 0)',13,10 db ' -i command Insert instruction at the beginning of source',13,10 db ' -n Do not show logo nor summary',13,10 db 0 _pass db ' pass, ',0 _passes db ' passes, ',0 _dot db '.' _seconds db ' seconds, ',0 _byte db ' byte.',0 _bytes db ' bytes.',0 _write_failed db 'failed to write the output file',0 _out_of_memory db 'not enough memory to complete the assembly',0 _code_cannot_be_generated db 'could not generate code within the allowed number of passes',0 include '../tables.inc' include '../messages.inc' align 4 include '../variables.inc' psp_selector dw ? main_selector dw ? malloc_freelist dd ? source_path dd ? output_path dd ? maximum_number_of_passes dd ? initial_commands dd ? initial_commands_length dd ? initial_commands_maximum_length dd ? timestamp dq ? timer dd ? verbosity_level dd ? no_logo db ? command_line db 80h dup ? parameters db 80h dup ? segment buffer_segment buffer = (buffer_segment-main) shl 4 db BUFFER_SIZE dup ? segment stack_segment stack_bottom = (stack_segment-main) shl 4 db STACK_SIZE dup ? stack_top = stack_bottom + $
#include <iostream> #include <vector> using namespace std; int main(void) { int T; cin >> T; while (T--) { int N, M; vector<int> arr; vector<int> dp; cin >> N; arr.resize(N + 1); for (int i = 1; i <= N; i++) cin >> arr[i]; cin >> M; dp.resize(M + 1, 0); dp[0] = 1; for (int i = 1; i <= N; i++) for (int j = arr[i]; j <= M; j++) dp[j] += dp[j - arr[i]]; cout << dp[M] << '\n'; } }
; code sizes (bytes): 8518 (incl. 0 frags, and 1606 lits); src size 0 ; assembly: 5813 lines; density: 33.23 bytes/stmt ; total bytes: 223558 (92.1% of 237.0k flash with 19130 free) ; peep hole pass: 136 instructions removed and 477 updated ; peep hole pass: 107 instructions removed and 79 updated ; peep hole pass: 0 instructions removed and 0 updated ; start .startaddr 0x34800 .hex 708E3B92C615A841C49866C975EE5197 ; magic number .hex 36EF2616D2F5C491 ; hex template hash .hex E059D8F63A18A5A8 ; program hash .short 11 ; num. globals .short 0 ; patched with number of words resulting from assembly .word _pxt_config_data .short 0 ; patched with comm section size .short 0 ; reserved .word 0 ; reserved ; ; Function <main> ; .section code b .themain .balign 4 _main___P1_Lit: .short 0xffff, 33 ; action literal .themain: @stackmark litfunc push {lr} @dummystack 4 bl _lambda_setup_0 bl _main___P1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code _main___P1: @stackmark func @stackmark args push {lr} @stackmark locals _main___P1_locals: ldr r0, [r6, #4] bl _pxt_decr movs r0, #0 str r0, [r6, #4] @stackempty locals ldr r0, _ldlit_2 push {r0} ; proc-arg bl addListener__P204 _proccall65: bl _clr1_1 @dummystack -1 @stackempty locals ldr r0, _ldlit_3 push {r0} ; proc-arg ldr r0, _ldlit_4 push {r0} ; proc-arg bl onCmdReceived__P357 _proccall66: bl _clr2_2 @dummystack -2 @stackempty locals ldr r0, _ldlit_5 push {r0} ; proc-arg ldr r0, _ldlit_6 push {r0} ; proc-arg bl onCmdReceived__P357 _proccall67: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #66 push {r0} ; proc-arg bl init__P374 _proccall68: bl _clr1_1 @dummystack -1 @stackempty locals ldr r0, _ldlit_7 push {r0}; tmpstore @1 ldr r0, [r6, #20] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #20] @stackempty locals ldr r0, [r6, #24] bl _pxt_decr movs r0, #10 str r0, [r6, #24] @stackempty locals ldr r0, [r6, #12] bl _pxt_decr movs r0, #6 str r0, [r6, #12] @stackempty locals movs r0, Message__C356_VT@hi ; ldptr lsls r0, r0, #8 adds r0, Message__C356_VT@lo bl pxt::mkClassInstance push {r0}; tmpstore @1 ldr r0, [r6, #16] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #16] @stackempty locals ldr r0, [r6, #40] bl _pxt_decr movs r0, #6 str r0, [r6, #40] @stackempty locals ldr r0, [r6, #36] bl _pxt_decr movs r0, #1 str r0, [r6, #36] @stackempty locals ldr r0, [r6, #32] bl _pxt_decr movs r0, #251 str r0, [r6, #32] @stackempty locals ldr r0, [r6, #28] bl _pxt_decr movs r0, #9 str r0, [r6, #28] @stackempty locals .ret.1: @stackempty locals _main___P1_end: pop {pc} @stackempty func @stackempty args ; ; Function inline ; .section code .balign 4 inline__P346_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl inline__P346 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code inline__P346: @stackmark func @stackmark args push {lr} @stackmark locals inline__P346_locals: bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 bl bluetooth::__log bl _clr1_1 @dummystack -1 @stackempty locals .ret.346: @stackempty locals inline__P346_end: pop {pc} @stackempty func @stackempty args ; ; Function addListener ; .section code .balign 4 addListener__P204_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl addListener__P204 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code addListener__P204: @stackmark func @stackmark args push {lr} @stackmark locals addListener__P204_locals: bl _pxt_incr_4 bl numops::toBoolDecr bl Boolean_::bang bl pxt::fromBool bl numops::toBoolDecr cmp r0, #0 beq .else_0_3 .jmpz69: b .ret.204 .else_0_3: .afterif_1_3: ldr r0, [r6, #4] bl _pxt_incr bl numops::toBoolDecr bl Boolean_::bang bl pxt::fromBool bl numops::toBoolDecr cmp r0, #0 beq .else_2_3 .jmpz70: bl Array_::mk push {r0}; tmpstore @1 ldr r0, [r6, #4] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #4] @stackempty locals .else_2_3: .afterif_3_3: ldr r0, [r6, #4] bl _pxt_incr_pushR0 @dummystack 1 bl _pxt_incr_pushR0_8 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl Array_::push bl _clr2_2 @dummystack -2 @stackempty locals .ret.204: @stackempty locals addListener__P204_end: pop {pc} @stackempty func @stackempty args ; ; Function inline ; .section code .balign 4 inline__P358_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl inline__P358 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code inline__P358: @stackmark func @stackmark args push {lr} movs r0, #0 push {r0} ;loc push {r0} ;loc @stackmark locals inline__P358_locals: bl _pxt_incr_12 movs r1, #0 bl pxtrt::ldfldRef push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals bl _pxt_incr_12 movs r1, #1 bl pxtrt::ldfldRef push {r0}; tmpstore @1 bl _pxt_decr_8 pop {r0} ; tmpref @1 str r0, [sp, locals@1] @stackempty locals bl _pxt_incr_pushR0_4 @dummystack 1 mov r1, r0 ldr r0, _ldlit_8 bl pxt::switch_eq cmp r0, #0 beq .jmpz71 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_0_4 .jmpz71: bl _pxt_decr_0 pop {r0} ; tmpref @1 b .switch_1_4 .switch_0_4: b .brk.362 .switch_1_4: movs r0, #101 push {r0} ; proc-arg movs r0, #4 lsls r0, r0, #8 adds r0, #23 push {r0} ; proc-arg bl playTone__P286 _proccall72: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #7 lsls r0, r0, #8 adds r0, #185 push {r0} ; proc-arg bl playTone__P286 _proccall73: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #4 lsls r0, r0, #8 adds r0, #23 push {r0} ; proc-arg bl playTone__P286 _proccall74: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #7 lsls r0, r0, #8 adds r0, #185 push {r0} ; proc-arg bl playTone__P286 _proccall75: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #4 lsls r0, r0, #8 adds r0, #23 push {r0} ; proc-arg bl playTone__P286 _proccall76: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #7 lsls r0, r0, #8 adds r0, #185 push {r0} ; proc-arg bl playTone__P286 _proccall77: bl _clr2_2 @dummystack -2 @stackempty locals .brk.362: .ret.358: @stackempty locals bl _pxt_decr_0 bl _pxt_decr_4 add sp, #4*2 ; pop locals 2 inline__P358_end: pop {pc} @stackempty func @stackempty args ; ; Function playTone ; .section code .balign 4 playTone__P286_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 6 bl _lambda_setup_5 bl playTone__P286 add sp, #4*2 ; pop locals 2 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code playTone__P286: @stackmark func @stackmark args push {lr} @stackmark locals playTone__P286_locals: ldr r0, [r6, #8] bl _pxt_incr bl numops::toBoolDecr cmp r0, #0 beq .else_0_5 .jmpz78: ldr r0, [r6, #8] bl _pxt_incr_pushR0 @dummystack 1 bl _pxt_incr_pushR0_8 @dummystack 1 bl _pxt_incr_pushR0_16 @dummystack 1 ldr r0, [sp, #4*2] ; estack ldr r1, [sp, #4*1] ; estack ldr r2, [sp, #4*0] ; estack bl pxt::runAction2 bl _clr3_6 @dummystack -3 @stackempty locals b .afterif_1_5 .else_0_5: bl _pxt_incr_pushR0_4 @dummystack 1 bl _pxt_incr_pushR0_12 @dummystack 1 bl _conv_7 bl pins::analogPitch bl _clr2_2 @dummystack -2 @stackempty locals .afterif_1_5: .ret.286: @stackempty locals playTone__P286_end: pop {pc} @stackempty func @stackempty args ; ; Function onCmdReceived ; .section code .balign 4 onCmdReceived__P357_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 6 bl _lambda_setup_5 bl onCmdReceived__P357 add sp, #4*2 ; pop locals 2 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code onCmdReceived__P357: @stackmark func @stackmark args push {lr} movs r0, #0 push {r0} ;loc @stackmark locals onCmdReceived__P357_locals: movs r0, LinkedKeyHandlerList__C368_VT@hi ; ldptr lsls r0, r0, #8 adds r0, LinkedKeyHandlerList__C368_VT@lo bl pxt::mkClassInstance push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 bl _pxt_incr_pushR0_16 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r2, [sp, #4*0] ; estack movs r1, #1 bl pxtrt::stfldRef add sp, #4*2 ; pop locals 2 @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 bl _pxt_incr_pushR0_12 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r2, [sp, #4*0] ; estack movs r1, #0 bl pxtrt::stfldRef add sp, #4*2 ; pop locals 2 @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 ldr r0, [r6, #12] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r2, [sp, #4*0] ; estack movs r1, #2 bl pxtrt::stfldRef add sp, #4*2 ; pop locals 2 @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 ldr r0, [r6, #12] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #12] @stackempty locals .ret.357: @stackempty locals bl _pxt_decr_0 add sp, #4*1 ; pop locals 1 onCmdReceived__P357_end: pop {pc} .balign 4 _ldlit_2: .word inline__P346_Lit _ldlit_3: .word inline__P358_Lit _ldlit_4: .word _str41meta _ldlit_5: .word inline__P370_Lit _ldlit_6: .word _str43meta _ldlit_7: .word _str44meta _ldlit_8: .word _str42meta @stackempty func @stackempty args ; ; Function inline ; .section code .balign 4 inline__P370_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl inline__P370 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code inline__P370: @stackmark func @stackmark args push {lr} movs r0, #0 push {r0} ;loc push {r0} ;loc @stackmark locals inline__P370_locals: bl _pxt_incr_12 movs r1, #0 bl pxtrt::ldfldRef push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals bl _pxt_incr_12 movs r1, #1 bl pxtrt::ldfldRef push {r0}; tmpstore @1 bl _pxt_decr_8 pop {r0} ; tmpref @1 str r0, [sp, locals@1] @stackempty locals .ret.370: @stackempty locals bl _pxt_decr_0 bl _pxt_decr_4 add sp, #4*2 ; pop locals 2 inline__P370_end: pop {pc} @stackempty func @stackempty args ; ; Function init ; .section code .balign 4 init__P374_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl init__P374 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code init__P374: @stackmark func @stackmark args push {lr} @stackmark locals init__P374_locals: bl bluetooth::startUartService @stackempty locals movs r0, #1 movs r1, #1 movs r2, inline__P382_Lit@hi ; ldptr lsls r2, r2, #8 adds r2, inline__P382_Lit@lo bl pxt::mkAction push {r0}; tmpstore @1 push {r0} ; proc-arg bl _pxt_incr_pushR0_12 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r2, [sp, #4*0] ; estack movs r1, #0 bl pxtrt::stclo add sp, #4*2 ; pop locals 2 ldr r0, [r6, #20] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*1] ; tmpref @1 push {r0} ; proc-arg bl _conv_8 bl bluetooth::onUartDataReceived bl _clr2_9 @dummystack -3 @stackempty locals ldr r0, _ldlit_10 bl bluetooth::onBluetoothConnected @stackempty locals ldr r0, _ldlit_11 bl bluetooth::onBluetoothDisconnected @stackempty locals movs r0, _img64@hi ; ldptr lsls r0, r0, #8 adds r0, _img64@lo movs r1, #25 lsls r1, r1, #4 bl basic::showLeds @stackempty locals .ret.374: @stackempty locals init__P374_end: pop {pc} @stackempty func @stackempty args ; ; Function inline ; .section code .balign 4 inline__P382_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 4 bl _lambda_setup_0 bl inline__P382 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code inline__P382: @stackmark func @stackmark args push {lr} @stackmark locals inline__P382_locals: ldr r0, [r5, #4*0] bl _pxt_incr_pushR0 @dummystack 1 bl handleIncomingUARTData__P383 _proccall79: bl _clr1_1 @dummystack -1 @stackempty locals movs r0, #10 bl basic::pause @stackempty locals .ret.382: @stackempty locals inline__P382_end: pop {pc} @stackempty func @stackempty args ; ; Function handleIncomingUARTData ; .section code .balign 4 handleIncomingUARTData__P383_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl handleIncomingUARTData__P383 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code handleIncomingUARTData__P383: @stackmark func @stackmark args push {lr} movs r0, #0 push {r0} ;loc push {r0} ;loc push {r0} ;loc push {r0} ;loc push {r0} ;loc @stackmark locals handleIncomingUARTData__P383_locals: ldr r0, [r6, #20] bl _pxt_incr_pushR0 @dummystack 1 bl _conv_4 bl bluetooth::uartReadUntil bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 bl _conv_4 bl String_::length bl _clr1_1 @dummystack -1 bl _numops_fromInt movs r1, #7 bl _cmp_lt beq .else_0_10 .jmpz80: b .ret.383 .else_0_10: .afterif_1_10: bl _pxt_incr_pushR0_0 @dummystack 1 bl _conv_4 movs r1, #0 movs r2, #3 bl String_::substr bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_8 pop {r0} ; tmpref @1 str r0, [sp, locals@1] @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 bl String_::length bl _clr1_1 @dummystack -1 bl _numops_fromInt movs r1, #7 bl _numops_subs push {r0} ; proc-arg bl _conv_10 movs r1, #3 bl String_::substr bl _clr2_2 @dummystack -2 push {r0}; tmpstore @1 bl _pxt_decr_12 pop {r0} ; tmpref @1 str r0, [sp, locals@2] @stackempty locals ldr r0, [r6, #12] bl _pxt_incr_pushR0 @dummystack 1 bl _pxt_decr_16 pop {r0} ; tmpref @1 str r0, [sp, locals@3] @stackempty locals ldr r0, [r6, #16] bl _pxt_incr_pushR0 @dummystack 1 bl _pxt_incr_pushR0_8 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r2, [sp, #4*0] ; estack movs r1, #0 bl pxtrt::stfldRef add sp, #4*2 ; pop locals 2 @stackempty locals ldr r0, [r6, #16] bl _pxt_incr_pushR0 @dummystack 1 bl _pxt_incr_pushR0_12 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r2, [sp, #4*0] ; estack movs r1, #1 bl pxtrt::stfldRef add sp, #4*2 ; pop locals 2 @stackempty locals bl _pxt_incr_pushR0_12 @dummystack 1 ldr r0, [sp, #4*0] ; estack movs r1, #6 bl langsupp::ptreq bl _clr1_1 @dummystack -1 bl numops::toBoolDecr cmp r0, #0 beq .else_2_10 .jmpz81: bl _pxt_incr_24 bl numops::toBoolDecr cmp r0, #0 beq .else_3_10 .jmpz82: bl _pxt_incr_pushR0_4 @dummystack 1 bl _pxt_incr_pushR0_12 @dummystack 1 pop {r1, r2} push {r1} push {r2} bl handleMessage__P391 _proccall83: bl _clr2_2 @dummystack -2 @stackempty locals .else_3_10: .afterif_4_10: b .afterif_5_10 .else_2_10: bl _pxt_decr_16 movs r0, #10 str r0, [sp, locals@4] @stackempty locals .cont.393: bl _pxt_incr_pushR0_12 @dummystack 1 ldr r0, [sp, #4*0] ; estack movs r1, #6 bl langsupp::ptrneq bl _clr1_1 @dummystack -1 bl numops::toBoolDecr cmp r0, #0 beq .brk.393 .jmpz84: bl _pxt_incr_12 movs r1, #0 bl pxtrt::ldfldRef push {r0} ; proc-arg bl _pxt_incr_pushR0_8 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl langsupp::ptreq bl _clr2_2 @dummystack -2 bl numops::toBoolDecr cmp r0, #0 beq .else_6_10 .jmpz85: bl _pxt_incr_12 movs r1, #1 bl pxtrt::ldfldRef push {r0} ; proc-arg ldr r0, [r6, #16] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl pxt::runAction1 bl _clr2_2 @dummystack -2 @stackempty locals bl _pxt_decr_16 movs r0, #66 str r0, [sp, locals@4] @stackempty locals b .afterif_7_10 .else_6_10: bl _pxt_incr_12 movs r1, #0 bl pxtrt::ldfldRef push {r0} ; proc-arg ldr r1, _ldlit_12 bl langsupp::ptreq bl _clr1_1 @dummystack -1 bl numops::toBoolDecr cmp r0, #0 beq .else_8_10 .jmpz86: bl _pxt_incr_12 movs r1, #1 bl pxtrt::ldfldRef push {r0} ; proc-arg ldr r0, [r6, #16] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl pxt::runAction1 bl _clr2_2 @dummystack -2 @stackempty locals bl _pxt_decr_16 movs r0, #66 str r0, [sp, locals@4] @stackempty locals .else_8_10: .afterif_9_10: .afterif_7_10: bl _pxt_incr_12 movs r1, #2 bl pxtrt::ldfldRef push {r0}; tmpstore @1 bl _pxt_decr_16 pop {r0} ; tmpref @1 str r0, [sp, locals@3] @stackempty locals b .cont.393 .brk.393: bl _pxt_incr_16 bl numops::toBoolDecr bl Boolean_::bang bl pxt::fromBool push {r0}; tmpstore @1 bl numops::toBool cmp r0, #0 bne .lazySkip_12_10 .jmpz87: ldr r0, [sp, #4*0] ; tmpref @1 @dummystack 1 add sp, #4*1 ; pop locals 1 b .lazy_11_10 .lazySkip_12_10: ldr r0, [sp, #0] ldr r0, [sp, #4*0] ; estack bl _clr1_1 @dummystack -1 bl _pxt_incr_24 .lazy_11_10: ; jmp value (already in r0) bl numops::toBoolDecr cmp r0, #0 beq .else_10_10 .jmpz88: bl _pxt_incr_pushR0_4 @dummystack 1 bl _pxt_incr_pushR0_12 @dummystack 1 pop {r1, r2} push {r1} push {r2} bl handleMessage__P391 _proccall89: bl _clr2_2 @dummystack -2 @stackempty locals .else_10_10: .afterif_13_10: .afterif_5_10: .ret.383: @stackempty locals bl _pxt_decr_0 bl _pxt_decr_4 bl _pxt_decr_8 bl _pxt_decr_12 bl _pxt_decr_16 add sp, #4*5 ; pop locals 5 handleIncomingUARTData__P383_end: pop {pc} @stackempty func @stackempty args ; ; Function handleMessage ; .section code .balign 4 handleMessage__P391_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 6 bl _lambda_setup_5 bl handleMessage__P391 add sp, #4*2 ; pop locals 2 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code handleMessage__P391: @stackmark func @stackmark args push {lr} @stackmark locals handleMessage__P391_locals: bl _pxt_incr_pushR0_4 @dummystack 1 mov r1, r0 ldr r0, _ldlit_13 bl pxt::switch_eq cmp r0, #0 beq .jmpz90 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_0_11 .balign 4 _ldlit_10: .word inline__P433_Lit _ldlit_11: .word inline__P435_Lit _ldlit_12: .word _str63meta _ldlit_13: .word _str46meta .jmpz90: ldr r0, _ldlit_15 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz91 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_1_11 .jmpz91: ldr r0, _ldlit_16 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz92 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_2_11 .jmpz92: ldr r0, _ldlit_17 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz93 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_3_11 .jmpz93: ldr r0, _ldlit_18 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz94 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_4_11 .jmpz94: ldr r0, _ldlit_19 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz95 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_5_11 .jmpz95: ldr r0, _ldlit_20 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz96 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_6_11 .jmpz96: ldr r0, _ldlit_21 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz97 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_7_11 .jmpz97: ldr r0, _ldlit_22 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz98 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_8_11 .jmpz98: ldr r0, _ldlit_23 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz99 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_9_11 .jmpz99: bl _pxt_decr_0 pop {r0} ; tmpref @1 b .switch_10_11 .switch_0_11: bl _pxt_incr_pushR0_8 @dummystack 1 bl _conv_4 movs r1, #150 bl basic::showString bl _clr1_1 @dummystack -1 @stackempty locals b .brk.396 .switch_1_11: bl control::reset @stackempty locals b .brk.396 .switch_2_11: bl _pxt_incr_pushR0_8 @dummystack 1 bl parseInt__P114 _proccall100: bl _clr1_1 @dummystack -1 mov r3, r0 movs r0, #4 lsls r0, r0, #8 adds r0, #177 push {r0} ; proc-arg push {r3} ; the one arg bl showIcon__P184 _proccall101: bl _clr2_2 @dummystack -2 @stackempty locals ldr r0, _ldlit_24 push {r0} ; proc-arg bl ledOnBoard__P397 _proccall102: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.396 .switch_3_11: bl _pxt_incr_pushR0_8 @dummystack 1 bl ledOnBoard__P397 _proccall103: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.396 .switch_4_11: bl _pxt_incr_pushR0_8 @dummystack 1 bl playMusic__P398 _proccall104: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.396 .switch_5_11: bl _pxt_incr_pushR0_4 @dummystack 1 bl input::lightLevel bl _numops_fromInt push {r0} ; proc-arg bl _conv_11 bl String_::concat bl _clr2_2 @dummystack -2 push {r0} ; the one arg bl sendSuperMessage__P399 _proccall105: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.396 .switch_6_11: bl _pxt_incr_pushR0_4 @dummystack 1 bl _pxt_incr_pushR0_12 @dummystack 1 bl _conv_11 bl String_::concat bl _clr2_2 @dummystack -2 push {r0} ; proc-arg bl _pxt_incr_pushR0_12 @dummystack 1 bl parseInt__P114 _proccall106: bl _clr1_1 @dummystack -1 push {r0} ; proc-arg bl _conv_12 bl input::acceleration bl _clr1_1 @dummystack -1 bl _numops_fromInt push {r0} ; proc-arg bl _conv_11 bl String_::concat bl _clr2_2 @dummystack -2 push {r0} ; the one arg bl sendSuperMessage__P399 _proccall107: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.396 .switch_7_11: bl _pxt_incr_pushR0_4 @dummystack 1 bl _pxt_incr_pushR0_12 @dummystack 1 bl _conv_11 bl String_::concat bl _clr2_2 @dummystack -2 push {r0} ; proc-arg bl _pxt_incr_pushR0_12 @dummystack 1 bl parseInt__P114 _proccall108: bl _clr1_1 @dummystack -1 push {r0} ; proc-arg bl _conv_12 bl input::magneticForce bl _clr1_1 @dummystack -1 bl _numops_fromInt push {r0} ; proc-arg bl _conv_11 bl String_::concat bl _clr2_2 @dummystack -2 push {r0} ; the one arg bl sendSuperMessage__P399 _proccall109: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.396 .switch_8_11: bl _pxt_incr_pushR0_4 @dummystack 1 bl input::temperature bl _numops_fromInt push {r0} ; proc-arg bl _conv_11 bl String_::concat bl _clr2_2 @dummystack -2 push {r0} ; the one arg bl sendSuperMessage__P399 _proccall110: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.396 .switch_9_11: bl setupApp__P377 _proccall111: @stackempty locals .switch_10_11: .brk.396: .ret.391: @stackempty locals handleMessage__P391_end: pop {pc} @stackempty func @stackempty args ; ; Function setupApp ; .section code .balign 4 setupApp__P377_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 4 bl _lambda_setup_0 bl setupApp__P377 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code setupApp__P377: @stackmark func @stackmark args push {lr} @stackmark locals setupApp__P377_locals: ldr r0, _ldlit_24 push {r0} ; proc-arg bl ledOnBoard__P397 _proccall112: bl _clr1_1 @dummystack -1 @stackempty locals .ret.377: @stackempty locals setupApp__P377_end: pop {pc} @stackempty func @stackempty args ; ; Function sendSuperMessage ; .section code .balign 4 sendSuperMessage__P399_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl sendSuperMessage__P399 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code sendSuperMessage__P399: @stackmark func @stackmark args push {lr} @stackmark locals sendSuperMessage__P399_locals: ldr r0, [r6, #24] bl _pxt_incr bl numops::toBoolDecr cmp r0, #0 beq .else_0_13 .jmpz113: bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 movs r1, #0 movs r2, #20 bl String_::substr bl _clr1_1 @dummystack -1 push {r0} ; proc-arg bl _conv_4 bl bluetooth::uartWriteString bl _clr1_1 @dummystack -1 @stackempty locals .else_0_13: .afterif_1_13: .ret.399: @stackempty locals sendSuperMessage__P399_end: pop {pc} @stackempty func @stackempty args ; ; Function playMusic ; .section code .balign 4 playMusic__P398_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl playMusic__P398 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code playMusic__P398: @stackmark func @stackmark args push {lr} movs r0, #0 push {r0} ;loc push {r0} ;loc push {r0} ;loc push {r0} ;loc push {r0} ;loc @stackmark locals playMusic__P398_locals: bl _pxt_incr_pushR0_24 @dummystack 1 bl _conv_4 movs r1, #0 movs r2, #4 bl String_::substr bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals bl _pxt_incr_pushR0_24 @dummystack 1 bl _pxt_incr_pushR0_28 @dummystack 1 bl _conv_4 bl String_::length bl _clr1_1 @dummystack -1 bl _numops_fromInt movs r1, #9 bl _numops_subs push {r0} ; proc-arg bl _conv_10 movs r1, #4 bl String_::substr bl _clr2_2 @dummystack -2 push {r0}; tmpstore @1 bl _pxt_decr_8 pop {r0} ; tmpref @1 str r0, [sp, locals@1] @stackempty locals bl _pxt_incr_pushR0_4 @dummystack 1 bl _pxt_decr_12 pop {r0} ; tmpref @1 str r0, [sp, locals@2] @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 mov r1, r0 ldr r0, _ldlit_25 bl pxt::switch_eq cmp r0, #0 beq .jmpz114 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_0_14 .jmpz114: ldr r0, _ldlit_26 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz115 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_1_14 .balign 4 _ldlit_15: .word _str47meta _ldlit_16: .word _str48meta _ldlit_17: .word _str49meta _ldlit_18: .word _str50meta _ldlit_19: .word _str51meta _ldlit_20: .word _str52meta _ldlit_21: .word _str53meta _ldlit_22: .word _str54meta _ldlit_23: .word _str55meta _ldlit_24: .word _str45meta _ldlit_25: .word _str56meta _ldlit_26: .word _str57meta .jmpz115: ldr r0, _ldlit_28 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz116 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_2_14 .jmpz116: ldr r0, _ldlit_29 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz117 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_3_14 .jmpz117: ldr r0, _ldlit_30 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz118 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_4_14 .jmpz118: bl _pxt_decr_0 pop {r0} ; tmpref @1 b .brk.405 .switch_0_14: bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 bl String_::length bl _clr1_1 @dummystack -1 bl _numops_fromInt movs r1, #11 bl _cmp_gt beq .else_5_14 .jmpz119: bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 movs r1, #0 movs r2, #4 bl String_::substr bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_12 pop {r0} ; tmpref @1 str r0, [sp, locals@2] @stackempty locals bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 movs r1, #5 movs r2, #1 bl String_::substr bl _clr1_1 @dummystack -1 push {r0} ; the one arg bl parseInt__P114 _proccall120: bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_16 pop {r0} ; tmpref @1 str r0, [sp, locals@3] @stackempty locals bl _pxt_incr_12 movs r1, #1 bl _cmp_gt beq .condexprz_6_14 .jmpz121: bl _pxt_incr_12 b .condexprfin_7_14 .condexprz_6_14: ldr r0, [r6, #28] bl _pxt_incr .condexprfin_7_14: ; jmp value (already in r0) push {r0}; tmpstore @1 ldr r0, [r6, #28] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #28] @stackempty locals .else_5_14: .afterif_8_14: bl _pxt_incr_pushR0_8 @dummystack 1 bl parseInt__P114 _proccall122: bl _clr1_1 @dummystack -1 push {r0} ; proc-arg ldr r0, [r6, #28] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [r6, #32] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl numops::muls bl _clr2_2 @dummystack -2 push {r0} ; proc-arg pop {r1, r2} push {r1} push {r2} bl playTone__P286 _proccall123: bl _clr2_2 @dummystack -2 @stackempty locals b .brk.405 .switch_1_14: bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 bl String_::length bl _clr1_1 @dummystack -1 bl _numops_fromInt movs r1, #11 bl _cmp_gt beq .else_9_14 .jmpz124: bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 movs r1, #0 movs r2, #4 bl String_::substr bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_12 pop {r0} ; tmpref @1 str r0, [sp, locals@2] @stackempty locals bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 movs r1, #5 movs r2, #1 bl String_::substr bl _clr1_1 @dummystack -1 push {r0} ; the one arg bl parseInt__P114 _proccall125: bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_20 pop {r0} ; tmpref @1 str r0, [sp, locals@4] @stackempty locals bl _pxt_incr_16 movs r1, #1 bl _cmp_gt beq .condexprz_10_14 .jmpz126: bl _pxt_incr_16 b .condexprfin_11_14 .condexprz_10_14: ldr r0, [r6, #28] bl _pxt_incr .condexprfin_11_14: ; jmp value (already in r0) push {r0}; tmpstore @1 ldr r0, [r6, #28] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #28] @stackempty locals .else_9_14: .afterif_12_14: bl input::runningTime bl _numops_fromInt push {r0}; tmpstore @1 ldr r0, [r6, #36] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #36] @stackempty locals bl _pxt_incr_pushR0_8 @dummystack 1 bl parseInt__P114 _proccall127: bl _clr1_1 @dummystack -1 push {r0} ; the one arg bl ringTone__P287 _proccall128: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.405 .switch_2_14: ldr r0, [r6, #32] bl _pxt_incr movs r1, #1 bl _cmp_gt beq .else_13_14 .jmpz129: ldr r0, [r6, #32] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [r6, #28] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl numops::muls bl _clr2_2 @dummystack -2 push {r0} ; proc-arg bl input::runningTime bl _numops_fromInt push {r0} ; proc-arg ldr r0, [r6, #36] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl _numops_subs add sp, #4*2 ; pop locals 2 push {r0} ; proc-arg ldr r0, [r6, #32] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl numops::mod bl _clr2_2 @dummystack -2 push {r0} ; proc-arg ldr r0, [sp, #4*1] ; estack ldr r1, [sp, #4*0] ; estack bl _numops_subs add sp, #4*2 ; pop locals 2 push {r0} ; proc-arg bl _conv_12 bl basic::pause bl _clr1_1 @dummystack -1 @stackempty locals .else_13_14: .afterif_14_14: movs r0, #3 push {r0} ; proc-arg bl rest__P288 _proccall130: bl _clr1_1 @dummystack -1 @stackempty locals b .brk.405 .switch_3_14: bl _pxt_incr_pushR0_4 @dummystack 1 bl parseInt__P114 _proccall132: bl _clr1_1 @dummystack -1 movs r1, #1 bl _cmp_ge beq .condexprz_15_14 .jmpz131: bl _pxt_incr_pushR0_4 @dummystack 1 bl parseInt__P114 _proccall133: bl _clr1_1 @dummystack -1 b .condexprfin_16_14 .condexprz_15_14: ldr r0, [r6, #32] bl _pxt_incr .condexprfin_16_14: ; jmp value (already in r0) push {r0}; tmpstore @1 ldr r0, [r6, #32] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #32] @stackempty locals b .brk.405 .switch_4_14: bl _pxt_incr_pushR0_4 @dummystack 1 bl parseInt__P114 _proccall135: bl _clr1_1 @dummystack -1 movs r1, #1 bl _cmp_ge beq .condexprz_17_14 .jmpz134: bl _pxt_incr_pushR0_4 @dummystack 1 bl parseInt__P114 _proccall136: bl _clr1_1 @dummystack -1 b .condexprfin_18_14 .condexprz_17_14: ldr r0, [r6, #28] bl _pxt_incr .condexprfin_18_14: ; jmp value (already in r0) push {r0}; tmpstore @1 ldr r0, [r6, #28] bl _pxt_decr pop {r0} ; tmpref @1 str r0, [r6, #28] @stackempty locals .brk.405: .ret.398: @stackempty locals bl _pxt_decr_0 bl _pxt_decr_4 bl _pxt_decr_8 bl _pxt_decr_12 bl _pxt_decr_16 add sp, #4*5 ; pop locals 5 playMusic__P398_end: pop {pc} @stackempty func @stackempty args ; ; Function rest ; .section code .balign 4 rest__P288_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl rest__P288 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code rest__P288: @stackmark func @stackmark args push {lr} @stackmark locals rest__P288_locals: bl _pxt_incr_pushR0_4 @dummystack 1 movs r0, #1 push {r0} ; proc-arg bl playTone__P286 _proccall137: bl _clr2_2 @dummystack -2 @stackempty locals .ret.288: @stackempty locals rest__P288_end: pop {pc} .balign 4 _ldlit_28: .word _str58meta _ldlit_29: .word _str59meta _ldlit_30: .word _str60meta @stackempty func @stackempty args ; ; Function ringTone ; .section code .balign 4 ringTone__P287_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl ringTone__P287 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code ringTone__P287: @stackmark func @stackmark args push {lr} @stackmark locals ringTone__P287_locals: bl _pxt_incr_4 mov r3, r0 movs r0, #1 push {r0} ; proc-arg push {r3} ; the one arg bl playTone__P286 _proccall138: bl _clr2_2 @dummystack -2 @stackempty locals .ret.287: @stackempty locals ringTone__P287_end: pop {pc} @stackempty func @stackempty args ; ; Function ledOnBoard ; .section code .balign 4 ledOnBoard__P397_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl ledOnBoard__P397 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code ledOnBoard__P397: @stackmark func @stackmark args push {lr} movs r0, #0 push {r0} ;loc push {r0} ;loc push {r0} ;loc push {r0} ;loc push {r0} ;loc @stackmark locals ledOnBoard__P397_locals: bl _pxt_incr_pushR0_24 @dummystack 1 bl _conv_4 movs r1, #0 movs r2, #3 bl String_::substr bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals bl _pxt_incr_pushR0_24 @dummystack 1 bl _pxt_incr_pushR0_28 @dummystack 1 bl _conv_4 bl String_::length bl _clr1_1 @dummystack -1 bl _numops_fromInt movs r1, #7 bl _numops_subs push {r0} ; proc-arg bl _conv_10 movs r1, #3 bl String_::substr bl _clr2_2 @dummystack -2 push {r0}; tmpstore @1 bl _pxt_decr_8 pop {r0} ; tmpref @1 str r0, [sp, locals@1] @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 mov r1, r0 ldr r0, _ldlit_32 bl pxt::switch_eq cmp r0, #0 beq .jmpz139 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_0_17 .jmpz139: ldr r0, _ldlit_33 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz140 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_1_17 .jmpz140: bl _pxt_decr_0 pop {r0} ; tmpref @1 b .brk.416 .switch_0_17: bl getLedPlots__P417 _proccall141: push {r0} ; proc-arg bl _conv_13 ldr r0, _ldlit_32 bl String_::concat bl _clr1_1 @dummystack -1 push {r0} ; proc-arg bl _conv_4 bl bluetooth::uartWriteString bl _clr1_1 @dummystack -1 @stackempty locals b .brk.416 .switch_1_17: bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 movs r1, #0 movs r2, #1 bl String_::substr bl _clr1_1 @dummystack -1 push {r0} ; the one arg bl parseInt__P114 _proccall142: bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_12 pop {r0} ; tmpref @1 str r0, [sp, locals@2] @stackempty locals bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 movs r1, #1 movs r2, #1 bl String_::substr bl _clr1_1 @dummystack -1 push {r0} ; the one arg bl parseInt__P114 _proccall143: bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_16 pop {r0} ; tmpref @1 str r0, [sp, locals@3] @stackempty locals bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 movs r1, #2 movs r2, #1 bl String_::substr bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_20 pop {r0} ; tmpref @1 str r0, [sp, locals@4] @stackempty locals bl _pxt_incr_pushR0_16 @dummystack 1 ldr r0, [sp, #4*0] ; estack ldr r1, _ldlit_34 bl langsupp::ptreq bl _clr1_1 @dummystack -1 bl numops::toBoolDecr cmp r0, #0 beq .else_2_17 .jmpz144: bl _pxt_incr_pushR0_8 @dummystack 1 bl _pxt_incr_pushR0_16 @dummystack 1 bl _conv_7 bl led::plot bl _clr2_2 @dummystack -2 @stackempty locals b .afterif_3_17 .else_2_17: bl _pxt_incr_pushR0_8 @dummystack 1 bl _pxt_incr_pushR0_16 @dummystack 1 bl _conv_7 bl led::unplot bl _clr2_2 @dummystack -2 @stackempty locals .afterif_3_17: bl getLedPlots__P417 _proccall145: push {r0} ; proc-arg bl _conv_13 ldr r0, _ldlit_32 bl String_::concat bl _clr1_1 @dummystack -1 push {r0} ; proc-arg bl _conv_4 bl bluetooth::uartWriteString bl _clr1_1 @dummystack -1 @stackempty locals .brk.416: .ret.397: @stackempty locals bl _pxt_decr_0 bl _pxt_decr_4 bl _pxt_decr_8 bl _pxt_decr_12 bl _pxt_decr_16 add sp, #4*5 ; pop locals 5 ledOnBoard__P397_end: pop {pc} @stackempty func @stackempty args ; ; Function getLedPlots ; .section code .balign 4 getLedPlots__P417_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 4 bl _lambda_setup_0 bl getLedPlots__P417 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code getLedPlots__P417: @stackmark func @stackmark args push {lr} movs r0, #0 push {r0} ;loc push {r0} ;loc push {r0} ;loc @stackmark locals getLedPlots__P417_locals: bl _pxt_decr_0 movs r0, #1 str r0, [sp, locals@0] @stackempty locals bl _pxt_decr_4 movs r0, #1 str r0, [sp, locals@1] @stackempty locals .fortop.423: bl _pxt_incr_4 movs r1, #11 bl _cmp_lt beq .brk.423 .jmpz146: bl _pxt_decr_8 movs r0, #1 str r0, [sp, locals@2] @stackempty locals .fortop.425: bl _pxt_incr_8 movs r1, #11 bl _cmp_lt beq .brk.425 .jmpz147: bl _pxt_incr_pushR0_0 @dummystack 1 ldr r0, [sp, #4*0] ; estack movs r1, #5 bl numops::muls bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals bl _pxt_incr_pushR0_4 @dummystack 1 bl _pxt_incr_pushR0_12 @dummystack 1 bl _conv_7 bl led::point bl _clr2_2 @dummystack -2 bl pxt::fromBool bl numops::toBoolDecr cmp r0, #0 beq .else_0_18 .jmpz148: bl _pxt_incr_0 movs r1, #3 bl _numops_adds push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals .else_0_18: .afterif_1_18: .cont.425: bl _pxt_incr_8 movs r1, #3 bl _numops_adds push {r0}; tmpstore @1 bl _pxt_decr_12 pop {r0} ; tmpref @1 str r0, [sp, locals@2] @stackempty locals b .fortop.425 .brk.425: .cont.423: bl _pxt_incr_4 movs r1, #3 bl _numops_adds push {r0}; tmpstore @1 bl _pxt_decr_8 pop {r0} ; tmpref @1 str r0, [sp, locals@1] @stackempty locals b .fortop.423 .brk.423: bl _pxt_incr_0 .ret.417: @stackempty locals ; jmp value (already in r0) push {r0}; tmpstore @1 bl _pxt_decr_4 bl _pxt_decr_8 bl _pxt_decr_12 pop {r0} ; tmpref @1 .final_2_18: add sp, #4*3 ; pop locals 3 getLedPlots__P417_end: pop {pc} @stackempty func @stackempty args ; ; Function parseInt ; .section code .balign 4 parseInt__P114_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl parseInt__P114 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code parseInt__P114: @stackmark func @stackmark args push {lr} @stackmark locals parseInt__P114_locals: bl _pxt_incr_pushR0_4 @dummystack 1 bl _conv_4 bl String_::toNumber bl _clr1_1 @dummystack -1 push {r0} ; proc-arg movs r1, #1 bl numops::asrs bl _clr1_1 @dummystack -1 .ret.114: @stackempty locals ; jmp value (already in r0) .final_0_19: parseInt__P114_end: pop {pc} @stackempty func @stackempty args ; ; Function showIcon ; .section code .balign 4 showIcon__P184_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 6 bl _lambda_setup_5 bl showIcon__P184 add sp, #4*2 ; pop locals 2 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code showIcon__P184: @stackmark func @stackmark args push {lr} movs r0, #0 push {r0} ;loc @stackmark locals showIcon__P184_locals: bl _pxt_incr_pushR0_8 @dummystack 1 bl iconImage__P187 _proccall149: bl _clr1_1 @dummystack -1 push {r0}; tmpstore @1 bl _pxt_decr_4 pop {r0} ; tmpref @1 str r0, [sp, locals@0] @stackempty locals bl _pxt_incr_pushR0_0 @dummystack 1 bl _pxt_incr_pushR0_16 @dummystack 1 bl _conv_14 movs r1, #0 bl ImageMethods::showImage bl _clr2_2 @dummystack -2 @stackempty locals .ret.184: @stackempty locals bl _pxt_decr_0 add sp, #4*1 ; pop locals 1 showIcon__P184_end: pop {pc} @stackempty func @stackempty args ; ; Function iconImage ; .section code .balign 4 iconImage__P187_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 5 bl _lambda_setup_3 bl iconImage__P187 add sp, #4*1 ; pop locals 1 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code iconImage__P187: @stackmark func @stackmark args push {lr} @stackmark locals iconImage__P187_locals: bl _pxt_incr_pushR0_4 @dummystack 1 mov r1, r0 movs r0, #1 bl pxt::switch_eq cmp r0, #0 beq .jmpz150 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_0_21 .jmpz150: movs r0, #3 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz151 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_1_21 .balign 4 _ldlit_32: .word _str45meta _ldlit_33: .word _str61meta _ldlit_34: .word _str62meta .jmpz151: movs r0, #9 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz152 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_2_21 .jmpz152: movs r0, #11 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz153 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_3_21 .jmpz153: movs r0, #13 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz154 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_4_21 .jmpz154: movs r0, #15 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz155 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_5_21 .jmpz155: movs r0, #17 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz156 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_6_21 .jmpz156: movs r0, #19 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz157 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_7_21 .jmpz157: movs r0, #21 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz158 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_8_21 .jmpz158: movs r0, #23 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz159 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_9_21 .jmpz159: movs r0, #25 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz160 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_10_21 .jmpz160: movs r0, #5 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz161 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_11_21 .jmpz161: movs r0, #7 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz162 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_12_21 .jmpz162: movs r0, #65 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz163 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_13_21 .jmpz163: movs r0, #67 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz164 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_14_21 .jmpz164: movs r0, #69 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz165 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_15_21 .jmpz165: movs r0, #71 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz166 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_16_21 .jmpz166: movs r0, #73 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz167 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_17_21 .jmpz167: movs r0, #75 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz168 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_18_21 .jmpz168: movs r0, #77 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz169 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_19_21 .jmpz169: movs r0, #79 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz170 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_20_21 .jmpz170: movs r0, #27 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz171 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_21_21 .jmpz171: movs r0, #29 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz172 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_22_21 .jmpz172: movs r0, #31 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz173 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_23_21 .jmpz173: movs r0, #33 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz174 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_24_21 .jmpz174: movs r0, #35 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz175 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_25_21 .jmpz175: movs r0, #37 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz176 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_26_21 .jmpz176: movs r0, #39 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz177 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_27_21 .jmpz177: movs r0, #41 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz178 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_28_21 .jmpz178: movs r0, #43 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz179 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_29_21 .jmpz179: movs r0, #45 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz180 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_30_21 .jmpz180: movs r0, #47 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz181 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_31_21 .jmpz181: movs r0, #49 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz182 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_32_21 .jmpz182: movs r0, #51 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz183 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_33_21 .jmpz183: movs r0, #53 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz184 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_34_21 .jmpz184: movs r0, #55 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz185 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_35_21 .jmpz185: movs r0, #57 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz186 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_36_21 .jmpz186: movs r0, #59 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz187 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_37_21 .jmpz187: movs r0, #61 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz188 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_38_21 .jmpz188: movs r0, #63 ldr r1, [sp, #4*0] ; tmpref @1 bl pxt::switch_eq cmp r0, #0 beq .jmpz189 @dummystack 1 add sp, #4*1 ; pop locals 1 b .switch_39_21 .jmpz189: bl _pxt_decr_0 pop {r0} ; tmpref @1 b .switch_40_21 .switch_0_21: movs r0, _img0@hi ; ldptr lsls r0, r0, #8 adds r0, _img0@lo bl images::createImage b .ret.187 .switch_1_21: movs r0, _img1@hi ; ldptr lsls r0, r0, #8 adds r0, _img1@lo bl images::createImage b .ret.187 .switch_2_21: movs r0, _img2@hi ; ldptr lsls r0, r0, #8 adds r0, _img2@lo bl images::createImage b .ret.187 .switch_3_21: movs r0, _img3@hi ; ldptr lsls r0, r0, #8 adds r0, _img3@lo bl images::createImage b .ret.187 .switch_4_21: movs r0, _img4@hi ; ldptr lsls r0, r0, #8 adds r0, _img4@lo bl images::createImage b .ret.187 .switch_5_21: movs r0, _img5@hi ; ldptr lsls r0, r0, #8 adds r0, _img5@lo bl images::createImage b .ret.187 .switch_6_21: movs r0, _img6@hi ; ldptr lsls r0, r0, #8 adds r0, _img6@lo bl images::createImage b .ret.187 .switch_7_21: movs r0, _img7@hi ; ldptr lsls r0, r0, #8 adds r0, _img7@lo bl images::createImage b .ret.187 .switch_8_21: movs r0, _img8@hi ; ldptr lsls r0, r0, #8 adds r0, _img8@lo bl images::createImage b .ret.187 .switch_9_21: movs r0, _img9@hi ; ldptr lsls r0, r0, #8 adds r0, _img9@lo bl images::createImage b .ret.187 .switch_10_21: movs r0, _img10@hi ; ldptr lsls r0, r0, #8 adds r0, _img10@lo bl images::createImage b .ret.187 .switch_11_21: movs r0, _img11@hi ; ldptr lsls r0, r0, #8 adds r0, _img11@lo bl images::createImage b .ret.187 .switch_12_21: movs r0, _img12@hi ; ldptr lsls r0, r0, #8 adds r0, _img12@lo bl images::createImage b .ret.187 .switch_13_21: movs r0, _img13@hi ; ldptr lsls r0, r0, #8 adds r0, _img13@lo bl images::createImage b .ret.187 .switch_14_21: movs r0, _img14@hi ; ldptr lsls r0, r0, #8 adds r0, _img14@lo bl images::createImage b .ret.187 .switch_15_21: movs r0, _img15@hi ; ldptr lsls r0, r0, #8 adds r0, _img15@lo bl images::createImage b .ret.187 .switch_16_21: movs r0, _img16@hi ; ldptr lsls r0, r0, #8 adds r0, _img16@lo bl images::createImage b .ret.187 .switch_17_21: movs r0, _img17@hi ; ldptr lsls r0, r0, #8 adds r0, _img17@lo bl images::createImage b .ret.187 .switch_18_21: movs r0, _img18@hi ; ldptr lsls r0, r0, #8 adds r0, _img18@lo bl images::createImage b .ret.187 .switch_19_21: movs r0, _img19@hi ; ldptr lsls r0, r0, #8 adds r0, _img19@lo bl images::createImage b .ret.187 .switch_20_21: movs r0, _img20@hi ; ldptr lsls r0, r0, #8 adds r0, _img20@lo bl images::createImage b .ret.187 .switch_21_21: movs r0, _img21@hi ; ldptr lsls r0, r0, #8 adds r0, _img21@lo bl images::createImage b .ret.187 .switch_22_21: movs r0, _img22@hi ; ldptr lsls r0, r0, #8 adds r0, _img22@lo bl images::createImage b .ret.187 .switch_23_21: movs r0, _img23@hi ; ldptr lsls r0, r0, #8 adds r0, _img23@lo bl images::createImage b .ret.187 .switch_24_21: movs r0, _img24@hi ; ldptr lsls r0, r0, #8 adds r0, _img24@lo bl images::createImage b .ret.187 .switch_25_21: movs r0, _img25@hi ; ldptr lsls r0, r0, #8 adds r0, _img25@lo bl images::createImage b .ret.187 .switch_26_21: movs r0, _img26@hi ; ldptr lsls r0, r0, #8 adds r0, _img26@lo bl images::createImage b .ret.187 .switch_27_21: movs r0, _img27@hi ; ldptr lsls r0, r0, #8 adds r0, _img27@lo bl images::createImage b .ret.187 .switch_28_21: movs r0, _img28@hi ; ldptr lsls r0, r0, #8 adds r0, _img28@lo bl images::createImage b .ret.187 .switch_29_21: movs r0, _img29@hi ; ldptr lsls r0, r0, #8 adds r0, _img29@lo bl images::createImage b .ret.187 .switch_30_21: movs r0, _img30@hi ; ldptr lsls r0, r0, #8 adds r0, _img30@lo bl images::createImage b .ret.187 .switch_31_21: movs r0, _img31@hi ; ldptr lsls r0, r0, #8 adds r0, _img31@lo bl images::createImage b .ret.187 .switch_32_21: movs r0, _img32@hi ; ldptr lsls r0, r0, #8 adds r0, _img32@lo bl images::createImage b .ret.187 .switch_33_21: movs r0, _img33@hi ; ldptr lsls r0, r0, #8 adds r0, _img33@lo bl images::createImage b .ret.187 .switch_34_21: movs r0, _img34@hi ; ldptr lsls r0, r0, #8 adds r0, _img34@lo bl images::createImage b .ret.187 .switch_35_21: movs r0, _img35@hi ; ldptr lsls r0, r0, #8 adds r0, _img35@lo bl images::createImage b .ret.187 .switch_36_21: movs r0, _img36@hi ; ldptr lsls r0, r0, #8 adds r0, _img36@lo bl images::createImage b .ret.187 .switch_37_21: movs r0, _img37@hi ; ldptr lsls r0, r0, #8 adds r0, _img37@lo bl images::createImage b .ret.187 .switch_38_21: movs r0, _img38@hi ; ldptr lsls r0, r0, #8 adds r0, _img38@lo bl images::createImage b .ret.187 .switch_39_21: movs r0, _img39@hi ; ldptr lsls r0, r0, #8 adds r0, _img39@lo bl images::createImage b .ret.187 .switch_40_21: movs r0, _img40@hi ; ldptr lsls r0, r0, #8 adds r0, _img40@lo bl images::createImage .brk.432: .ret.187: @stackempty locals ; jmp value (already in r0) .final_41_21: iconImage__P187_end: pop {pc} @stackempty func @stackempty args ; ; Function inline ; .section code .balign 4 inline__P433_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 4 bl _lambda_setup_0 bl inline__P433 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code inline__P433: @stackmark func @stackmark args push {lr} @stackmark locals inline__P433_locals: ldr r0, [r6, #24] bl _pxt_decr movs r0, #66 str r0, [r6, #24] @stackempty locals movs r0, #4 lsls r0, r0, #8 adds r0, #177 push {r0} ; proc-arg movs r0, #71 push {r0} ; proc-arg bl showIcon__P184 _proccall190: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #4 lsls r0, r0, #8 adds r0, #23 push {r0} ; proc-arg bl playTone__P286 _proccall191: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #5 lsls r0, r0, #8 adds r0, #117 push {r0} ; proc-arg bl playTone__P286 _proccall192: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #7 lsls r0, r0, #8 adds r0, #185 push {r0} ; proc-arg bl playTone__P286 _proccall193: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #10 bl basic::pause @stackempty locals ldr r0, [r6, #40] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*0] ; estack movs r1, #6 bl langsupp::ptrneq bl _clr1_1 @dummystack -1 bl numops::toBoolDecr cmp r0, #0 beq .else_0_22 .jmpz194: ldr r0, [r6, #40] bl _pxt_incr movs r1, #0 bl pxtrt::ldfldRef push {r0} ; proc-arg bl pxt::runAction0 bl _clr1_1 @dummystack -1 @stackempty locals .else_0_22: .afterif_1_22: .ret.433: @stackempty locals inline__P433_end: pop {pc} @stackempty func @stackempty args ; ; Function inline ; .section code .balign 4 inline__P435_Lit: .short 0xffff, 33 ; action literal @stackmark litfunc push {lr} @dummystack 4 bl _lambda_setup_0 bl inline__P435 pop {r4, r5, r6, r7, pc} @stackempty litfunc .section code inline__P435: @stackmark func @stackmark args push {lr} @stackmark locals inline__P435_locals: ldr r0, [r6, #24] bl _pxt_decr movs r0, #10 str r0, [r6, #24] @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #7 lsls r0, r0, #8 adds r0, #185 push {r0} ; proc-arg bl playTone__P286 _proccall195: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #5 lsls r0, r0, #8 adds r0, #117 push {r0} ; proc-arg bl playTone__P286 _proccall196: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #101 push {r0} ; proc-arg movs r0, #4 lsls r0, r0, #8 adds r0, #23 push {r0} ; proc-arg bl playTone__P286 _proccall197: bl _clr2_2 @dummystack -2 @stackempty locals movs r0, #10 bl basic::pause @stackempty locals ldr r0, [r6, #40] bl _pxt_incr_pushR0 @dummystack 1 ldr r0, [sp, #4*0] ; estack movs r1, #6 bl langsupp::ptrneq bl _clr1_1 @dummystack -1 bl numops::toBoolDecr cmp r0, #0 beq .else_0_23 .jmpz198: ldr r0, [r6, #40] bl _pxt_incr movs r1, #0 bl pxtrt::ldfldRef push {r0} ; proc-arg bl pxt::runAction0 bl _clr1_1 @dummystack -1 @stackempty locals .else_0_23: .afterif_1_23: .ret.435: @stackempty locals inline__P435_end: pop {pc} @stackempty func @stackempty args .balign 4 LinkedKeyHandlerList__C368_VT: .short 16 ; size in bytes .byte 3, 0 ; num. methods .word LinkedKeyHandlerList__C368_IfaceVT .word pxt::RefRecord_destroy@fn .word pxt::RefRecord_print@fn .word 0 .byte 1,1,1,0 .balign 4 LinkedKeyHandlerList__C368_IfaceVT: .balign 4 Message__C356_VT: .short 12 ; size in bytes .byte 3, 0 ; num. methods .word Message__C356_IfaceVT .word pxt::RefRecord_destroy@fn .word pxt::RefRecord_print@fn .word 0 .byte 1,1 .balign 4 Message__C356_IfaceVT: .section code _lambda_setup_0: push {r4, r5, r6, r7} mov r5, r0 mov r4, lr bl pxtrt::getGlobalsPtr mov r6, r0 bx r4 @dummystack -4 .section code _clr1_1: @dummystack 1 mov r7, r0 mov r4, lr pop {r0} lsls r1, r0, #30 bne .tag0 cmp r0, #0 beq .tag0 bl pxt::decr .tag0: mov r0, r7 bx r4 .section code _clr2_2: @dummystack 2 mov r7, r0 mov r4, lr pop {r0} lsls r1, r0, #30 bne .tag0 cmp r0, #0 beq .tag0 bl pxt::decr .tag0: pop {r0} lsls r1, r0, #30 bne .tag1 cmp r0, #0 beq .tag1 bl pxt::decr .tag1: mov r0, r7 bx r4 .section code _lambda_setup_3: push {r4, r5, r6, r7} push {r1} mov r5, r0 mov r4, lr bl pxtrt::getGlobalsPtr mov r6, r0 bx r4 @dummystack -5 .section code _conv_4: @stackmark args push {lr} ldr r0, [sp, #4*1] ; estack bl numops::stringConv str r0, [sp, #4*1] ; estack pop {pc} @stackempty args .section code _lambda_setup_5: push {r4, r5, r6, r7} push {r2} push {r1} mov r5, r0 mov r4, lr bl pxtrt::getGlobalsPtr mov r6, r0 bx r4 @dummystack -6 .section code _clr3_6: @dummystack 3 mov r7, r0 mov r4, lr pop {r0} lsls r1, r0, #30 bne .tag0 cmp r0, #0 beq .tag0 bl pxt::decr .tag0: pop {r0} lsls r1, r0, #30 bne .tag1 cmp r0, #0 beq .tag1 bl pxt::decr .tag1: pop {r0} lsls r1, r0, #30 bne .tag2 cmp r0, #0 beq .tag2 bl pxt::decr .tag2: mov r0, r7 bx r4 .section code _conv_7: @stackmark args push {lr} ldr r0, [sp, #4*2] ; estack bl _numops_toInt push {r0} ldr r0, [sp, #4*2] ; estack bl _numops_toInt mov r1, r0 pop {r0, pc} @stackempty args .section code _conv_8: @stackmark args push {lr} ldr r0, [sp, #4*2] ; estack bl numops::stringConv str r0, [sp, #4*2] ; estack ldr r1, [sp, #4*1] ; estack pop {pc} @stackempty args .section code _clr2_9: @dummystack 3 mov r7, r0 mov r4, lr pop {r0} lsls r1, r0, #30 bne .tag0 cmp r0, #0 beq .tag0 bl pxt::decr .tag0: pop {r0} lsls r1, r0, #30 bne .tag1 cmp r0, #0 beq .tag1 bl pxt::decr .tag1: add sp, #4*1 ; pop locals 1 mov r0, r7 bx r4 .section code _conv_10: @stackmark args push {lr} ldr r0, [sp, #4*2] ; estack bl numops::stringConv str r0, [sp, #4*2] ; estack push {r0} ldr r0, [sp, #4*2] ; estack bl _numops_toInt mov r2, r0 pop {r0, pc} @stackempty args .section code _conv_11: @stackmark args push {lr} ldr r0, [sp, #4*2] ; estack bl numops::stringConv str r0, [sp, #4*2] ; estack push {r0} ldr r0, [sp, #4*2] ; estack bl numops::stringConv str r0, [sp, #4*2] ; estack mov r1, r0 pop {r0, pc} @stackempty args .section code _conv_12: @stackmark args push {lr} ldr r0, [sp, #4*1] ; estack bl _numops_toInt pop {pc} @stackempty args .section code _conv_13: @stackmark args push {lr} ldr r0, [sp, #4*1] ; estack bl numops::stringConv str r0, [sp, #4*1] ; estack mov r1, r0 pop {pc} @stackempty args .section code _conv_14: @stackmark args push {lr} ldr r0, [sp, #4*1] ; estack bl _numops_toInt mov r2, r0 ldr r0, [sp, #4*2] ; estack pop {pc} @stackempty args _numops_adds: @scope _numops_adds lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r2, r1, #1 adds r2, r0, r2 bvs .boxed movs r0, r2 blx lr .boxed: push {r4, lr} push {r0, r1} bl numops::adds movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _numops_subs: @scope _numops_subs lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r2, r1, #1 subs r2, r0, r2 bvs .boxed movs r0, r2 blx lr .boxed: push {r4, lr} push {r0, r1} bl numops::subs movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _numops_ands: @scope _numops_ands lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed ands r0, r1 blx lr .boxed: push {r4, lr} push {r0, r1} bl numops::ands movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _numops_orrs: @scope _numops_orrs lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed orrs r0, r1 blx lr .boxed: push {r4, lr} push {r0, r1} bl numops::orrs movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _numops_eors: @scope _numops_eors lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed eors r0, r1 adds r0, r0, #1 blx lr .boxed: push {r4, lr} push {r0, r1} bl numops::eors movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} @scope _numops_toInt _numops_toInt: asrs r0, r0, #1 bcc .over blx lr .over: push {lr} lsls r0, r0, #1 bl pxt::toInt pop {pc} _numops_fromInt: lsls r2, r0, #1 asrs r1, r2, #1 cmp r0, r1 bne .over2 adds r0, r2, #1 blx lr .over2: push {lr} bl pxt::fromInt pop {pc} .section code _pxt_incr_56: ldr r0, [sp, #56] b _pxt_incr _pxt_incr_52: ldr r0, [sp, #52] b _pxt_incr _pxt_incr_48: ldr r0, [sp, #48] b _pxt_incr _pxt_incr_44: ldr r0, [sp, #44] b _pxt_incr _pxt_incr_40: ldr r0, [sp, #40] b _pxt_incr _pxt_incr_36: ldr r0, [sp, #36] b _pxt_incr _pxt_incr_32: ldr r0, [sp, #32] b _pxt_incr _pxt_incr_28: ldr r0, [sp, #28] b _pxt_incr _pxt_incr_24: ldr r0, [sp, #24] b _pxt_incr _pxt_incr_20: ldr r0, [sp, #20] b _pxt_incr _pxt_incr_16: ldr r0, [sp, #16] b _pxt_incr _pxt_incr_12: ldr r0, [sp, #12] b _pxt_incr _pxt_incr_8: ldr r0, [sp, #8] b _pxt_incr _pxt_incr_4: ldr r0, [sp, #4] b _pxt_incr _pxt_incr_0: ldr r0, [sp, #0] ; b _pxt_incr _pxt_incr: lsls r3, r0, #30 beq .t0 .skip: bx lr .t0: cmp r0, #0 beq .skip push {lr} bl pxt::incr pop {pc} _pxt_incr_pushR0_56: ldr r0, [sp, #56] b _pxt_incr_pushR0 _pxt_incr_pushR0_52: ldr r0, [sp, #52] b _pxt_incr_pushR0 _pxt_incr_pushR0_48: ldr r0, [sp, #48] b _pxt_incr_pushR0 _pxt_incr_pushR0_44: ldr r0, [sp, #44] b _pxt_incr_pushR0 _pxt_incr_pushR0_40: ldr r0, [sp, #40] b _pxt_incr_pushR0 _pxt_incr_pushR0_36: ldr r0, [sp, #36] b _pxt_incr_pushR0 _pxt_incr_pushR0_32: ldr r0, [sp, #32] b _pxt_incr_pushR0 _pxt_incr_pushR0_28: ldr r0, [sp, #28] b _pxt_incr_pushR0 _pxt_incr_pushR0_24: ldr r0, [sp, #24] b _pxt_incr_pushR0 _pxt_incr_pushR0_20: ldr r0, [sp, #20] b _pxt_incr_pushR0 _pxt_incr_pushR0_16: ldr r0, [sp, #16] b _pxt_incr_pushR0 _pxt_incr_pushR0_12: ldr r0, [sp, #12] b _pxt_incr_pushR0 _pxt_incr_pushR0_8: ldr r0, [sp, #8] b _pxt_incr_pushR0 _pxt_incr_pushR0_4: ldr r0, [sp, #4] b _pxt_incr_pushR0 _pxt_incr_pushR0_0: ldr r0, [sp, #0] ; b _pxt_incr_pushR0 _pxt_incr_pushR0: push {r0} @dummystack -1 lsls r3, r0, #30 beq .t2 .skip2: bx lr .t2: cmp r0, #0 beq .skip2 push {lr} bl pxt::incr pop {pc} .section code _pxt_decr_56: ldr r0, [sp, #56] b _pxt_decr _pxt_decr_52: ldr r0, [sp, #52] b _pxt_decr _pxt_decr_48: ldr r0, [sp, #48] b _pxt_decr _pxt_decr_44: ldr r0, [sp, #44] b _pxt_decr _pxt_decr_40: ldr r0, [sp, #40] b _pxt_decr _pxt_decr_36: ldr r0, [sp, #36] b _pxt_decr _pxt_decr_32: ldr r0, [sp, #32] b _pxt_decr _pxt_decr_28: ldr r0, [sp, #28] b _pxt_decr _pxt_decr_24: ldr r0, [sp, #24] b _pxt_decr _pxt_decr_20: ldr r0, [sp, #20] b _pxt_decr _pxt_decr_16: ldr r0, [sp, #16] b _pxt_decr _pxt_decr_12: ldr r0, [sp, #12] b _pxt_decr _pxt_decr_8: ldr r0, [sp, #8] b _pxt_decr _pxt_decr_4: ldr r0, [sp, #4] b _pxt_decr _pxt_decr_0: ldr r0, [sp, #0] ; b _pxt_decr _pxt_decr: lsls r3, r0, #30 beq .t0 .skip: bx lr .t0: cmp r0, #0 beq .skip push {lr} bl pxt::decr pop {pc} _pxt_decr_pushR0_56: ldr r0, [sp, #56] b _pxt_decr_pushR0 _pxt_decr_pushR0_52: ldr r0, [sp, #52] b _pxt_decr_pushR0 _pxt_decr_pushR0_48: ldr r0, [sp, #48] b _pxt_decr_pushR0 _pxt_decr_pushR0_44: ldr r0, [sp, #44] b _pxt_decr_pushR0 _pxt_decr_pushR0_40: ldr r0, [sp, #40] b _pxt_decr_pushR0 _pxt_decr_pushR0_36: ldr r0, [sp, #36] b _pxt_decr_pushR0 _pxt_decr_pushR0_32: ldr r0, [sp, #32] b _pxt_decr_pushR0 _pxt_decr_pushR0_28: ldr r0, [sp, #28] b _pxt_decr_pushR0 _pxt_decr_pushR0_24: ldr r0, [sp, #24] b _pxt_decr_pushR0 _pxt_decr_pushR0_20: ldr r0, [sp, #20] b _pxt_decr_pushR0 _pxt_decr_pushR0_16: ldr r0, [sp, #16] b _pxt_decr_pushR0 _pxt_decr_pushR0_12: ldr r0, [sp, #12] b _pxt_decr_pushR0 _pxt_decr_pushR0_8: ldr r0, [sp, #8] b _pxt_decr_pushR0 _pxt_decr_pushR0_4: ldr r0, [sp, #4] b _pxt_decr_pushR0 _pxt_decr_pushR0_0: ldr r0, [sp, #0] ; b _pxt_decr_pushR0 _pxt_decr_pushR0: push {r0} @dummystack -1 lsls r3, r0, #30 beq .t2 .skip2: bx lr .t2: cmp r0, #0 beq .skip2 push {lr} bl pxt::decr pop {pc} _cmp_lt: @scope _cmp_lt lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r0, r1 blt .true .false: movs r0, #0 bx lr .true: movs r0, #1 bx lr .boxed: push {r4, lr} push {r0, r1} bl numops::lt bl numops::toBoolDecr movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _cmp_gt: @scope _cmp_gt lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r0, r1 bgt .true .false: movs r0, #0 bx lr .true: movs r0, #1 bx lr .boxed: push {r4, lr} push {r0, r1} bl numops::gt bl numops::toBoolDecr movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _cmp_le: @scope _cmp_le lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r0, r1 ble .true .false: movs r0, #0 bx lr .true: movs r0, #1 bx lr .boxed: push {r4, lr} push {r0, r1} bl numops::le bl numops::toBoolDecr movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _cmp_ge: @scope _cmp_ge lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r0, r1 bge .true .false: movs r0, #0 bx lr .true: movs r0, #1 bx lr .boxed: push {r4, lr} push {r0, r1} bl numops::ge bl numops::toBoolDecr movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _cmp_eq: @scope _cmp_eq lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r0, r1 beq .true .false: movs r0, #0 bx lr .true: movs r0, #1 bx lr .boxed: push {r4, lr} push {r0, r1} bl numops::eq bl numops::toBoolDecr movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _cmp_eqq: @scope _cmp_eqq lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r0, r1 beq .true .false: movs r0, #0 bx lr .true: movs r0, #1 bx lr .boxed: push {r4, lr} push {r0, r1} bl numops::eqq bl numops::toBoolDecr movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _cmp_neq: @scope _cmp_neq lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r0, r1 bne .true .false: movs r0, #0 bx lr .true: movs r0, #1 bx lr .boxed: push {r4, lr} push {r0, r1} bl numops::neq bl numops::toBoolDecr movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} _cmp_neqq: @scope _cmp_neqq lsls r2, r0, #31 beq .boxed lsls r2, r1, #31 beq .boxed subs r0, r1 bne .true .false: movs r0, #0 bx lr .true: movs r0, #1 bx lr .boxed: push {r4, lr} push {r0, r1} bl numops::neqq bl numops::toBoolDecr movs r4, r0 pop {r0} bl _pxt_decr pop {r0} bl _pxt_decr movs r0, r4 pop {r4, pc} .balign 4 _pxt_config_data: .word 0 _js_end: .balign 4 _img0: .short 0xffff .short 5, 5 .byte 0,255,0,255,0,255,255,255,255,255,255,255,255,255,255,0,255,255,255,0,0,0,255,0,0,0 .balign 4 _img1: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,255,0,255,0,0,255,255,255,0,0,0,255,0,0,0,0,0,0,0,0 .balign 4 _img2: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,255,0,255,0,0,0,0,0,0,255,0,0,0,255,0,255,255,255,0,0 .balign 4 _img3: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,255,0,255,0,0,0,0,0,0,0,255,255,255,0,255,0,0,0,255,0 .balign 4 _img4: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,255,0,255,0,0,0,0,0,0,0,255,0,255,0,255,0,255,0,255,0 .balign 4 _img5: .short 0xffff .short 5, 5 .byte 255,0,0,0,255,0,255,0,255,0,0,0,0,0,0,255,255,255,255,255,255,0,255,0,255,0 .balign 4 _img6: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,255,255,0,255,255,0,0,0,0,0,0,255,255,255,0,0,0,0,0,0,0 .balign 4 _img7: .short 0xffff .short 5, 5 .byte 0,255,0,255,0,0,0,0,0,0,0,0,255,0,0,0,255,0,255,0,0,0,255,0,0,0 .balign 4 _img8: .short 0xffff .short 5, 5 .byte 255,0,0,0,255,0,0,0,0,0,255,255,255,255,255,0,0,0,255,255,0,0,0,255,255,0 .balign 4 _img9: .short 0xffff .short 5, 5 .byte 255,255,255,255,255,255,255,0,255,255,0,0,0,0,0,0,255,0,255,0,0,255,255,255,0,0 .balign 4 _img10: .short 0xffff .short 5, 5 .byte 255,255,0,255,255,0,0,0,0,0,0,0,0,255,0,0,0,255,0,0,0,255,0,0,0,0 .balign 4 _img11: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,0,0,0,255,0,0,0,255,0,255,0,255,0,0,0,255,0,0,0,0 .balign 4 _img12: .short 0xffff .short 5, 5 .byte 255,0,0,0,255,0,255,0,255,0,0,0,255,0,0,0,255,0,255,0,255,0,0,0,255,0 .balign 4 _img13: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,0,255,0,0,0,255,0,255,0,255,255,255,255,255,0,0,0,0,0,0 .balign 4 _img14: .short 0xffff .short 5, 5 .byte 255,0,0,0,0,255,255,0,0,0,255,0,255,0,0,255,0,0,255,0,255,255,255,255,255,0 .balign 4 _img15: .short 0xffff .short 5, 5 .byte 0,255,0,255,0,255,0,255,0,255,0,255,0,255,0,255,0,255,0,255,0,255,0,255,0,0 .balign 4 _img16: .short 0xffff .short 5, 5 .byte 0,0,255,0,0,0,255,0,255,0,255,0,0,0,255,0,255,0,255,0,0,0,255,0,0,0 .balign 4 _img17: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,0,255,0,0,0,255,0,255,0,0,0,255,0,0,0,0,0,0,0,0 .balign 4 _img18: .short 0xffff .short 5, 5 .byte 255,255,255,255,255,255,0,0,0,255,255,0,0,0,255,255,0,0,0,255,255,255,255,255,255,0 .balign 4 _img19: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,255,255,255,0,0,255,0,255,0,0,255,255,255,0,0,0,0,0,0,0 .balign 4 _img20: .short 0xffff .short 5, 5 .byte 255,255,0,0,255,255,255,0,255,0,0,0,255,0,0,255,255,0,255,0,255,255,0,0,255,0 .balign 4 _img21: .short 0xffff .short 5, 5 .byte 255,255,0,255,255,255,255,255,255,255,0,255,255,255,0,0,255,255,255,0,0,255,255,255,0,0 .balign 4 _img22: .short 0xffff .short 5, 5 .byte 0,0,0,255,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,0,255,0,255,0,0 .balign 4 _img23: .short 0xffff .short 5, 5 .byte 0,255,255,0,0,255,255,255,0,0,0,255,255,255,255,0,255,255,255,0,0,0,0,0,0,0 .balign 4 _img24: .short 0xffff .short 5, 5 .byte 0,0,255,0,0,0,255,255,255,0,255,255,255,255,255,0,255,255,255,0,0,255,0,255,0,0 .balign 4 _img25: .short 0xffff .short 5, 5 .byte 0,0,0,0,0,0,255,255,255,0,255,255,255,255,255,0,255,0,255,0,0,0,0,0,0,0 .balign 4 _img26: .short 0xffff .short 5, 5 .byte 255,255,0,255,255,255,255,255,255,255,0,0,255,0,0,255,255,255,255,255,255,255,0,255,255,0 .balign 4 _img27: .short 0xffff .short 5, 5 .byte 0,0,255,0,0,255,255,255,255,255,0,0,255,0,0,0,255,0,255,0,255,0,0,0,255,0 .balign 4 _img28: .short 0xffff .short 5, 5 .byte 0,255,255,255,0,255,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255,0,255,0,255,0 .balign 4 _img29: .short 0xffff .short 5, 5 .byte 0,0,255,0,0,0,0,255,0,0,0,0,255,0,0,0,255,255,255,0,0,0,255,0,0,0 .balign 4 _img30: .short 0xffff .short 5, 5 .byte 255,255,0,0,0,0,255,0,0,0,0,255,0,0,0,0,255,255,255,0,0,255,0,255,0,0 .balign 4 _img31: .short 0xffff .short 5, 5 .byte 0,255,255,255,0,255,0,255,0,255,255,255,255,255,255,0,255,255,255,0,0,255,255,255,0,0 .balign 4 _img32: .short 0xffff .short 5, 5 .byte 0,255,255,255,0,255,255,255,255,255,0,0,255,0,0,255,0,255,0,0,255,255,255,0,0,0 .balign 4 _img33: .short 0xffff .short 5, 5 .byte 255,255,0,0,0,255,255,0,255,255,0,255,0,255,0,0,255,255,255,0,0,0,0,0,0,0 .balign 4 _img34: .short 0xffff .short 5, 5 .byte 255,0,255,0,0,255,0,255,0,0,255,255,255,255,0,255,255,0,255,0,255,255,255,255,0,0 .balign 4 _img35: .short 0xffff .short 5, 5 .byte 255,0,0,0,255,255,0,0,0,255,255,255,255,255,255,0,255,255,255,0,0,0,255,0,0,0 .balign 4 _img36: .short 0xffff .short 5, 5 .byte 0,0,255,0,0,0,0,255,0,0,0,0,255,0,0,255,255,255,0,0,255,255,255,0,0,0 .balign 4 _img37: .short 0xffff .short 5, 5 .byte 0,0,255,0,0,0,0,255,255,0,0,0,255,0,255,255,255,255,0,0,255,255,255,0,0,0 .balign 4 _img38: .short 0xffff .short 5, 5 .byte 255,0,255,0,255,255,0,255,0,255,255,255,255,255,255,0,0,255,0,0,0,0,255,0,0,0 .balign 4 _img39: .short 0xffff .short 5, 5 .byte 0,0,255,0,0,0,255,255,255,0,255,255,0,255,255,0,255,255,255,0,0,0,255,0,0,0 .balign 4 _img40: .short 0xffff .short 5, 5 .byte 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 .balign 4 _img64: .short 0xffff .short 5, 5 .byte 0,0,255,255,0,255,0,255,0,255,0,255,255,255,0,255,0,255,0,255,0,0,255,255,0,0 .balign 4 _str42meta: .short 0xffff, 1, 1 _str42: .string "0" .balign 4 _str62meta: .short 0xffff, 1, 1 _str62: .string "1" .balign 4 _str41meta: .short 0xffff, 1, 3 _str41: .string "alm" .balign 4 _str43meta: .short 0xffff, 1, 3 _str43: .string "mp3" .balign 4 _str44meta: .short 0xffff, 1, 1 _str44: .string "\n" .balign 4 _str45meta: .short 0xffff, 1, 3 _str45: .string "llp" .balign 4 _str46meta: .short 0xffff, 1, 3 _str46: .string "str" .balign 4 _str47meta: .short 0xffff, 1, 3 _str47: .string "rst" .balign 4 _str48meta: .short 0xffff, 1, 3 _str48: .string "img" .balign 4 _str49meta: .short 0xffff, 1, 3 _str49: .string "lob" .balign 4 _str50meta: .short 0xffff, 1, 3 _str50: .string "msc" .balign 4 _str51meta: .short 0xffff, 1, 3 _str51: .string "lll" .balign 4 _str52meta: .short 0xffff, 1, 3 _str52: .string "acc" .balign 4 _str53meta: .short 0xffff, 1, 3 _str53: .string "com" .balign 4 _str54meta: .short 0xffff, 1, 3 _str54: .string "tem" .balign 4 _str55meta: .short 0xffff, 1, 3 _str55: .string "set" .balign 4 _str56meta: .short 0xffff, 1, 4 _str56: .string "play" .balign 4 _str57meta: .short 0xffff, 1, 4 _str57: .string "ring" .balign 4 _str58meta: .short 0xffff, 1, 4 _str58: .string "rest" .balign 4 _str59meta: .short 0xffff, 1, 4 _str59: .string "beat" .balign 4 _str60meta: .short 0xffff, 1, 4 _str60: .string "dura" .balign 4 _str61meta: .short 0xffff, 1, 3 _str61: .string "slp" .balign 4 _str63meta: .short 0xffff, 1, 3 _str63: .string "---" _program_end:
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: dBase III MODULE: Export FILE: exportFile.asm AUTHOR: Ted H. Kim, 9/14/92 ROUTINES: Name Description ---- ----------- TransExport Library routine called by Impex REVISION HISTORY: Name Date Description ---- ---- ----------- ted 9/92 Initial revision DESCRIPTION: Contains all of file export routines. $Id: exportFile.asm,v 1.1 97/04/07 11:42:57 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ Export segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TransExport %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Library routine called by Impex CALLED BY: Impex PASS: ds:si - ExportFrame RETURN: ax - TransError DESTROYED: bx, cx, dx, si, di, bp, es, ds KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ted 5/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TransExport proc far TE_Local local ImpexStackFrame TE_SSMeta local SSMetaStruc .enter ; check to see if transfer VM file is empty mov ax, TE_EXPORT_INVALID_CLIPBOARD_FORMAT ; just in case... cmp ds:[si].EF_clipboardFormat, CIF_SPREADSHEET LONG jne exit cmp ds:[si].EF_manufacturerID, MANUFACTURER_ID_GEOWORKS LONG jne exit mov ax, ds:[si].EF_transferVMChain.low or ax, ds:[si].EF_transferVMChain.high jne notEmpty ; skip if not empty mov ax, TE_EXPORT_FILE_EMPTY ; ax - TransError jmp exit notEmpty: ; set up the output file for writing mov bx, ds:[si].EF_outputFile ; bx - handle of output file call OutputCacheAttach ; create output cache block mov ax, TE_OUT_OF_MEMORY ; not enough memory LONG jc exit ; exit if error mov TE_Local.ISF_cacheBlock, bx ; save handle of cache block ; get the handle of map entry block from the stack frame mov bx, ds:[si].EF_exportOptions ; bx - map list block mov TE_Local.ISF_mapBlock, bx ; save it ; initialize the stack frame for file exporting mov bx, ds:[si].EF_transferVMFile ; bx - VM file handle mov ax, ds:[si].EF_transferVMChain.high ; ax - VM block handle push bp mov dx, ss lea bp, TE_SSMeta ; dx:bp - SSMetaStruc call SSMetaInitForRetrieval pop bp ; now grab the number of records and fields from the transfer file mov ax, TE_SSMeta.SSMDAS_scrapRows mov TE_Local.ISF_numRecords.low, ax ; ax - number of records mov TE_Local.ISF_numRecords.high, 0 mov ax, TE_SSMeta.SSMDAS_scrapCols mov TE_Local.ISF_numSourceFields, ax; ax - number of fields ; allocate a block for storing field length and type mov ax, FIELD_INFO_BLOCK_SIZE ; ax - size of block to allocate mov cx, ((mask HAF_ZERO_INIT or mask HAF_NO_ERR) shl 8) or 0 call MemAlloc ; allocate a block mov TE_Local.ISF_fieldInfoBlock, bx ; save the handle ; convert to dBase III call ExportFileHeader jc fileErr ; skip if error ; check to see if there is a map block tst TE_Local.ISF_mapBlock jne mapBlk ; if there is, skip call ExportFileFast ; no map block, do fast export jnc noError ; skip if no error jmp fileErr mapBlk: call ExportRecordData jnc noError ; skip if no error ; delete the FieldInfo data block fileErr: push ax ; ax - TransError mov bx, TE_Local.ISF_fieldInfoBlock call MemFree mov bx, TE_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheFlush ; flush out the buffer call OutputCacheDestroy ; destroy cache block pop ax ; ax = TransError jmp exit noError: call ExportEndOfFileChar ; write out EOF character mov bx, TE_Local.ISF_fieldInfoBlock call MemFree ; clean up the cached block mov bx, TE_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheFlush ; flush out the buffer jc error ; exit if error call OutputCacheDestroy ; destroy cache block mov ax, TE_NO_ERROR ; return with no error jmp exit error: mov ax, TE_FILE_ERROR ; return with file error exit: .leave ret TransExport endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ExportFileHeader %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create a block with file header and write it out CALLED BY: TransExport PASS: ImpexStackFrame RETURN: ImpexStackFrame carry set if error (ax = TransError) DESTROYED: ax, bx, cx, dx, es, ds, si, di SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 9/92 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ExportFileHeader proc near EFH_Local local ImpexStackFrame EFH_SSMeta local SSMetaStruc .enter inherit near ; check to see if there are too many fields mov ax, EFH_Local.ISF_numSourceFields cmp ax, MAX_NUM_FIELDS ; the limit is 128 jle skip ; if not over the limit, skip mov al, MAX_NUM_FIELDS ; al - 128 fields skip: ; calculate the size of file header to allocate inc al ; add one for other info mov cl, FIELD_DESCRIPTOR_SIZE mul cl inc ax ; ax - size of file header block ; now allocate file header block mov cx, ((mask HAF_LOCK or mask HAF_ZERO_INIT) shl 8) or 0 call MemAlloc ; allocate a block LONG jc noMem ; exit if not enough memory mov EFH_Local.ISF_fileHeader, bx ; save the handle mov es, ax clr di mov es:[di].DBH_version, DBASE3_NO_MEMO ; write out ver. num. mov ax, EFH_Local.ISF_numRecords.low mov es:[di].DBH_numRecords.low, ax ; write out num records mov EFH_Local.ISF_recordSize, 1 ; initialize record size to one clr dx ; dx - field counter mov di, size DBaseHeader ; es:di - ptr to field descriptors nextField: call ExportFieldDescriptor ; write out field descriptor jnc notMapped ; skip if the field not mapped ; lock the field info block push es, dx, di mov bx, EFH_Local.ISF_fieldInfoBlock call MemLock ; calculate place to insert FieldHeaderInfo mov es, ax mov ax, dx mov cx, size FieldHeaderInfo mul cx mov di, ax ; es:di - place to insert ; update field infor block for this field mov al, EFH_Local.ISF_fieldType mov es:[di].FHI_type, al mov ax, EFH_Local.ISF_fieldLength mov es:[di].FHI_length, ax call MemUnlock pop es, dx, di ; don't update the pointer if field size was zero tst ax je notMapped ; check to see if we are done add di, size FieldDescriptor notMapped: inc dx cmp dx, EFH_Local.ISF_numSourceFields jne nextField ; write out record length and header size mov byte ptr es:[di], CR ; file header terminator inc di mov ax, EFH_Local.ISF_recordSize mov es:[DBH_recordSize], ax mov es:[DBH_headerSize], di ; if done, write out file header block segmov ds, es clr dx ; ds:dx - fptr to string mov cx, di ; cx - number of bytes to write out mov bx, EFH_Local.ISF_cacheBlock call OutputCacheWrite ; write out file header block ; delete the file header block pushf mov bx, EFH_Local.ISF_fileHeader call MemFree popf jnc quit ; skip if no error mov ax, TE_FILE_ERROR ; ax - TransError jmp quit noMem: mov ax, TE_OUT_OF_MEMORY ; ax - TransError quit: .leave ret ExportFileHeader endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ExportFieldDescriptor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Creates a new file descriptor and copies it into file header CALLED BY: INTERNAL (ExportFileHeader) PASS: es:di - ptr to file header block dx - current column (field) number RETURN: carry clear if the field has not been mapped carry set if mapped DESTROYED: ax, bx, cx, ds, si SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 9/92 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ExportFieldDescriptor proc near uses dx, di EFD_Local local ImpexStackFrame EFD_SSMeta local SSMetaStruc .enter inherit near ; get true column number after the field has been mapped mov ax, dx ; ax - column number mov bx, EFD_Local.ISF_mapBlock ; bx - handle map block mov cl, mask IF_EXPORT ; do export call GetMappedRowAndColNumber jnc exit ; skip if not mapped ; get FieldBlockInfo info from FIELD array mov EFD_SSMeta.SSMDAS_dataArraySpecifier, DAS_FIELD mov EFD_SSMeta.SSMDAS_col, ax ; ax - column number mov EFD_SSMeta.SSMDAS_row, 0 ; row number push bp mov dx, ss lea bp, EFD_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayGetEntryByCoord ; get this element pop bp jnc notEmpty ; exit if empty call ExportGetDefaultFieldInfo ; get default field info jmp done notEmpty: add si, size SSMetaEntry ; ds:si - ptr to FieldBlockInfo ; check to see if this is an empty column tst ds:[si].FIB_fieldSize je skip ; if so, just exit push si, di ; copy the field name into file descriptor clr cx add si, offset FIB_fieldName ; ds:si - ptr to field name next: lodsb stosb inc cx cmp cx, FIELD_NAME_SIZE-1 je doneCopy tst al jne next doneCopy: pop si, di ; get the field data type skip: mov al, ds:[si].FIB_fieldType mov EFD_Local.ISF_fieldType, al ; get the field data length call ExportGetFieldLength ; al - dbase III data type mov es:[di].FD_fieldType, al ; save it cmp EFD_Local.ISF_fieldType, FDT_REAL ; float format? jne notFloat ; if not, skip ; if float format, update the decimal count in field descriptor ; I AM USING A DEFAULT VALUE FOR ALL FLOAT FIELDS BECAUSE THERE ; IS NOT AN EASY WAY OF GETTING DECIMAL OFFSETS FOR EACH FIELD mov es:[di].FD_decCount, DEFAULT_DECIMAL_OFFSET notFloat: mov es:[di].FD_fieldSize, bl ; bx - field length mov EFD_Local.ISF_fieldLength, bx add EFD_Local.ISF_recordSize, bx ; update record length ; unlock the data array push bp mov dx, ss lea bp, EFD_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayUnlock pop bp done: stc ; return with carry set exit: .leave ret ExportFieldDescriptor endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ExportGetDefaultFieldInfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create a default field info block. CALLED BY: INTERNAL ExportFieldDescriptor PASS: ax - column number es:di - ptr to file header block RETURN: nothing DESTROYED: ax, bx, cx, dx, si SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 11/92 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ExportGetDefaultFieldInfo proc near EGDFI_Local local ImpexStackFrame EGDFI_SSMeta local SSMetaStruc .enter inherit near ; get field name from CELL array mov EGDFI_SSMeta.SSMDAS_dataArraySpecifier, DAS_CELL mov EGDFI_SSMeta.SSMDAS_col, ax ; ax - column number mov EGDFI_SSMeta.SSMDAS_row, 0 ; row number push bp, ax mov dx, ss lea bp, EGDFI_SSMeta ; dx:bp - SSMetaStruc clr bx ; Assume no data call SSMetaDataArrayGetEntryByCoord ; ds:si <- ptr to data ; cx <- size pop bp, dx jc noCell ; branch if there is no data ; There is data, we need to either reset our pointer, ; or else format the data to a block which we allocate. push bp, dx, es, di mov dx, ss lea bp, EGDFI_SSMeta ; dx:bp - SSMetaStruc call SSMetaFormatCellText ; ds:si <- ptr to text pop bp, dx, es, di ; ax <- size of text jnc notEmpty ; skip if cell exists ; if there is no cell, get a default field name mov cx, FIELD_NAME_SIZE-1 ; cx - maximum field name length call GetDefaultFieldName jmp unlock ; if this cell is empty get a default field name noCell: mov cx, FIELD_NAME_SIZE-1 ; cx - maximum field name length call GetDefaultFieldName jmp getSize notEmpty: push si, di ; copy the field name into file descriptor clr cx next: lodsb stosb inc cx cmp cx, FIELD_NAME_SIZE-1 je doneCopy tst al jne next doneCopy: pop si, di ; unlock the data array unlock: push bp, dx mov dx, ss lea bp, EGDFI_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataRecordFieldUnlock pop bp, dx getSize: ; get field size from CELL array mov EGDFI_SSMeta.SSMDAS_dataArraySpecifier, DAS_CELL mov EGDFI_SSMeta.SSMDAS_col, dx ; dx - column number mov EGDFI_SSMeta.SSMDAS_row, 1 ; row number push bp, dx mov dx, ss lea bp, EGDFI_SSMeta ; dx:bp - SSMetaStruc clr bx ; Assume no data call SSMetaDataArrayGetEntryByCoord ; ds:si <- ptr to data ; cx <- size pop bp, dx jc empty ; branch if there is no data ; There is data, we need to either reset our pointer, ; or else format the data to a block which we allocate. push bp, dx, es, di mov dx, ss lea bp, EGDFI_SSMeta ; dx:bp - SSMetaStruc call SSMetaFormatCellText ; ds:si <- ptr to text pop bp, dx, es, di ; ax <- size of text ; bx <- block (if any) ; unlock the data array pushf push bp, dx mov dx, ss lea bp, EGDFI_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataRecordFieldUnlock pop bp, dx popf jc empty ; make the column a little bit wider just in case add al, FIELD_WIDTH_ADJUSTMENT jmp common empty: mov al, DEFAULT_FIELD_WIDTH ; use the default field size common: mov es:[di].FD_fieldSize, al ; ax - field length mov EGDFI_Local.ISF_fieldLength, ax add EGDFI_Local.ISF_recordSize, ax ; update record length ; get field type from CELL array mov EGDFI_SSMeta.SSMDAS_dataArraySpecifier, DAS_CELL mov EGDFI_SSMeta.SSMDAS_col, dx ; dx - column number mov EGDFI_SSMeta.SSMDAS_row, 1 ; row number push bp, dx mov dx, ss lea bp, EGDFI_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayGetEntryByCoord ; get this element pop bp, dx jc noType ; unlock the data array push bp mov dx, ss lea bp, EGDFI_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayUnlock pop bp add si, size SSMetaEntry ; ds:si - ptr to CellCommon mov al, ds:[si].CC_type ; al - field data type call ConvertCellType jmp skip noType: mov al, FDT_GENERAL_TEXT skip: mov EGDFI_Local.ISF_fieldType, al call ConvertFieldType ; convert to dbase field type mov es:[di].FD_fieldType, al ; save it .leave ret ExportGetDefaultFieldInfo endp FDT_IGNORE equ 255 FDT_FORMULA_TEXT equ 254 FDT_FORMULA_CONST equ 253 ConvertCellType proc near uses si .enter cmp al, CT_TEXT jne checkConst mov al, FDT_GENERAL_TEXT jmp exit checkConst: cmp al, CT_CONSTANT jne checkFormula mov al, FDT_REAL jmp exit checkFormula: cmp al, CT_FORMULA jne checkName formula: add si, size CellCommon ; ds:si - ptr to ReturnType mov al, ds:[si] ; al - ReturnType cmp al, RT_VALUE ; numeric value? jne checkText ; if not, skip mov al, FDT_FORMULA_CONST ; numeric field jmp exit checkText: cmp al, RT_TEXT ; text string? jne error ; if not, error value mov al, FDT_FORMULA_TEXT ; text field jmp exit error: mov al, FDT_FORMULA_CONST ; text field jmp exit checkName: cmp al, CT_NAME jne checkChart mov al, FDT_IGNORE jmp exit checkChart: cmp al, CT_CHART jne checkEmpty mov al, FDT_IGNORE jmp exit checkEmpty: cmp al, CT_EMPTY jne formula mov al, FDT_IGNORE exit: .leave ret ConvertCellType endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ConvertFieldType %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Converts FieldDataType to dBase III field type. CALLED BY: (INTERNAL) ExportGetDefaultFieldInfo PASS: al - FieldDataType RETURN: al - dBase III field data type DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 1/26/93 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ConvertFieldType proc near CFT_Local local ImpexStackFrame CFT_SSMeta local SSMetaStruc .enter inherit near ; check to see if this is a text field cmp al, FDT_GENERAL_TEXT jne checkComputed mov al, 'C' ; al - dBase III field type jmp exit ; check to see if this is a computed field checkComputed: cmp al, FDT_COMPUTED jne checkInteger mov al, 'N' ; convert it to numeric field jmp exit ; check to see if this is an integer field checkInteger: cmp al, FDT_INTEGER jne checkReal mov al, 'N' ; convert it to numeric field jmp exit ; check to see if this is a read field checkReal: cmp al, FDT_REAL jne checkDate mov al, 'N' ; convert it to numeric field jmp exit ; check to see if this is a date field checkDate: cmp al, FDT_DATE jne checkTime mov al, 'D' ; convert it to date field jmp exit ; check to see if this is a time field checkTime: cmp al, FDT_TIME jne checkIgnore mov al, 'C' ; convert it to text field jmp exit checkIgnore: cmp al, FDT_IGNORE jne checkFormula1 mov al, 'C' jmp exit checkFormula1: cmp al, FDT_FORMULA_CONST jne checkFormula2 mov al, 'N' ; numeric field jmp exit checkFormula2: mov al, 'C' ; assume text value exit: .leave ret ConvertFieldType endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ExportGetFieldLength %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Given a field data type, returns field length and dBase III data type. CALLED BY: INTERNAL (ExportFieldDescriptor) PASS: ds:si - ptr to FieldDescriptor RETURN: al - dBase III field data type bx - field size DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 9/92 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ExportGetFieldLength proc near EGFL_Local local ImpexStackFrame EGFL_SSMeta local SSMetaStruc .enter inherit near ; check to see if this is a text field cmp al, FDT_GENERAL_TEXT jne checkComputed mov al, 'C' ; al - dBase III field type mov bx, ds:[si].FIB_fieldSize ; check to see if the field size is too big cmp bx, TEXT_FIELD_SIZE jle exit mov bx, TEXT_FIELD_SIZE ; bx - field length jmp exit ; check to see if this is a computed field checkComputed: cmp al, FDT_COMPUTED jne checkInteger mov al, 'N' ; convert it to numeric field mov bx, FLOAT_FIELD_SIZE ; bx - field length jmp exit ; check to see if this is an integer field checkInteger: cmp al, FDT_INTEGER jne checkReal mov al, 'N' ; convert it to numeric field mov bx, INTEGER_FIELD_SIZE ; bx - field length jmp exit ; check to see if this is a read field checkReal: cmp al, FDT_REAL jne checkDate mov al, 'N' ; convert it to numeric field mov bx, FLOAT_FIELD_SIZE ; bx - field size jmp exit ; check to see if this is a date field checkDate: cmp al, FDT_DATE jne checkTime mov al, 'D' mov bx, DATE_FIELD_SIZE ; bx - field size jmp exit ; it has to be a time field checkTime: mov al, 'C' ; convert it to numeric field mov bx, TIME_FIELD_SIZE ; bx - field size exit: .leave ret ExportGetFieldLength endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ExportFileFast %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Write out data portion of the meta file using 'SSMetaDataArrayGetNext'. CALLED BY: TransExport PASS: ImportStackFrame RETURN: carry set if error (ax = TransError) DESTROYED: ax, bx, cx, dx, si, di, es, ds SIDE EFFECTS: nothing PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 9/92 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ExportFileFast proc near EFF_Local local ImpexStackFrame EFF_SSMeta local SSMetaStruc .enter inherit near ; initialize some flags mov EFF_Local.ISF_endOfFile, FALSE mov EFF_Local.ISF_endOfLine, FALSE ; point to the beginning of DAS_CELL data chain mov EFF_SSMeta.SSMDAS_dataArraySpecifier, DAS_CELL push bp mov dx, ss lea bp, EFF_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayResetEntryPointer pop bp ; allocate a block for storing field data mov ax, TEXT_FIELD_SIZE ; ax - size of block to allocate mov cx, (HAF_STANDARD_NO_ERR shl 8) or 0 ; HeapAllocFlags call MemAlloc ; allocate a block mov EFF_Local.ISF_fieldBlock, bx ; save the handle of this block clr EFF_Local.ISF_rowNumber ; record number counter nextRecord: ; write out a space character to indicate the beg. of a record push ds segmov ds, cs mov dx, offset space ; ds:dx - fptr to string mov cx, 1 ; cx - # of bytes to write out mov bx, EFF_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite pop ds LONG jc fileErr ; skip if file error clr EFF_Local.ISF_colNumber ; field number counter nextField: ; check to see if the field data we are about to parse has already ; been lock by a previous call to 'SSMetaDataArrayGetNextEntry' tst EFF_Local.ISF_endOfLine jne locked ; if locked, skip ; get an element from DAS_CELL data chain push bp mov dx, ss lea bp, EFF_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayGetNextEntry pop bp jnc locked ; skip if not end of chain ; end of data chain, set end of file flag mov EFF_Local.ISF_endOfFile, TRUE jmp checkEOL locked: ; check to see if we are at the end of a record mov ax, EFF_Local.ISF_rowNumber cmp ax, ds:[si].SSME_coordRow je checkField checkEOL: ; we are at the end of a record, write out some empty ; data fields, if necessary mov dx, EFF_Local.ISF_colNumber cmp dx, EFF_Local.ISF_numSourceFields jne writeEmpty ; no need to write out any empty data fields ; set end of line flag and update row and column counters tst EFF_Local.ISF_endOfFile ; no more data? jne done ; if none, exit mov EFF_Local.ISF_endOfLine, TRUE inc EFF_Local.ISF_rowNumber clr EFF_Local.ISF_colNumber jmp nextRecord writeEmpty: ; write out empty fields until we are at the end of a record mov EFF_Local.ISF_emptyField, TRUE push ds, si call ExportFieldData ; write out field data pop ds, si jc fileErr ; exit if file error inc EFF_Local.ISF_colNumber ; update column counter jmp checkEOL ; done, parse next record checkField: ; check to see if we need to write out some empty data fields mov dx, EFF_Local.ISF_colNumber cmp dx, ds:[si].SSME_coordCol je exportField ; if not, skip to export ; empty fields exist between two non-empty cells, write them out mov EFF_Local.ISF_emptyField, TRUE push ds, si call ExportFieldData ; write out field data pop ds, si jc fileErr ; exit if file error inc EFF_Local.ISF_colNumber ; update column counter jmp checkField ; if not continue exportField: ; finally, we are ready to export this data mov EFF_Local.ISF_emptyField, FALSE add si, size SSMetaEntry ; ds:si - field data call ExportFieldData ; write out field data jc fileErr ; exit if file error inc EFF_Local.ISF_colNumber ; update column counter mov EFF_Local.ISF_endOfLine, FALSE jmp nextField ; continue done: ; unlock the data chain push bp mov dx, ss lea bp, EFF_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayUnlock pop bp ; remove the field data block mov bx, EFF_Local.ISF_fieldBlock call MemFree clc jmp quit fileErr: mov ax, TE_FILE_ERROR ; ax - TransError mov bx, EFF_Local.ISF_fieldBlock call MemFree ; remove the field data block stc quit: .leave ret ExportFileFast endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ExportRecordData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Write out data portion of the meta file CALLED BY: TransExport PASS: ImportStackFrame RETURN: carry set if error (ax = TransError) DESTROYED: ax, bx, cx, dx, si, di, es, ds SIDE EFFECTS: nothing PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 9/92 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ space byte SPACE, 0 ExportRecordData proc near ERD_Local local ImpexStackFrame ERD_SSMeta local SSMetaStruc .enter inherit near ; allocate a block for storing field data mov ax, TEXT_FIELD_SIZE ; ax - size of block to allocate mov cx, (HAF_STANDARD_NO_ERR shl 8) or 0 ; HeapAllocFlags call MemAlloc ; allocate a block mov ERD_Local.ISF_fieldBlock, bx ; save the handle of this block clr cx ; record number counter nextRecord: push cx mov ERD_SSMeta.SSMDAS_row, cx ; cx - row number segmov ds, cs mov dx, offset space ; ds:dx - fptr to string mov cx, 1 ; cx - # of bytes to write out mov bx, ERD_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write out space character jc fileErr ; skip if file error clr dx ; field number counter nextField: ; get true column number after the field has been mapped push dx mov ax, dx ; ax - column number mov bx, ERD_Local.ISF_mapBlock ; bx - handle map block mov cl, mask IF_EXPORT ; do export call GetMappedRowAndColNumber jnc skip ; skip if not mapped ; get field data from CELL array mov ERD_Local.ISF_emptyField, FALSE ; assume not empty mov ERD_SSMeta.SSMDAS_dataArraySpecifier, DAS_CELL mov ERD_SSMeta.SSMDAS_col, ax ; ax - mapped column number push bp mov dx, ss lea bp, ERD_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayGetEntryByCoord ; get this element pop bp jnc notEmpty ; skip if not empty mov ERD_Local.ISF_emptyField, TRUE ; set empty field flag notEmpty: pop dx ; dx - current column number push dx add si, size SSMetaEntry ; ds:si - field data call ExportFieldData ; write out field data ; no need to unlock a data entry that was non extant pushf ; save the carry flag cmp ERD_Local.ISF_emptyField, TRUE ; was it an empty field? je empty ; skip if empty ; unlock the huge array block push bp mov dx, ss lea bp, ERD_SSMeta ; dx:bp - SSMetaStruc call SSMetaDataArrayUnlock pop bp empty: popf ; restore the carry flag jc fileErr0 ; exit if file error skip: ; get the next field if not done pop dx inc dx cmp dx, ERD_Local.ISF_numSourceFields jne nextField ; get the next record if not done pop cx inc cx cmp cx, ERD_Local.ISF_numRecords.low jne nextRecord ; remove the field data block mov bx, ERD_Local.ISF_fieldBlock call MemFree clc jmp quit fileErr0: pop dx fileErr: pop cx mov ax, TE_FILE_ERROR ; ax - TransError mov bx, ERD_Local.ISF_fieldBlock call MemFree ; remove the field data block stc quit: .leave ret ExportRecordData endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ExportFieldData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Write out the field data to export file. CALLED BY: INTERNAL (ExportRecordData) PASS: ds:si - ptr to CellCommon dx - current field number RETURN: carry set if there was a file error DESTROYED: ax, bx, es, ds, si, di SIDE EFFECTS: nothing PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 9/92 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ExportFieldData proc near uses cx, dx EFD_Local local ImpexStackFrame EFD_SSMeta local SSMetaStruc .enter inherit near ; lock the field info block mov bx, EFD_Local.ISF_fieldInfoBlock call MemLock ; locate the field info for the current field mov es, ax mov ax, dx mov cx, size FieldHeaderInfo mul cx mov di, ax ; es:di - FieldHeaderInfo mov al, es:[di].FHI_type mov cx, es:[di].FHI_length call MemUnlock ; save FieldHeaderInfo mov EFD_Local.ISF_fieldType, al mov EFD_Local.ISF_fieldLength, cx ; check to see if the current cell data type matches field data type push ax mov al, ds:[si].CC_type ; al - CellType call CompareDataTypes ; check for data type conflict pop ax jne emptyCell ; if so, write out empty cell add si, size CellCommon ; ds:si - pointer to field data ; check to see if this is an empty column cmp EFD_Local.ISF_emptyField, TRUE jne notEmpty ; if not, skip ; if this is an empty field in a non empty column ; then write out the empty field data emptyCell: jcxz exit call ExportEmptyFieldData ; write out empty field jmp exit notEmpty: cmp al, FDT_GENERAL_TEXT jne checkInteger call ExportTextField jmp exit ; check to see if this is an integer field checkInteger: cmp al, FDT_INTEGER jne checkReal call ExportIntegerField jmp exit ; check to see if this is a real field checkReal: cmp al, FDT_REAL jne checkDate call ExportIntegerField jmp exit ; check to see if this is a date field checkDate: cmp al, FDT_DATE jne checkTime call ExportDateField jmp exit ; check to see if this is a time field checkTime: cmp al, FDT_TIME jne checkIgnore call ExportTimeFieldData jmp exit ; check to see if this is an ignored field checkIgnore: cmp al, FDT_IGNORE jne checkFormula1 call ExportEmptyFieldData ; write out empty field jmp exit ; check to see if this is a text formula field checkFormula1: cmp al, FDT_FORMULA_TEXT jne checkFormula2 call ExportTextFormulaFieldData jmp exit ; check to see if this is a numeric formula field checkFormula2: cmp al, FDT_FORMULA_CONST ; is this a numeric formula field? je formula ; if so, skip to handle it stc ; if not a formula field, jmp exit ; exit with carry set formula: call ExportNumericFormulaFieldData exit: .leave ret ExportFieldData endp CompareDataTypes proc near CDT_Local local ImpexStackFrame CDT_SSMeta local SSMetaStruc .enter inherit near cmp al, CT_CONSTANT jne other ; treat FDT_REAL, FDT_INTEGER, FDT_DATE, and FDT_TIME the same cmp CDT_Local.ISF_fieldType, FDT_REAL je exit cmp CDT_Local.ISF_fieldType, FDT_INTEGER je exit cmp CDT_Local.ISF_fieldType, FDT_DATE je exit cmp CDT_Local.ISF_fieldType, FDT_TIME jmp exit other: call ConvertCellType cmp CDT_Local.ISF_fieldType, al exit: .leave ret CompareDataTypes endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ExportTextField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Writes out text field data CALLED BY: INTERNAL (ExportFieldData) PASS: ds:si - ptr to field data RETURN: carry set if there was a file error DESTROYED: ax, bx, cx, es, si, di SIDE EFFECTS: nothing PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- THK 9/92 Initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ExportTextField proc near ETF_Local local ImpexStackFrame ETF_SSMeta local SSMetaStruc .enter inherit near ; lock the data block mov bx, ETF_Local.ISF_fieldBlock call MemLock mov cx, TEXT_FIELD_SIZE ; cx - size of data block ; initialize this data block with space characters mov es, ax clr di mov al, SPACE rep stosb ; copy the text string in ds:si to this data block mov cx, TEXT_FIELD_SIZE ; cx - size of data block clr di next: lodsb tst al ; do not copy null terminator je exitLoop stosb loop next exitLoop: ; write out this data block to export file mov cx, ETF_Local.ISF_fieldLength ; cx - # of bytes to write out segmov ds, es clr dx ; ds:dx - fptr to string mov bx, ETF_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write header block pushf ; save the flags mov bx, ETF_Local.ISF_fieldBlock call MemUnlock popf ; restore the flags .leave ret ExportTextField endp ExportIntegerField proc near EIF_Local local ImpexStackFrame EIF_SSMeta local SSMetaStruc .enter inherit near ; lock the data block mov bx, EIF_Local.ISF_fieldBlock call MemLock mov cx, TEXT_FIELD_SIZE ; cx - size of data block ; initialize this data block with space characters mov es, ax clr di mov al, SPACE rep stosb ; convert number to ascii string mov di, INTEGER_FIELD_SIZE ; es:di - destination addr mov al, EIF_Local.ISF_fieldType ; al - field data type call ExportIntegerToAscii ; convert the number tst cx ; successful conversion? jne noError ; if so, skip ; if error, get the size of error string call LocalStringSize ; cx <- Size of string noError: ; write out this data field to export file mov dx, EIF_Local.ISF_fieldLength ; dx - field length cmp cx, dx ; ascii string too long? jge tooLong ; if so, skip ; figure out where the start of string to copy is sub dx, cx mov ax, INTEGER_FIELD_SIZE sub ax, dx xchg dx, ax jmp common tooLong: mov dx, INTEGER_FIELD_SIZE ; ds:dx - ptr to field data common: mov cx, EIF_Local.ISF_fieldLength ; cx - # of bytes to copy segmov ds, es mov bx, EIF_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write out data field pushf mov bx, EIF_Local.ISF_fieldBlock call MemUnlock popf .leave ret ExportIntegerField endp ExportIntegerToAscii proc near EITA_Local local FFA_stackFrame .enter ; no header or trailer string mov EITA_Local.FFA_float.FFA_params.header, 0 mov EITA_Local.FFA_float.FFA_params.trailer, 0 mov EITA_Local.FFA_float.FFA_params.formatFlags, mask FFAF_FROM_ADDR mov EITA_Local.FFA_float.FFA_params.decimalLimit, 0 cmp al, FDT_FORMULA_CONST ; formula number? je skip ; if so, skip cmp al, FDT_REAL ; float number field? jne notFloat ; if not, skip ; if float format, use the default decimal limit ; I AM USING A DEFAULT VALUE FOR ALL FLOAT FIELDS BECAUSE THERE ; IS NOT AN EASY WAY OF GETTING DECIMAL OFFSETS FOR EACH FIELD skip: mov EITA_Local.FFA_float.FFA_params.decimalLimit, DEFAULT_DECIMAL_OFFSET notFloat: mov EITA_Local.FFA_float.FFA_params.totalDigits, DECIMAL_PRECISION mov EITA_Local.FFA_float.FFA_params.decimalOffset, 0 mov EITA_Local.FFA_float.FFA_params.preNegative, '-' mov EITA_Local.FFA_float.FFA_params.preNegative+1, 0 mov EITA_Local.FFA_float.FFA_params.postNegative, 0 mov EITA_Local.FFA_float.FFA_params.postPositive, 0 mov EITA_Local.FFA_float.FFA_params.prePositive, 0 call FloatFloatToAscii ; convert! .leave ret ExportIntegerToAscii endp ExportDateField proc near EDF_Local local ImpexStackFrame EDF_SSMeta local SSMetaStruc .enter inherit near ; lock the data block mov bx, EDF_Local.ISF_fieldBlock call MemLock mov es, ax clr di ; initialize the floating point stack mov ax, FP_DEFAULT_STACK_SIZE mov bl, FLOAT_STACK_DEFAULT_TYPE call FloatInit ; push the float number on to the stack call FloatPushNumber call FloatDateNumberGetYear ; ax - year number jnc noError ; skip if no error clr ax ; just convert zero noError: clr dx ; dx:ax - number to convert mov cx, mask UHTAF_INCLUDE_LEADING_ZEROS ; cx - UtilHexToAsciiFlags call UtilHex32ToAscii ; convert it to ascii ; write out year string to export file push ds, si mov cx, DATE_YEAR_SIZE ; cx - # of bytes to write out mov dx, 6 ; ds:dx - ptr to field data segmov ds, es mov bx, EDF_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write out data field pop ds, si jc error ; exit if error ; push the float number on to the stack again call FloatPushNumber call FloatDateNumberGetMonthAndDay ; bl - month, bh - day clr di ; es:di - destination buffer clr dx clr ah mov al, bl ; dx:ax - number to convert mov cx, mask UHTAF_INCLUDE_LEADING_ZEROS ; cx - UtilHexToAsciiFlags call UtilHex32ToAscii ; convert month to ascii ; write out month string to export file push bx mov cx, 2 ; cx - # of bytes to write out mov dx, 8 ; ds:dx - ptr to field data segmov ds, es mov bx, EDF_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write out data field pop bx jc error ; exit if error clr di ; es:di - destination buffer clr dx clr ah mov al, bh mov cx, mask UHTAF_INCLUDE_LEADING_ZEROS ; cx - UtilHexToAsciiFlags call UtilHex32ToAscii ; convert day to ascii ; write out date string to export file mov cx, 2 ; cx - # of bytes to write out mov dx, 8 ; ds:dx - ptr to field data segmov ds, es mov bx, EDF_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write out data field error: pushf call FloatExit mov bx, EDF_Local.ISF_fieldBlock call MemUnlock popf .leave ret ExportDateField endp ExportTimeFieldData proc near ETFD_Local local ImpexStackFrame ETFD_SSMeta local SSMetaStruc .enter inherit near ; lock the data block mov bx, ETFD_Local.ISF_fieldBlock call MemLock mov cx, FLOAT_TO_ASCII_NORMAL_BUF_LEN ; initialize this data block with space characters mov es, ax clr di mov al, SPACE rep stosb ; convert time float number to ascii string clr di ; es:di - destination buffer call ExportTimeToAscii ; count the number of bytes in the ascii string call LocalStringSize ; cx - string size mov di, cx mov byte ptr es:[di], SPACE ; write out time string to export file mov cx, ETFD_Local.ISF_fieldLength ; cx - # of bytes to copy clr dx segmov ds, es ; ds:dx - ptr to string to copy mov bx, ETFD_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write out data field pushf mov bx, ETFD_Local.ISF_fieldBlock call MemUnlock popf .leave ret ExportTimeFieldData endp ExportTimeToAscii proc near ETTA_Local local FFA_stackFrame .enter mov ax, DTF_HMS ; time format mov bx, mask FFDT_DATE_TIME_OP or mask FFDT_FROM_ADDR or ax, bx mov ETTA_Local.FFA_dateTime.FFA_dateTimeParams.FFA_dateTimeFlags, ax call FloatFloatToAscii ; convert to time .leave ret ExportTimeToAscii endp ExportEmptyFieldData proc near EEFD_Local local ImpexStackFrame EEFD_SSMeta local SSMetaStruc .enter inherit near ; lock the data block mov bx, EEFD_Local.ISF_fieldBlock call MemLock mov cx, TEXT_FIELD_SIZE ; cx - size of data block ; initialize this data block with space characters mov es, ax clr di mov al, SPACE rep stosb ; write out empty data block to export file mov cx, EEFD_Local.ISF_fieldLength ; cx - # of bytes to write out segmov ds, es clr dx ; ds:dx - fptr to string mov bx, EEFD_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write header block pushf mov bx, EEFD_Local.ISF_fieldBlock call MemUnlock popf .leave ret ExportEmptyFieldData endp ExportTextFormulaFieldData proc near ETFFD_Local local ImpexStackFrame ETFFD_SSMeta local SSMetaStruc .enter inherit near inc si call ExportTextField .leave ret ExportTextFormulaFieldData endp ExportNumericFormulaFieldData proc near ENFFD_Local local ImpexStackFrame ENFFD_SSMeta local SSMetaStruc .enter inherit near inc si call ExportIntegerField .leave ret ExportNumericFormulaFieldData endp endOF byte 26, 0 ExportEndOfFileChar proc near uses ds, cx, bp EEOFC_Local local ImpexStackFrame EEOFC_SSMeta local SSMetaStruc .enter inherit near segmov ds, cs mov dx, offset endOF ; ds:dx - fptr to string mov cx, 1 ; cx - # of bytes to write out mov bx, EEOFC_Local.ISF_cacheBlock ; bx - handle of cache block call OutputCacheWrite ; write out these two chars .leave ret ExportEndOfFileChar endp Export ends
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/heap/memory-reducer.h" #include "src/flags.h" #include "src/heap/gc-tracer.h" #include "src/heap/heap-inl.h" #include "src/utils.h" #include "src/v8.h" namespace v8 { namespace internal { const int MemoryReducer::kLongDelayMs = 20000; const int MemoryReducer::kShortDelayMs = 500; const int MemoryReducer::kWatchdogDelayMs = 100000; const int MemoryReducer::kMaxNumberOfGCs = 3; MemoryReducer::TimerTask::TimerTask(MemoryReducer* memory_reducer) : CancelableTask(memory_reducer->heap()->isolate()), memory_reducer_(memory_reducer) {} void MemoryReducer::TimerTask::RunInternal() { Heap* heap = memory_reducer_->heap(); Event event; double time_ms = heap->MonotonicallyIncreasingTimeInMs(); heap->tracer()->SampleAllocation(time_ms, heap->NewSpaceAllocationCounter(), heap->OldGenerationAllocationCounter()); event.type = kTimer; event.time_ms = time_ms; event.low_allocation_rate = heap->HasLowAllocationRate(); event.can_start_incremental_gc = heap->incremental_marking()->IsStopped() && heap->incremental_marking()->CanBeActivated(); memory_reducer_->NotifyTimer(event); } void MemoryReducer::NotifyTimer(const Event& event) { DCHECK_EQ(kTimer, event.type); DCHECK_EQ(kWait, state_.action); state_ = Step(state_, event); if (state_.action == kRun) { DCHECK(heap()->incremental_marking()->IsStopped()); DCHECK(FLAG_incremental_marking); if (FLAG_trace_gc_verbose) { PrintIsolate(heap()->isolate(), "Memory reducer: started GC #%d\n", state_.started_gcs); } if (heap()->ShouldOptimizeForMemoryUsage()) { // Do full GC if memory usage has higher priority than latency. This is // important for background tabs that do not send idle notifications. heap()->CollectAllGarbage(Heap::kReduceMemoryFootprintMask, "memory reducer"); } else { heap()->StartIdleIncrementalMarking(); } } else if (state_.action == kWait) { if (!heap()->incremental_marking()->IsStopped() && heap()->ShouldOptimizeForMemoryUsage()) { // Make progress with pending incremental marking if memory usage has // higher priority than latency. This is important for background tabs // that do not send idle notifications. const int kIncrementalMarkingDelayMs = 500; double deadline = heap()->MonotonicallyIncreasingTimeInMs() + kIncrementalMarkingDelayMs; heap()->incremental_marking()->AdvanceIncrementalMarking( 0, deadline, i::IncrementalMarking::StepActions( i::IncrementalMarking::NO_GC_VIA_STACK_GUARD, i::IncrementalMarking::FORCE_MARKING, i::IncrementalMarking::FORCE_COMPLETION)); heap()->FinalizeIncrementalMarkingIfComplete( "Memory reducer: finalize incremental marking"); } // Re-schedule the timer. ScheduleTimer(state_.next_gc_start_ms - event.time_ms); if (FLAG_trace_gc_verbose) { PrintIsolate(heap()->isolate(), "Memory reducer: waiting for %.f ms\n", state_.next_gc_start_ms - event.time_ms); } } } void MemoryReducer::NotifyMarkCompact(const Event& event) { DCHECK_EQ(kMarkCompact, event.type); Action old_action = state_.action; state_ = Step(state_, event); if (old_action != kWait && state_.action == kWait) { // If we are transitioning to the WAIT state, start the timer. ScheduleTimer(state_.next_gc_start_ms - event.time_ms); } if (old_action == kRun) { if (FLAG_trace_gc_verbose) { PrintIsolate(heap()->isolate(), "Memory reducer: finished GC #%d (%s)\n", state_.started_gcs, state_.action == kWait ? "will do more" : "done"); } } } void MemoryReducer::NotifyContextDisposed(const Event& event) { DCHECK_EQ(kContextDisposed, event.type); Action old_action = state_.action; state_ = Step(state_, event); if (old_action != kWait && state_.action == kWait) { // If we are transitioning to the WAIT state, start the timer. ScheduleTimer(state_.next_gc_start_ms - event.time_ms); } } void MemoryReducer::NotifyBackgroundIdleNotification(const Event& event) { DCHECK_EQ(kBackgroundIdleNotification, event.type); Action old_action = state_.action; int old_started_gcs = state_.started_gcs; state_ = Step(state_, event); if (old_action == kWait && state_.action == kWait && old_started_gcs + 1 == state_.started_gcs) { DCHECK(heap()->incremental_marking()->IsStopped()); // TODO(ulan): Replace it with incremental marking GC once // chromium:490559 is fixed. if (event.time_ms > state_.last_gc_time_ms + kLongDelayMs) { heap()->CollectAllGarbage(Heap::kReduceMemoryFootprintMask, "memory reducer background GC"); } else { DCHECK(FLAG_incremental_marking); heap()->StartIdleIncrementalMarking(); if (FLAG_trace_gc_verbose) { PrintIsolate(heap()->isolate(), "Memory reducer: started GC #%d" " (background idle)\n", state_.started_gcs); } } } } bool MemoryReducer::WatchdogGC(const State& state, const Event& event) { return state.last_gc_time_ms != 0 && event.time_ms > state.last_gc_time_ms + kWatchdogDelayMs; } // For specification of this function see the comment for MemoryReducer class. MemoryReducer::State MemoryReducer::Step(const State& state, const Event& event) { if (!FLAG_incremental_marking || !FLAG_memory_reducer) { return State(kDone, 0, 0, state.last_gc_time_ms); } switch (state.action) { case kDone: if (event.type == kTimer || event.type == kBackgroundIdleNotification) { return state; } else { DCHECK(event.type == kContextDisposed || event.type == kMarkCompact); return State( kWait, 0, event.time_ms + kLongDelayMs, event.type == kMarkCompact ? event.time_ms : state.last_gc_time_ms); } case kWait: switch (event.type) { case kContextDisposed: return state; case kTimer: if (state.started_gcs >= kMaxNumberOfGCs) { return State(kDone, kMaxNumberOfGCs, 0.0, state.last_gc_time_ms); } else if (event.can_start_incremental_gc && (event.low_allocation_rate || WatchdogGC(state, event))) { if (state.next_gc_start_ms <= event.time_ms) { return State(kRun, state.started_gcs + 1, 0.0, state.last_gc_time_ms); } else { return state; } } else { return State(kWait, state.started_gcs, event.time_ms + kLongDelayMs, state.last_gc_time_ms); } case kBackgroundIdleNotification: if (event.can_start_incremental_gc && state.started_gcs < kMaxNumberOfGCs) { return State(kWait, state.started_gcs + 1, event.time_ms + kLongDelayMs, state.last_gc_time_ms); } else { return state; } case kMarkCompact: return State(kWait, state.started_gcs, event.time_ms + kLongDelayMs, event.time_ms); } case kRun: if (event.type != kMarkCompact) { return state; } else { if (state.started_gcs < kMaxNumberOfGCs && (event.next_gc_likely_to_collect_more || state.started_gcs == 1)) { return State(kWait, state.started_gcs, event.time_ms + kShortDelayMs, event.time_ms); } else { return State(kDone, kMaxNumberOfGCs, 0.0, event.time_ms); } } } UNREACHABLE(); return State(kDone, 0, 0, 0.0); // Make the compiler happy. } void MemoryReducer::ScheduleTimer(double delay_ms) { DCHECK(delay_ms > 0); // Leave some room for precision error in task scheduler. const double kSlackMs = 100; v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(heap()->isolate()); auto timer_task = new MemoryReducer::TimerTask(this); V8::GetCurrentPlatform()->CallDelayedOnForegroundThread( isolate, timer_task, (delay_ms + kSlackMs) / 1000.0); } void MemoryReducer::TearDown() { state_ = State(kDone, 0, 0, 0.0); } } // namespace internal } // namespace v8
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %rcx lea addresses_UC_ht+0x10277, %r11 clflush (%r11) nop nop nop nop nop cmp $61281, %rcx mov $0x6162636465666768, %r15 movq %r15, %xmm1 and $0xffffffffffffffc0, %r11 movaps %xmm1, (%r11) add %r11, %r11 pop %rcx pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r8 push %r9 push %rsi // Faulty Load lea addresses_normal+0x1ef7, %r8 nop nop nop nop nop xor $19311, %r13 movb (%r8), %r9b lea oracles, %r13 and $0xff, %r9 shlq $12, %r9 mov (%r13,%r9,1), %r9 pop %rsi pop %r9 pop %r8 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_normal', 'same': False, 'size': 32, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_normal', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 16, 'congruent': 7, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
[org 0x0600] [bits 16] global _start _start: cli xor ax, ax mov ss, ax mov sp, ax mov ds, ax mov es, ax mov cx, 0x0100 ; 256 WORDs in MBR mov si, 0x7C00 ; Current MBR Address mov di, 0x0600 ; New MBR Address rep movsw ; Copy MBR jmp 0x0:safe_start safe_start: mov [boot_drive], dl ; Remember that the BIOS sets us the boot drive in 'dl' on boot mov bp, sp sti mov bx, WelcomeString call Print call PrintHex call PrintLn mov bx, partition_1 mov cx, 4 ; there are 4 partitions loop: mov al, byte [bx] test al, 0x80 jnz found add bx, 0x10 dec cx jnz loop jmp no_active_part found: mov word [partition_off], bx add bx, 8 mov ebx, dword [bx] ; LBA start mov di, 0x7C00 mov cx, 1 call ReadDisk cmp word [0x7DFE], 0xAA55 ; Check Boot Signature jne not_bootable mov si, word [partition_off] mov dl, byte [boot_drive] jmp 0x0:0x7C00 ; Jump To VBR no_active_part: mov bx, NoActivePartitionString call Print jmp $ not_bootable: mov bx, NotBootablePartitionString call Print jmp $ %include "print.asm" %include "disk_reader.asm" WelcomeString: db "MBR loaded! Active disk: ", 0x00 NoActivePartitionString: db "No active partition!", 0x00 NotBootablePartitionString: db "Active partition is not bootable!", 0x00 boot_drive: db 0 partition_off: db 0 times 0x1B4 - ($ - $$) nop UID: times 10 db 0 partition_1: db 0x80 ; Active partition db 0x00 ; CHS start db 0x00 db 0x00 db 0x00 ; Partition type db 0x00 ; CHS end db 0x00 db 0x00 dd 0x01 ; LBA start dd 333 ; LBA size, 1 + 64 + 12 + 256 = 333 partition_2: db 0x00 ; Not active partition db 0x00 ; CHS start db 0x00 db 0x00 db 0x0B ; Partition type db 0x00 ; CHS end db 0x00 db 0x00 dd 334 ; LBA start dd 93750 ; LBA size, the size of our HackOS_FAT.img partition_3: times 16 db 0 partition_4: times 16 db 0 boot_signature: dw 0xAA55
;============================================================== ; SEGA MEGA DRIVE/GENESIS - DEMO 3 - SPRITES SAMPLE ;============================================================== ; by Big Evil Corporation ;============================================================== ; A small, discreet, and complete sprites sample, with a healthy ; dose of comments and explanations for beginners. ; Runs on genuine hardware, and (hopefully) all emulators. ; ; I recommend reading and understanding the Scroll Planes ; sample first. ; ; To assemble this program with ASM68K.EXE: ; ASM68K.EXE /p sprites.asm,sprites.bin,sprites.map,sprites.lst ; ; To assemble this program with SNASM68K.EXE: ; SNASM68K.EXE /p sprites.asm,sprites.map,sprites.lst,sprites.bin ; ; sprites.asm = this source file ; sprites.bin = the binary file, fire this up in your emulator! ; sprites.lst = listing file, shows assembled addresses alongside ; your source code, open in a text editor ; sprites.map = symbol map file for linking (unused) ;============================================================== ; Start of ROM ROM_Start: ;============================================================== ; CPU VECTOR TABLE ;============================================================== dc.l 0x00FFE000 ; Initial stack pointer value dc.l CPU_EntryPoint ; Start of program dc.l CPU_Exception ; Bus error dc.l CPU_Exception ; Address error dc.l CPU_Exception ; Illegal instruction dc.l CPU_Exception ; Division by zero dc.l CPU_Exception ; CHK CPU_Exception dc.l CPU_Exception ; TRAPV CPU_Exception dc.l CPU_Exception ; Privilege violation dc.l INT_Null ; TRACE exception dc.l INT_Null ; Line-A emulator dc.l INT_Null ; Line-F emulator dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Spurious exception dc.l INT_Null ; IRQ level 1 dc.l INT_Null ; IRQ level 2 dc.l INT_Null ; IRQ level 3 dc.l INT_HInterrupt ; IRQ level 4 (horizontal retrace interrupt) dc.l INT_Null ; IRQ level 5 dc.l INT_VInterrupt ; IRQ level 6 (vertical retrace interrupt) dc.l INT_Null ; IRQ level 7 dc.l INT_Null ; TRAP #00 exception dc.l INT_Null ; TRAP #01 exception dc.l INT_Null ; TRAP #02 exception dc.l INT_Null ; TRAP #03 exception dc.l INT_Null ; TRAP #04 exception dc.l INT_Null ; TRAP #05 exception dc.l INT_Null ; TRAP #06 exception dc.l INT_Null ; TRAP #07 exception dc.l INT_Null ; TRAP #08 exception dc.l INT_Null ; TRAP #09 exception dc.l INT_Null ; TRAP #10 exception dc.l INT_Null ; TRAP #11 exception dc.l INT_Null ; TRAP #12 exception dc.l INT_Null ; TRAP #13 exception dc.l INT_Null ; TRAP #14 exception dc.l INT_Null ; TRAP #15 exception dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) dc.l INT_Null ; Unused (reserved) ;============================================================== ; SEGA MEGA DRIVE ROM HEADER ;============================================================== dc.b "SEGA MEGA DRIVE " ; Console name dc.b "BIGEVILCORP. " ; Copyright holder and release date dc.b "HELLO WORLD " ; Domestic name dc.b "HELLO WORLD " ; International name dc.b "GM XXXXXXXX-XX" ; Version number dc.w 0x0000 ; Checksum dc.b "J " ; I/O support dc.l ROM_Start ; Start address of ROM dc.l ROM_End-1 ; End address of ROM dc.l 0x00FF0000 ; Start address of RAM dc.l 0x00FF0000+0x0000FFFF ; End address of RAM dc.l 0x00000000 ; SRAM enabled dc.l 0x00000000 ; Unused dc.l 0x00000000 ; Start address of SRAM dc.l 0x00000000 ; End address of SRAM dc.l 0x00000000 ; Unused dc.l 0x00000000 ; Unused dc.b " " ; Notes (unused) dc.b " E " ; Country codes ;============================================================== ; INITIAL VDP REGISTER VALUES ;============================================================== ; In this demo, we're particularly interested in register 0x5, ; which specifies the address of the Sprite Attribute Table ; (SAT) within VRAM. Here it's set to 0xF000. ;============================================================== VDPRegisters: dc.b 0x14 ; 0x00: H interrupt on, palettes on dc.b 0x74 ; 0x01: V interrupt on, display on, DMA on, Genesis mode on dc.b 0x30 ; 0x02: Pattern table for Scroll Plane A at VRAM 0xC000 (bits 3-5 = bits 13-15) dc.b 0x00 ; 0x03: Pattern table for Window Plane at VRAM 0x0000 (disabled) (bits 1-5 = bits 11-15) dc.b 0x07 ; 0x04: Pattern table for Scroll Plane B at VRAM 0xE000 (bits 0-2 = bits 11-15) dc.b 0x78 ; 0x05: Sprite Attribute Table at VRAM 0xF000 (bits 0-6 = bits 9-15) dc.b 0x00 ; 0x06: Unused dc.b 0x00 ; 0x07: Background colour: bits 0-3 = colour, bits 4-5 = palette dc.b 0x00 ; 0x08: Unused dc.b 0x00 ; 0x09: Unused dc.b 0x08 ; 0x0A: Frequency of Horiz. interrupt in Rasters (number of lines travelled by the beam) dc.b 0x00 ; 0x0B: External interrupts off, V scroll per-page, H scroll per-page dc.b 0x81 ; 0x0C: Shadows and highlights off, interlace off, H40 mode (320 x 224 screen res) dc.b 0x3F ; 0x0D: Horiz. scroll table at VRAM 0xFC00 (bits 0-5) dc.b 0x00 ; 0x0E: Unused dc.b 0x02 ; 0x0F: Autoincrement 2 bytes dc.b 0x01 ; 0x10: Scroll plane size: 64x32 tiles dc.b 0x00 ; 0x11: Window Plane X pos 0 left (pos in bits 0-4, left/right in bit 7) dc.b 0x00 ; 0x12: Window Plane Y pos 0 up (pos in bits 0-4, up/down in bit 7) dc.b 0xFF ; 0x13: DMA length lo byte dc.b 0xFF ; 0x14: DMA length hi byte dc.b 0x00 ; 0x15: DMA source address lo byte dc.b 0x00 ; 0x16: DMA source address mid byte dc.b 0x80 ; 0x17: DMA source address hi byte, memory-to-VRAM mode (bits 6-7) even ;============================================================== ; CONSTANTS ;============================================================== ; VDP port addresses vdp_control equ 0x00C00004 vdp_data equ 0x00C00000 ; VDP commands vdp_cmd_vram_write equ 0x40000000 vdp_cmd_cram_write equ 0xC0000000 vdp_cmd_vsram_write equ 0x40000010 ; VDP memory addresses ; according to VDP registers 0x2, 0x4, 0x5, and 0xD (see table above) vram_addr_tiles equ 0x0000 vram_addr_plane_a equ 0xC000 vram_addr_plane_b equ 0xE000 vram_addr_sprite_table equ 0xF000 ; NEW in this demo - the Sprite Attribute Table (SAT) vram_addr_hscroll equ 0xFC00 ; Screen width and height (in pixels) vdp_screen_width equ 0x0140 vdp_screen_height equ 0x00F0 ; The plane width and height (in tiles) ; according to VDP register 0x10 (see table above) vdp_plane_width equ 0x40 vdp_plane_height equ 0x20 ; The size of the sprite plane (512x512 pixels) ; ; With only a 320x240 display size, a lot of this ; is off screen, which is useful for hiding sprites ; when not needed (saves needing to adjust the linked ; list in the attribute table). vdp_sprite_plane_width equ 0x0200 vdp_sprite_plane_height equ 0x0200 ; The sprite border (invisible area left + top) size ; ; The sprite plane is 512x512 pixels, but is offset by ; -128 pixels in both X and Y directions. To see a sprite ; on screen at 0,0 we need to offset its position by ; this border. vdp_sprite_border_x equ 0x80 vdp_sprite_border_y equ 0x80 ; Hardware version address hardware_ver_address equ 0x00A10001 ; TMSS tmss_address equ 0x00A14000 tmss_signature equ 'SEGA' ; The size of a word and longword size_word equ 2 size_long equ 4 ; The size of one palette (in bytes, words, and longwords) size_palette_b equ 0x20 size_palette_w equ size_palette_b/size_word size_palette_l equ size_palette_b/size_long ; The size of one graphics tile (in bytes, words, and longwords) size_tile_b equ 0x20 size_tile_w equ size_tile_b/size_word size_tile_l equ size_tile_b/size_long ; Sprite initial draw positions (in pixels) sprite_1_start_pos_x equ vdp_sprite_border_x sprite_1_start_pos_y equ vdp_sprite_border_y sprite_2_start_pos_x equ vdp_sprite_border_x+0x0040 sprite_2_start_pos_y equ vdp_sprite_border_y+0x0020 ; Speed (in pixels per frame) to move our sprites sprite_1_move_speed_x equ 0x1 sprite_1_move_speed_y equ 0x1 sprite_2_move_speed_x equ 0x2 sprite_2_move_speed_y equ 0x0 ;============================================================== ; VRAM WRITE MACROS ;============================================================== ; Set the VRAM (video RAM) address to write to next SetVRAMWrite: macro addr move.l #(vdp_cmd_vram_write)|((\addr)&$3FFF)<<16|(\addr)>>14, vdp_control endm ; Set the CRAM (colour RAM) address to write to next SetCRAMWrite: macro addr move.l #(vdp_cmd_cram_write)|((\addr)&$3FFF)<<16|(\addr)>>14, vdp_control endm ; Set the VSRAM (vertical scroll RAM) address to write to next SetVSRAMWrite: macro addr move.l #(vdp_cmd_vsram_write)|((\addr)&$3FFF)<<16|(\addr)>>14, vdp_control endm ;============================================================== ; SPRITE ATTRIBUTE MACRO ;============================================================== ; A macro to help build an entry in the Sprite Attribute ; Table, since manipulating structures and bit twiddling isn't ; the focus of this demo, and would make the code harder to ; read. ;============================================================== ; Proper game implementations would make use of a local SAT ; table in RAM and use DMA to transfer the table to VRAM each ; frame (which also allows us to use RAM like a "stream" to write ; this data more efficiently) but this is the best method for ; teaching the basics first. ;============================================================== ; Each sprite attribute entry is in the following format: ; ; Y coordinate 1 word - the Y coordinate on the sprite plane ; Dimensions bits 1 byte - bits describing the layout (1x1 tiles up to 4x4 tiles) ; Linked list next 1 byte - the index of the next sprite to draw, or 0 if end of list ; Prio/palette/flip 1 byte - the priority (bit 15), palette (bits 14-13), ; v/h flip (bits 12 and 11), and top 3 bits of the tile ID ; Tile ID bottom 1 byte - the bottom 8 bits of the tile ID ; X coordinate 1 word - the X coordinate on the sprite plane ;============================================================== ; Writes a sprite attribute structure to 4 registers, ready to write to VRAM BuildSpriteStructure: macro x_pos, ; X pos on sprite plane y_pos, ; Y pos on sprite plane dimension_bits, ; Sprite tile dimensions (4 bits) next_id, ; Next sprite index in linked list priority_bit, ; Draw priority palette_id, ; Palette index flip_x, ; Flip horizontally flip_y, ; Flip vertically tile_id, ; First tile index reg1, ; Output: reg1 reg2, ; Output: reg2 reg3, ; Output: reg3 reg4 ; Output: reg4 move.w #y_pos, \reg1 move.w #(\dimension_bits<<8|\next_id), \reg2 move.w #(\priority_bit<<14|\palette_id<<13|\flip_x<<11|\flip_y<<10|\tile_id), \reg3 move.w #x_pos, \reg4 endm ;============================================================== ; MEMORY MAP ;============================================================== ; We need to store the current sprite positions in RAM and update ; them each frame. There are a few ways to create a memory map, ; but the cleanest, simplest, and easiest to maintain method ; uses the assembler's "RS" keywords. RSSET begins a new table of ; offsets starting from any other offset (here we're starting at ; 0x00FF0000, the start of RAM), and allows us to add named entries ; of any size for the "variables". We can then read/write these ; variables using the offsets' labels (see INT_VInterrupt for use ; cases). ;============================================================== RSSET 0x00FF0000 ; Start a new offset table from beginning of RAM ram_sprite_1_pos_x rs.w 1 ; 1 table entry of word size for sprite 1's X pos ram_sprite_1_pos_y rs.w 1 ; 1 table entry of word size for sprite 1's Y pos ram_sprite_2_pos_x rs.w 1 ; 1 table entry of word size for sprite 2's X pos ram_sprite_2_pos_y rs.w 1 ; 1 table entry of word size for sprite 2's Y pos ; !! Be careful when adding any table entries of BYTE size, since ; you'll need to start worrying about alignment. More of this in a ; future demo. ;============================================================== ; PALETTE ;============================================================== ; In this demo we'll be using one palette per sprite, ; so we've added a palette count to upload the correct number ; of entries. ;============================================================== Palettes: ; Palette for sprite 1 Palette1: dc.w 0x0000 dc.w 0x0020 dc.w 0x0EEE dc.w 0x00AC dc.w 0x02EA dc.w 0x00EE dc.w 0x0008 dc.w 0x000C dc.w 0x000A dc.w 0x0000 dc.w 0x0000 dc.w 0x0000 dc.w 0x0000 dc.w 0x0000 dc.w 0x0000 dc.w 0x0000 ; Palette for sprite 2 Palette2: dc.w 0x0000 dc.w 0x0004 dc.w 0x0226 dc.w 0x0040 dc.w 0x0446 dc.w 0x0262 dc.w 0x0662 dc.w 0x004A dc.w 0x0468 dc.w 0x0882 dc.w 0x006C dc.w 0x0202 dc.w 0x04A0 dc.w 0x0AC2 dc.w 0x06AE dc.w 0x02EC ; Number of palettes to write to CRAM palette_count equ 0x2 ;============================================================== ; TILE IDs ;============================================================== ; The indices of the first tile in each sprite. We only need ; to tell the sprite table where to find the starting tile of ; each sprite, so we don't bother keeping track of every tile ; index. ; ; Note we still leave the first tile blank (planes A and B are ; filled with tile 0) so we'll be uploading our sprite tiles ; from index 1. ; ; See bottom of the file for the sprite tiles themselves. ;============================================================== tile_id_blank equ 0x00 ; The blank tile at index 0 tile_id_sprite_1 equ 0x01 ; Sprite 1 index (4 tiles) tile_id_sprite_2 equ 0x05 ; Sprite 2 index (12 tiles) ; Total number of tiles in the sprites to upload to VRAM tile_count equ 0x11 ; Total tiles = 16 ;============================================================== ; CODE ENTRY POINT ;============================================================== CPU_EntryPoint: ;============================================================== ; Initialise the Mega Drive ;============================================================== ; Write the TMSS signature (if a model 1+ Mega Drive) jsr VDP_WriteTMSS ; Load the initial VDP registers jsr VDP_LoadRegisters ;============================================================== ; Clear VRAM (video memory) ;============================================================== ; Setup the VDP to write to VRAM address 0x0000 (start of VRAM) SetVRAMWrite 0x0000 ; Write 0's across all of VRAM move.w #(0x00010000/size_word)-1, d0 ; Loop counter = 64kb, in words (-1 for DBRA loop) @ClrVramLp: ; Start of loop move.w #0x0, vdp_data ; Write a 0x0000 (word size) to VRAM dbra d0, @ClrVramLp ; Decrement d0 and loop until finished (when d0 reaches -1) ;============================================================== ; Write the palettes to CRAM (colour memory) ;============================================================== ; Setup the VDP to write to CRAM address 0x0000 (first palette) SetCRAMWrite 0x0000 ; Write the palettes to CRAM ; ; This time we're writing multiple palettes, so multiply the word count ; by the palette count (and don't forget the -1 for the loop counter). lea Palettes, a0 ; Move palette address to a0 move.w #(palette_count*size_palette_w)-1, d0 ; Loop counter = 8 words in palette (-1 for DBRA loop) @PalLp: ; Start of loop move.w (a0)+, vdp_data ; Write palette entry, post-increment address dbra d0, @PalLp ; Decrement d0 and loop until finished (when d0 reaches -1) ;============================================================== ; Write the sprite tiles to VRAM ;============================================================== ; Setup the VDP to write to VRAM address 0x0020 (the address of the first sprite tile, index 1) ; ; We need to leave the first tile blank (we cleared VRAM, so it should be all 0's) for ; planes A and B to display, so skip the first tile (offset address by size_tile_b). SetVRAMWrite vram_addr_tiles+size_tile_b ; Write the sprite tiles to VRAM lea sprite_tiles, a0 ; Move the address of the first graphics tile into a0 move.w #(tile_count*size_tile_l)-1, d0 ; Loop counter = 8 longwords per tile * num tiles (-1 for DBRA loop) @CharLp: ; Start of loop move.l (a0)+, vdp_data ; Write tile line (4 bytes per line), and post-increment address dbra d0, @CharLp ; Decrement d0 and loop until finished (when d0 reaches -1) ;============================================================== ; Set up the Sprite Attribute Table (SAT) ;============================================================== ; The Sprite Attribute Table is a table of sprites to draw. ; Each entry in the table describes the first tile ID, the number ; of tiles to draw (and their layout), the X and Y position ; (on the 512x512 sprite plane), the palette to draw with, a ; priority flag, and X/Y flipping flags. ; ; Sprites can be layed out in these tile dimensions: ; ; 1x1 (1 tile) - 0000 ; 1x2 (2 tiles) - 0001 ; 1x3 (3 tiles) - 0010 ; 1x4 (4 tiles) - 0011 ; 2x1 (2 tiles) - 0100 ; 2x2 (4 tiles) - 0101 ; 2x3 (6 tiles) - 0110 ; 2x4 (8 tiles) - 0111 ; 3x1 (3 tiles) - 1000 ; 3x2 (6 tiles) - 1001 ; 3x3 (9 tiles) - 1010 ; 3x4 (12 tiles)- 1011 ; 4x1 (4 tiles) - 1100 ; 4x2 (8 tiles) - 1101 ; 4x3 (12 tiles)- 1110 ; 4x4 (16 tiles)- 1111 ; ; The tiles are layed out in COLUMN MAJOR, rather than planes A and B ; which are row major. Tiles within a sprite cannot be reused (since it ; only accepts a starting tile and a count/layout) so the whole sprite ; needs uploading to VRAM in one consecutive chunk, even if some tiles ; are duplicates. ; ; The X/Y flipping flags take the layout into account, you don't need ; to re-adjust the layout, position, or tile IDs to flip the entire ; sprite as a whole. ; ; There are 64 entries in the table, but the number of them drawn, ; and the order in which they're processed, is determined by a linked ; list. Each sprite entry has an index to the NEXT sprite to be drawn. ; If this index is 0, the list ends, and the VDP won't draw any more ; sprites this frame. ; Start writing to the sprite attribute table in VRAM SetVRAMWrite vram_addr_sprite_table ;============================================================== ; Set up sprite 1 ; Write all values into registers first to make it easier. We ; write to VRAM one word at a time (auto-increment is set to 2 ; in VDP register 0xF), so we'll assign each word to a register. ; ; Since bit twiddling and manipulating structures isn't the focus of ; this sample, we have a macro to simplify this part. ; Position: sprite_1_start_pos_x,sprite_1_start_pos_y ; Dimensions: 2x2 tiles (8 tiles total) = 0101 in binary (see table above) ; Next link: sprite index 1 is next to be processed ; Priority: 0 ; Palette id: 0 ; Flip X: 0 ; Flip Y: 0 ; Tile id: tile_id_sprite_1 BuildSpriteStructure sprite_1_start_pos_x,sprite_1_start_pos_y,%0101,0x1,0x0,0x0,0x0,0x0,tile_id_sprite_1,d0,d1,d2,d3 ; Write the entire sprite attribute structure to the sprite table move.w d0, vdp_data move.w d1, vdp_data move.w d2, vdp_data move.w d3, vdp_data ;============================================================== ; Set up sprite 2 ; Position: sprite_2_start_pos_x,sprite_2_start_pos_y ; Dimensions: 4x3 tiles (16 tiles total) = 1110 in binary (see table above) ; Next link: sprite index 0 (end of linked list) ; Priority: 0 ; Palette id: 1 ; Flip X: 0 ; Flip Y: 0 ; Tile id: tile_id_sprite_2 BuildSpriteStructure sprite_2_start_pos_x,sprite_2_start_pos_y,%1110,0x0,0x0,0x1,0x0,0x0,tile_id_sprite_2,d0,d1,d2,d3 ; Write the entire sprite attribute structure to the sprite table move.w d0, vdp_data move.w d1, vdp_data move.w d2, vdp_data move.w d3, vdp_data ;============================================================== ; Intitialise variables in RAM ;============================================================== move.w #sprite_1_start_pos_x, ram_sprite_1_pos_x move.w #sprite_1_start_pos_y, ram_sprite_1_pos_y move.w #sprite_2_start_pos_x, ram_sprite_2_pos_x move.w #sprite_2_start_pos_y, ram_sprite_2_pos_y ;============================================================== ; Initialise status register and set interrupt level. ; This begins firing vertical and horizontal interrupts. ; ; Since the vinterrupt does something meaningful in this ; demo, we start this AFTER setting up the VDP to draw and ; intialising the variables in RAM. ;============================================================== move.w #0x2300, sr ; Finished! ;============================================================== ; Loop forever ;============================================================== ; This loops forever, effectively ending our main routine, ; but the VDP will continue to run of its own accord and ; will still fire vertical and horizontal interrupts (which is ; where our update code is), so the demo continues to run. ; ; For a game, it would be better to use this loop for processing ; input and game code, and wait here until next vblank before ; looping again. We only use vinterrupt for updates in this demo ; for simplicity (because we don't yet have any timing code). @InfiniteLp: bra @InfiniteLp ;============================================================== ; INTERRUPT ROUTINES ;============================================================== ; Vertical interrupt - run once per frame (50hz in PAL, 60hz in NTSC) INT_VInterrupt: ; Fetch current sprite coordinates from RAM move.w ram_sprite_1_pos_x, d0 move.w ram_sprite_1_pos_y, d1 move.w ram_sprite_2_pos_x, d2 move.w ram_sprite_2_pos_y, d3 ; Animate them (x/y coords are 9 bits, so this ; wraps around the whole 512x512 sprite plane) addi.w #sprite_1_move_speed_x, d0 addi.w #sprite_1_move_speed_y, d1 addi.w #sprite_2_move_speed_x, d2 addi.w #sprite_2_move_speed_y, d3 ; Store updated values back in RAM for next frame move.w d0, ram_sprite_1_pos_x move.w d1, ram_sprite_1_pos_y move.w d2, ram_sprite_2_pos_x move.w d3, ram_sprite_2_pos_y ; Write updated coordinates to the Sprite Attribute Table in VRAM. ; Each entry is 8 bytes in size, so sprite 1 is at table+0x0000, ; and sprite 2 is at table+0x0008. ; ; The Y coord is the 1st word in the structure, and the X coord is ; the 4th. As already noted, there are cleaner ways to do this, ; like storing the tables in RAM and copying them via DMA every ; frame, but that's beyond the focus of this sample. ; Sprite 1's Y coordinate is at table+0x0000 SetVRAMWrite vram_addr_sprite_table+0x0000 move.w d1, vdp_data ; Sprite 1's X coordinate is at table+0x0006 SetVRAMWrite vram_addr_sprite_table+0x0006 move.w d0, vdp_data ; Sprite 2's Y coordinate is at table+0x0008 SetVRAMWrite vram_addr_sprite_table+0x0008 move.w d3, vdp_data ; Sprite 2's X coordinate is at table+0x000E SetVRAMWrite vram_addr_sprite_table+0x000E move.w d2, vdp_data rte ; Horizontal interrupt - run once per N scanlines (N = specified in VDP register 0xA) INT_HInterrupt: ; Doesn't do anything in this demo rte ; NULL interrupt - for interrupts we don't care about INT_Null: rte ; Exception interrupt - called if an error has occured CPU_Exception: ; Just halt the CPU if an error occurred stop #0x2700 rte ;============================================================== ; UTILITY FUNCTIONS ;============================================================== VDP_WriteTMSS: ; Poke the TMSS to show "LICENSED BY SEGA..." message and allow us to ; access the VDP (or it will lock up on first access). move.b hardware_ver_address, d0 ; Move Megadrive hardware version to d0 andi.b #0x0F, d0 ; The version is stored in last four bits, so mask it with 0F beq @SkipTMSS ; If version is equal to 0, skip TMSS signature move.l #tmss_signature, tmss_address ; Move the string "SEGA" to 0xA14000 @SkipTMSS: ; Check VDP move.w vdp_control, d0 ; Read VDP status register (hangs if no access) rts VDP_LoadRegisters: ; Set VDP registers lea VDPRegisters, a0 ; Load address of register table into a0 move.w #0x18-1, d0 ; 24 registers to write (-1 for loop counter) move.w #0x8000, d1 ; 'Set register 0' command to d1 @CopyRegLp: move.b (a0)+, d1 ; Move register value from table to lower byte of d1 (and post-increment the table address for next time) move.w d1, vdp_control ; Write command and value to VDP control port addi.w #0x0100, d1 ; Increment register # dbra d0, @CopyRegLp ; Decrement d0, and jump back to top of loop if d0 is still >= 0 rts ;============================================================== ; SPRITE TILES ;============================================================== ; The sprite graphics tiles. Too big to paste in here, so we'll ; include them from external files at the bottom of the ROM. ; ; If your tile data is in binary format rather than text, use ; INCBIN instead of INCLUDE. ;============================================================== sprite_tiles: ; Sprite 1 - a red Fuzzl, 2x2 tiles include "sprite1.asm" ; Sprite 2 - a bouncy mushroom, 4x3 tiles include "sprite2.asm" ; The end of ROM ROM_End:
; A158636: a(n) = 576*n^2 - 24. ; 552,2280,5160,9192,14376,20712,28200,36840,46632,57576,69672,82920,97320,112872,129576,147432,166440,186600,207912,230376,253992,278760,304680,331752,359976,389352,419880,451560,484392,518376,553512,589800,627240,665832,705576,746472,788520,831720,876072,921576,968232,1016040,1065000,1115112,1166376,1218792,1272360,1327080,1382952,1439976,1498152,1557480,1617960,1679592,1742376,1806312,1871400,1937640,2005032,2073576,2143272,2214120,2286120,2359272,2433576,2509032,2585640,2663400,2742312,2822376,2903592,2985960,3069480,3154152,3239976,3326952,3415080,3504360,3594792,3686376,3779112,3873000,3968040,4064232,4161576,4260072,4359720,4460520,4562472,4665576,4769832,4875240,4981800,5089512,5198376,5308392,5419560,5531880,5645352,5759976,5875752,5992680,6110760,6229992,6350376,6471912,6594600,6718440,6843432,6969576,7096872,7225320,7354920,7485672,7617576,7750632,7884840,8020200,8156712,8294376,8433192,8573160,8714280,8856552,8999976,9144552,9290280,9437160,9585192,9734376,9884712,10036200,10188840,10342632,10497576,10653672,10810920,10969320,11128872,11289576,11451432,11614440,11778600,11943912,12110376,12277992,12446760,12616680,12787752,12959976,13133352,13307880,13483560,13660392,13838376,14017512,14197800,14379240,14561832,14745576,14930472,15116520,15303720,15492072,15681576,15872232,16064040,16257000,16451112,16646376,16842792,17040360,17239080,17438952,17639976,17842152,18045480,18249960,18455592,18662376,18870312,19079400,19289640,19501032,19713576,19927272,20142120,20358120,20575272,20793576,21013032,21233640,21455400,21678312,21902376,22127592,22353960,22581480,22810152,23039976,23270952,23503080,23736360,23970792,24206376,24443112,24681000,24920040,25160232,25401576,25644072,25887720,26132520,26378472,26625576,26873832,27123240,27373800,27625512,27878376,28132392,28387560,28643880,28901352,29159976,29419752,29680680,29942760,30205992,30470376,30735912,31002600,31270440,31539432,31809576,32080872,32353320,32626920,32901672,33177576,33454632,33732840,34012200,34292712,34574376,34857192,35141160,35426280,35712552,35999976 mov $1,2 add $1,$0 mul $1,$0 mul $1,576 add $1,552
/* $info$ tags: Bin|Opt desc: Unused $end_info$ */ #include <FEXCore/Config/Config.h> #include "Common/ArgumentLoader.h" #include <memory> int main(int argc, char **argv, char **const envp) { FEXCore::Config::Initialize(); FEXCore::Config::AddLayer(FEXCore::Config::CreateMainLayer()); FEXCore::Config::AddLayer(std::make_unique<FEX::ArgLoader::ArgLoader>(argc, argv)); FEXCore::Config::AddLayer(FEXCore::Config::CreateEnvironmentLayer(envp)); FEXCore::Config::Load(); }
<% from pwnlib.shellcraft.mips.linux import syscall %> <%page args="fd, length"/> <%docstring> Invokes the syscall ftruncate64. See 'man 2 ftruncate64' for more information. Arguments: fd(int): fd length(off64_t): length </%docstring> ${syscall('SYS_ftruncate64', fd, length)}