text
stringlengths
1
1.05M
;=============================================================================== ; BASIC Loader *=$0801 ; 10 SYS (2064) byte $0E, $08, $0A, $00, $9E, $20, $28, $32 byte $30, $36, $34, $29, $00, $00, $00 ; Our code starts at $0810 (2064 decimal) ; after the 15 bytes for the BASIC loader ;=============================================================================== ; Initialize ; Turn off interrupts to stop LIBSCREEN_WAIT failing every so ; often when the kernal interrupt syncs up with the scanline test sei ; Disable run/stop + restore keys lda #$FC sta $0328 ; Set border and background colors ; The last 3 parameters are not used yet LIBSCREEN_SETCOLORS Black, Black, Black, Black, Black ; Fill 1000 bytes (40x25) of screen memory LIBSCREEN_SET1000 SCREENRAM, SpaceCharacter ; Fill 1000 bytes (40x25) of color memory LIBSCREEN_SET1000 COLORRAM, White ; Set sprite multicolors LIBSPRITE_SETMULTICOLORS_VV MediumGray, DarkGray ; Set the memory location of the custom character set LIBSCREEN_SETCHARMEMORY 14 ; Initialize the game jsr gameAliensInit jsr gamePlayerInit ;=============================================================================== ; Update gMLoop ; Wait for scanline 255 LIBSCREEN_WAIT_V 255 ; Start code timer change border color ;inc EXTCOL ; Update the library jsr libInputUpdate jsr libSpritesUpdate ; Update the game jsr gameAliensUpdate jsr gameStarsUpdate jsr gamePlayerUpdate jsr gameBulletsUpdate ; End code timer reset border color ;dec EXTCOL ; Loop back to the start of the game loop jmp gMLoop
; A033890: a(n) = Fibonacci(4*n+2). ; 1,8,55,377,2584,17711,121393,832040,5702887,39088169,267914296,1836311903,12586269025,86267571272,591286729879,4052739537881,27777890035288,190392490709135,1304969544928657,8944394323791464,61305790721611591,420196140727489673,2880067194370816120,19740274219868223167,135301852344706746049,927372692193078999176,6356306993006846248183,43566776258854844738105,298611126818977066918552,2046711111473984623691759,14028366653498915298923761,96151855463018422468774568,659034621587630041982498215,4517090495650391871408712937,30960598847965113057878492344,212207101440105399533740733471,1454489111232772683678306641953,9969216677189303386214405760200,68330027629092351019822533679447,468340976726457153752543329995929,3210056809456107725247980776292056,22002056689466296922983322104048463,150804340016807970735635273952047185 mul $0,2 mov $1,1 mov $2,1 lpb $0 sub $0,1 add $2,$1 add $1,$2 lpe mov $0,$1
// Copyright (c) 2017-2020, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "axom/mint/config.hpp" // for compile-time type // definitions #include "axom/mint/mesh/blueprint.hpp" // for blueprint functions #include "axom/mint/mesh/CellTypes.hpp" // for CellTypes enum definition #include "axom/mint/mesh/ParticleMesh.hpp" // for ParticleMesh #include "axom/mint/mesh/UniformMesh.hpp" // for UniformMesh #include "StructuredMesh_helpers.hpp" // for StructuredMesh test helpers #include "axom/slic/interface/slic.hpp" // for slic macros // Sidre includes #ifdef AXOM_MINT_USE_SIDRE #include "axom/sidre/core/sidre.hpp" // for sidre classes namespace sidre = axom::sidre; #endif #include "gtest/gtest.h" // for gtest macros using namespace axom::mint; using IndexType = axom::IndexType; // globals const char* IGNORE_OUTPUT = ".*"; //------------------------------------------------------------------------------ // HELPER METHODS //------------------------------------------------------------------------------ namespace { //------------------------------------------------------------------------------ #ifdef AXOM_MINT_USE_SIDRE void check_sidre_group( sidre::Group* root_group, int expected_dimension, const double* expected_origin, const double* expected_spacing ) { EXPECT_TRUE( blueprint::isValidRootGroup( root_group ) ); const sidre::Group* topology = blueprint::getTopologyGroup( root_group ); EXPECT_TRUE( blueprint::isValidTopologyGroup( topology ) ); EXPECT_EQ( topology->getParent()->getNumGroups(), 1 ); EXPECT_EQ( topology->getParent()->getNumViews(), 0 ); const sidre::Group* coordset = blueprint::getCoordsetGroup( root_group, topology ); EXPECT_TRUE( blueprint::isValidCoordsetGroup( coordset ) ); EXPECT_EQ( coordset->getParent()->getNumGroups(), 1 ); EXPECT_EQ( coordset->getParent()->getNumViews(), 0 ); int mesh_type = UNDEFINED_MESH; int dimension = -1; blueprint::getMeshTypeAndDimension( mesh_type, dimension, root_group ); EXPECT_EQ( mesh_type, STRUCTURED_UNIFORM_MESH ); EXPECT_EQ( dimension, expected_dimension ); double mesh_origin[ 3 ]; double mesh_spacing[ 3 ]; blueprint::getUniformMeshProperties( dimension, mesh_origin, mesh_spacing, coordset ); for ( int i=0 ; i < dimension ; ++i ) { EXPECT_DOUBLE_EQ( expected_origin[ i ], mesh_origin[ i ] ); EXPECT_DOUBLE_EQ( expected_spacing[ i ], mesh_spacing[ i ] ); } } #endif } //------------------------------------------------------------------------------ // UNIT TESTS //------------------------------------------------------------------------------ TEST( mint_mesh_uniform_mesh_DeathTest, invalid_construction ) { const double lo[] = { 0.0, 0.0, 0.0 }; const double hi[] = { 2.0, 2.0, 2.0 }; const IndexType Ni = 5; const IndexType Nj = 5; const IndexType Nk = 5; EXPECT_DEATH_IF_SUPPORTED( UniformMesh( nullptr, hi, Ni, Nj, Nk ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( UniformMesh( lo, nullptr, Ni,Nj,Nk ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( UniformMesh( lo, hi, -1 ), IGNORE_OUTPUT ); #ifdef AXOM_MINT_USE_SIDRE sidre::DataStore ds; sidre::Group* root = ds.getRoot(); sidre::Group* valid_group = root->createGroup( "mesh" ); sidre::Group* particle_mesh = root->createGroup( "particle_mesh" ); ParticleMesh( 3, 10, particle_mesh ); // check pull constructor EXPECT_DEATH_IF_SUPPORTED( UniformMesh( root, "" ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( UniformMesh( particle_mesh, "" ), IGNORE_OUTPUT ); // check push constructor EXPECT_DEATH_IF_SUPPORTED( UniformMesh( particle_mesh, lo, hi, Ni, Nj, Nk ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( UniformMesh( nullptr, lo, hi, Ni, Nj, Nk ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( UniformMesh( valid_group, lo, nullptr, Ni, Nj, Nk ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( UniformMesh( valid_group, nullptr, hi, Ni, Nj, Nk ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( UniformMesh( valid_group, lo, hi, -1), IGNORE_OUTPUT ); #endif } //------------------------------------------------------------------------------ TEST( mint_mesh_uniform_mesh_DeathTest, invalid_operations ) { const double low[] = { 0.0, 0.0, 0.0 }; const double high[] = { 0.5, 0.5, 0.5 }; const IndexType Ni = 4; const IndexType Nj = 4; const IndexType Nk = 4; UniformMesh m( low, high, Ni, Nj, Nk ); EXPECT_DEATH_IF_SUPPORTED( m.getCoordinateArray( 0 ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( m.getCoordinateArray( 1 ), IGNORE_OUTPUT ); EXPECT_DEATH_IF_SUPPORTED( m.getCoordinateArray( 2 ), IGNORE_OUTPUT ); } //------------------------------------------------------------------------------ TEST( mint_mesh_uniform_mesh, native_constructor ) { constexpr int NDIMS = 3; const double lo[] = { 0.0, 0.0, 0.0 }; const double hi[] = { 2.0, 2.0, 2.0 }; const double h[] = { 0.5, 0.5, 0.5 }; const IndexType N[] = { 5, 5, 5 }; const int64 node_ext[] = { -55, -51, 10, 14, 0, 4 }; for ( int idim=1 ; idim <= NDIMS ; ++idim ) { UniformMesh* m; switch ( idim ) { case 1: m = new UniformMesh( lo, hi, N[0] ); break; case 2: m = new UniformMesh( lo, hi, N[0], N[1] ); break; default: EXPECT_TRUE( idim==3 ); m = new UniformMesh( lo, hi, N[0], N[1], N[2] ); } internal::check_constructor( m, idim, lo, h, N ); EXPECT_FALSE( m->hasSidreGroup() ); internal::check_create_fields( m ); internal::check_fields( m, false ); m->setExtent( idim, node_ext ); internal::check_node_extent( m, node_ext ); delete m; } // END for all dimensions } #ifdef AXOM_MINT_USE_SIDRE //------------------------------------------------------------------------------ TEST( mint_mesh_uniform_mesh, sidre_constructor ) { constexpr int NDIMS = 3; const double lo[] = { 0.0, 0.0, 0.0 }; const double hi[] = { 2.0, 2.0, 2.0 }; const double h[] = { 0.5, 0.5, 0.5 }; const IndexType N[] = { 5, 5, 5 }; const int64 node_ext[] = { -55, -51, 10, 14, 0, 4 }; for ( int idim=1 ; idim <= NDIMS ; ++idim ) { // STEP 0: create a datastore to store the mesh. sidre::DataStore ds; sidre::Group* root = ds.getRoot(); sidre::Group* meshGroup = root->createGroup( "mesh" ); // STEP 1: create a uniform mesh in Sidre. UniformMesh* m; switch ( idim ) { case 1: m = new UniformMesh( meshGroup, lo, hi, N[0] ); break; case 2: m = new UniformMesh( meshGroup, lo, hi, N[0], N[1] ); break; default: EXPECT_TRUE( idim==3 ); m = new UniformMesh( meshGroup, lo, hi, N[0], N[1], N[2] ); } // END switch EXPECT_TRUE( m->hasSidreGroup() ); internal::check_constructor( m, idim, lo, h, N ); internal::check_create_fields( m ); m->setExtent( idim, node_ext ); internal::check_node_extent( m, node_ext ); delete m; m = nullptr; // STEP 2: pull the mesh from the sidre groups, and check with expected m = new UniformMesh( meshGroup ); internal::check_constructor( m, idim, lo, h, N ); internal::check_fields( m, true ); internal::check_node_extent( m, node_ext ); delete m; // STEP 3: ensure the data is persistent in sidre check_sidre_group( meshGroup, idim, lo, h ); } } #endif //------------------------------------------------------------------------------ TEST( mint_mesh_uniform_mesh, check_evaluate_coordinate ) { constexpr int NDIMS = 3; const double lo[] = { 0.0, 0.0, 0.0 }; const double hi[] = { 2.0, 2.0, 2.0 }; const double h[] = { 0.5, 0.5, 0.5 }; const IndexType N[] = { 5, 5, 5 }; for ( int idim=1 ; idim <= NDIMS ; ++idim ) { switch ( idim ) { case 1: { UniformMesh m( lo, hi, N[ 0 ] ); internal::check_constructor( &m, idim, lo, h, N ); EXPECT_FALSE( m.hasSidreGroup() ); const IndexType Ni = m.getNodeResolution( I_DIRECTION ); EXPECT_EQ( Ni, N[ I_DIRECTION ] ); for ( IndexType i=0 ; i < Ni ; ++i ) { const double expected_x = lo[ X_COORDINATE ] + i * h[ X_COORDINATE ]; const double x = m.evaluateCoordinate( i, I_DIRECTION ); EXPECT_DOUBLE_EQ( expected_x, x ); } // END for all i } // END 1D break; case 2: { UniformMesh m( lo, hi, N[ 0 ], N[ 1 ] ); internal::check_constructor( &m, idim, lo, h, N ); EXPECT_FALSE( m.hasSidreGroup() ); const IndexType Ni = m.getNodeResolution( I_DIRECTION ); const IndexType Nj = m.getNodeResolution( J_DIRECTION ); EXPECT_EQ( Ni, N[ I_DIRECTION ] ); EXPECT_EQ( Nj, N[ J_DIRECTION ] ); for ( IndexType j=0 ; j < Nj ; ++j ) { for ( IndexType i=0 ; i < Ni ; ++i ) { const double expected_x = lo[ X_COORDINATE ] + i * h[ X_COORDINATE ]; const double expected_y = lo[ Y_COORDINATE ] + j * h[ Y_COORDINATE ]; const double x = m.evaluateCoordinate( i, I_DIRECTION ); const double y = m.evaluateCoordinate( j, J_DIRECTION ); EXPECT_DOUBLE_EQ( expected_x, x ); EXPECT_DOUBLE_EQ( expected_y, y ); } // END for all i } // END for all j } // END 2D break; default: EXPECT_EQ( idim, 3 ); { UniformMesh m( lo, hi, N[ 0 ], N[ 1 ], N[ 2 ] ); internal::check_constructor( &m, idim, lo, h, N ); EXPECT_FALSE( m.hasSidreGroup() ); const IndexType Ni = m.getNodeResolution( I_DIRECTION ); const IndexType Nj = m.getNodeResolution( J_DIRECTION ); const IndexType Nk = m.getNodeResolution( K_DIRECTION ); EXPECT_EQ( Ni, N[ I_DIRECTION ] ); EXPECT_EQ( Nj, N[ J_DIRECTION ] ); EXPECT_EQ( Nk, N[ K_DIRECTION ] ); for ( IndexType k=0 ; k < Nk ; ++k ) { for ( IndexType j=0 ; j < Nj ; ++j ) { for ( IndexType i=0 ; i < Ni ; ++i ) { const double expected_x = lo[ X_COORDINATE ] + i* h[ X_COORDINATE ]; const double expected_y = lo[ Y_COORDINATE ] + j* h[ Y_COORDINATE ]; const double expected_z = lo[ Z_COORDINATE ] + k* h[ Z_COORDINATE ]; const double x = m.evaluateCoordinate( i, I_DIRECTION ); const double y = m.evaluateCoordinate( j, J_DIRECTION ); const double z = m.evaluateCoordinate( k, K_DIRECTION ); EXPECT_DOUBLE_EQ( expected_x, x ); EXPECT_DOUBLE_EQ( expected_y, y ); EXPECT_DOUBLE_EQ( expected_z, z ); } // END for all i } // END for all j } // END for all k } // END 3D } // END switch } } //------------------------------------------------------------------------------ #include "axom/slic/core/UnitTestLogger.hpp" using axom::slic::UnitTestLogger; int main(int argc, char* argv[]) { int result = 0; ::testing::InitGoogleTest(&argc, argv); UnitTestLogger logger; // create & initialize test logger, // finalized when exiting main scope result = RUN_ALL_TESTS(); return result; }
; A330395: Number of nontrivial equivalence classes of S_n under the {1234,3412} pattern-replacement equivalence. ; 1,9,26,51,85,129,184,251,331,425,534,659,801,961,1140,1339,1559,1801,2066,2355,2669,3009,3376,3771,4195,4649,5134,5651,6201,6785,7404,8059,8751,9481,10250,11059,11909,12801,13736,14715,15739,16809,17926,19091,20305,21569,22884,24251,25671,27145,28674,30259,31901,33601,35360,37179,39059,41001,43006,45075,47209,49409,51676,54011,56415,58889,61434,64051,66741,69505,72344,75259,78251,81321,84470,87699,91009,94401,97876,101435,105079,108809,112626,116531,120525,124609,128784,133051,137411,141865 mov $3,$0 add $3,1 mov $6,$0 lpb $3 mov $0,$6 sub $3,1 sub $0,$3 mov $7,$0 add $7,1 mov $9,$0 mov $10,0 lpb $7 mov $0,$9 sub $7,1 sub $0,$7 mov $2,$0 mov $4,$0 mov $5,8 mov $8,5 lpb $2 lpb $5 mul $0,2 add $8,$4 trn $5,$8 lpe add $0,8 mov $2,0 lpe mov $4,$0 div $4,2 add $4,1 add $10,$4 lpe add $1,$10 lpe mov $0,$1
; ; z88dk library: Generic VDP support code ; ; ; $Id: gen_clg.asm,v 1.2 2010/09/15 09:00:39 stefano Exp $ ; XLIB clg LIB msx_set_mode LIB msx_color LIB FILVRM .clg ld hl,2 ; set graphics mode call msx_set_mode ld hl,15 push hl ; border push hl ; paper ld hl,0 ; ink push hl call msx_color pop hl pop hl pop hl ld bc,6144 ; set VRAM attribute area ld a,$1F ld hl,8192 push bc call FILVRM pop bc ; clear VRAM picture area xor a ld h,a ld l,a jp FILVRM
; A214856: Number of triangular numbers in interval ](n-1)^2, n^2] for n>0, a(0)=1. ; 1,1,1,1,2,1,2,1,1,2,1,2,1,1,2,1,2,1,1,2,1,2,1,2,1,1,2,1,2,1,1,2,1,2,1,2,1,1,2,1,2,1,1,2,1,2,1,1,2,1,2,1,2,1,1,2,1,2,1,1,2,1,2,1,2,1,1,2,1,2,1,1,2,1 mov $7,$0 mov $9,2 lpb $9,1 mov $0,$7 sub $9,1 add $0,$9 sub $0,1 pow $0,2 mov $2,$0 mov $4,1 mov $5,$0 lpb $2,1 lpb $5,1 add $4,1 trn $5,$4 lpe mov $2,$3 lpe mov $6,$9 mov $8,$4 lpb $6,1 mov $1,$8 sub $6,1 lpe lpe lpb $7,1 sub $1,$8 mov $7,0 lpe
// Boost.Function library // Copyright Douglas Gregor 2002-2003. 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) // For more information, see http://www.boost.org #define BOOST_FUNCTION_NUM_ARGS 10 #include <boost/function/detail/maybe_include.hpp> #undef BOOST_FUNCTION_NUM_ARGS
* Sprite cf10 * * Mode 4 * +|------------+ * - gg ggg g g - * |g g gg g g| * |g g g g g| * |g gg g g g| * |g g g g g| * |g g g g g| * | gg g ggg g | * +|------------+ * section sprite xdef sp_cf10 xref sp_zero sp_cf10 dc.w $0100,$0000 dc.w 13,7,0,0 dc.l sc4_cf10-* dc.l sp_zero-* dc.l 0 sc4_cf10 dc.w $6E00,$9000 dc.w $8900,$A800 dc.w $8800,$A800 dc.w $8C00,$A800 dc.w $8800,$A800 dc.w $8800,$A800 dc.w $6900,$D000 * end
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.16.27026.1 TITLE Z:\Sources\Lunor\Repos\rougemeilland\Palmtree.Math.Core.Implements\Palmtree.Math.Core.Implements\pmc_exclusiveor.c .686P .XMM include listing.inc .model flat INCLUDELIB MSVCRTD INCLUDELIB OLDNAMES msvcjmc SEGMENT __7B7A869E_ctype@h DB 01H __457DD326_basetsd@h DB 01H __4384A2D9_corecrt_memcpy_s@h DB 01H __4E51A221_corecrt_wstring@h DB 01H __2140C079_string@h DB 01H __1887E595_winnt@h DB 01H __9FC7C64B_processthreadsapi@h DB 01H __FA470AEC_memoryapi@h DB 01H __F37DAFF1_winerror@h DB 01H __7A450CCC_winbase@h DB 01H __B4B40122_winioctl@h DB 01H __86261D59_stralign@h DB 01H __7B8DBFC3_pmc_uint_internal@h DB 01H __6B0481B0_pmc_inline_func@h DB 01H __6904D90E_pmc_exclusiveor@c DB 01H msvcjmc ENDS PUBLIC _Initialize_ExclusiveOr PUBLIC _PMC_ExclusiveOr_I_X@12 PUBLIC _PMC_ExclusiveOr_L_X@16 PUBLIC _PMC_ExclusiveOr_X_I@12 PUBLIC _PMC_ExclusiveOr_X_L@16 PUBLIC _PMC_ExclusiveOr_X_X@12 PUBLIC __JustMyCode_Default EXTRN _CheckBlockLight:PROC EXTRN _AllocateNumber:PROC EXTRN _DeallocateNumber:PROC EXTRN _CommitNumber:PROC EXTRN _CheckNumber:PROC EXTRN _DuplicateNumber:PROC EXTRN _From_I_Imp:PROC EXTRN _From_L_Imp:PROC EXTRN @_RTC_CheckStackVars@8:PROC EXTRN @__CheckForDebuggerJustMyCode@4:PROC EXTRN __RTC_CheckEsp:PROC EXTRN __RTC_InitBase:PROC EXTRN __RTC_Shutdown:PROC EXTRN __aullshr:PROC EXTRN _number_zero:BYTE ; COMDAT rtc$TMZ rtc$TMZ SEGMENT __RTC_Shutdown.rtc$TMZ DD FLAT:__RTC_Shutdown rtc$TMZ ENDS ; COMDAT rtc$IMZ rtc$IMZ SEGMENT __RTC_InitBase.rtc$IMZ DD FLAT:__RTC_InitBase rtc$IMZ ENDS ; Function compile flags: /Odt ; COMDAT __JustMyCode_Default _TEXT SEGMENT __JustMyCode_Default PROC ; COMDAT push ebp mov ebp, esp pop ebp ret 0 __JustMyCode_Default ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _nw_light_check_code$1 = -84 ; size = 4 _w_bit_count$2 = -76 ; size = 4 _v_bit_count$3 = -72 ; size = 4 _u_bit_count$4 = -68 ; size = 4 _nw_light_check_code$5 = -60 ; size = 4 _w_bit_count$6 = -52 ; size = 4 _v_bit_count$7 = -48 ; size = 4 _nw_light_check_code$8 = -40 ; size = 4 _w_bit_count$9 = -32 ; size = 4 _v_bit_count$10 = -28 ; size = 4 _v_lo$11 = -24 ; size = 4 _v_hi$12 = -16 ; size = 4 _u_bit_count$13 = -8 ; size = 4 _result$ = -4 ; size = 4 _u$ = 8 ; size = 4 _v$ = 12 ; size = 8 _w$ = 20 ; size = 4 _PMC_ExclusiveOr_X_L_Imp PROC ; 282 : { push ebp mov ebp, esp sub esp, 88 ; 00000058H push edi lea edi, DWORD PTR [ebp-88] mov ecx, 22 ; 00000016H mov eax, -858993460 ; ccccccccH rep stosd mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 283 : PMC_STATUS_CODE result; ; 284 : if (u->IS_ZERO) mov eax, DWORD PTR _u$[ebp] mov ecx, DWORD PTR [eax+24] shr ecx, 1 and ecx, 1 je SHORT $LN2@PMC_Exclus ; 285 : { ; 286 : // x が 0 である場合 ; 287 : if (v == 0) mov edx, DWORD PTR _v$[ebp] or edx, DWORD PTR _v$[ebp+4] jne SHORT $LN4@PMC_Exclus ; 288 : { ; 289 : // v が 0 である場合 ; 290 : *w = &number_zero; mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax], OFFSET _number_zero ; 291 : } jmp SHORT $LN5@PMC_Exclus $LN4@PMC_Exclus: ; 292 : else ; 293 : { ; 294 : // v が 0 でない場合 ; 295 : if ((result = From_L_Imp(v, w)) != PMC_STATUS_OK) mov ecx, DWORD PTR _w$[ebp] push ecx mov edx, DWORD PTR _v$[ebp+4] push edx mov eax, DWORD PTR _v$[ebp] push eax call _From_L_Imp add esp, 12 ; 0000000cH mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN5@PMC_Exclus ; 296 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN5@PMC_Exclus: ; 297 : } ; 298 : } jmp $LN3@PMC_Exclus $LN2@PMC_Exclus: ; 299 : else if (v == 0) mov ecx, DWORD PTR _v$[ebp] or ecx, DWORD PTR _v$[ebp+4] jne SHORT $LN7@PMC_Exclus ; 300 : { ; 301 : // y が 0 である場合 ; 302 : if ((result = DuplicateNumber(u, w)) != PMC_STATUS_OK) mov edx, DWORD PTR _w$[ebp] push edx mov eax, DWORD PTR _u$[ebp] push eax call _DuplicateNumber add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN9@PMC_Exclus ; 303 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN9@PMC_Exclus: ; 304 : } jmp $LN3@PMC_Exclus $LN7@PMC_Exclus: ; 305 : else ; 306 : { ; 307 : // u と v がともに 0 ではない場合 ; 308 : if (__UNIT_TYPE_BIT_COUNT < sizeof(v) * 8) mov ecx, 1 test ecx, ecx je $LN10@PMC_Exclus ; 309 : { ; 310 : // _UINT64_T が 1 ワードで表現しきれない場合 ; 311 : __UNIT_TYPE u_bit_count = u->UNIT_BIT_COUNT; mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+12] mov DWORD PTR _u_bit_count$13[ebp], eax ; 312 : _UINT32_T v_hi; ; 313 : _UINT32_T v_lo = _FROMDWORDTOWORD(v, &v_hi); lea ecx, DWORD PTR _v_hi$12[ebp] push ecx mov edx, DWORD PTR _v$[ebp+4] push edx mov eax, DWORD PTR _v$[ebp] push eax call __FROMDWORDTOWORD add esp, 12 ; 0000000cH mov DWORD PTR _v_lo$11[ebp], eax ; 314 : if (v_hi == 0) cmp DWORD PTR _v_hi$12[ebp], 0 jne $LN12@PMC_Exclus ; 315 : { ; 316 : // v の値が 32bit で表現可能な場合 ; 317 : __UNIT_TYPE v_bit_count = sizeof(v_lo) * 8 - _LZCNT_ALT_32(v_lo); mov ecx, DWORD PTR _v_lo$11[ebp] push ecx call __LZCNT_ALT_32 add esp, 4 mov edx, 32 ; 00000020H sub edx, eax mov DWORD PTR _v_bit_count$10[ebp], edx ; 318 : __UNIT_TYPE w_bit_count = _MAXIMUM_UNIT(u_bit_count, v_bit_count); mov eax, DWORD PTR _v_bit_count$10[ebp] push eax mov ecx, DWORD PTR _u_bit_count$13[ebp] push ecx call __MAXIMUM_UNIT add esp, 8 mov DWORD PTR _w_bit_count$9[ebp], eax ; 319 : __UNIT_TYPE nw_light_check_code; ; 320 : if ((result = AllocateNumber(w, w_bit_count, &nw_light_check_code)) != PMC_STATUS_OK) lea edx, DWORD PTR _nw_light_check_code$8[ebp] push edx mov eax, DWORD PTR _w_bit_count$9[ebp] push eax mov ecx, DWORD PTR _w$[ebp] push ecx call _AllocateNumber add esp, 12 ; 0000000cH mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN14@PMC_Exclus ; 321 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN14@PMC_Exclus: ; 322 : ExclusiveOr_X_1W(u->BLOCK, u->UNIT_WORD_COUNT, v_lo, (*w)->BLOCK); mov edx, DWORD PTR _w$[ebp] mov eax, DWORD PTR [edx] mov ecx, DWORD PTR [eax+32] push ecx mov edx, DWORD PTR _v_lo$11[ebp] push edx mov eax, DWORD PTR _u$[ebp] mov ecx, DWORD PTR [eax+8] push ecx mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+32] push eax call _ExclusiveOr_X_1W add esp, 16 ; 00000010H ; 323 : if ((result = CheckBlockLight((*w)->BLOCK, nw_light_check_code)) != PMC_STATUS_OK) mov ecx, DWORD PTR _nw_light_check_code$8[ebp] push ecx mov edx, DWORD PTR _w$[ebp] mov eax, DWORD PTR [edx] mov ecx, DWORD PTR [eax+32] push ecx call _CheckBlockLight add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN15@PMC_Exclus ; 324 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN15@PMC_Exclus: ; 325 : } jmp $LN13@PMC_Exclus $LN12@PMC_Exclus: ; 326 : else ; 327 : { ; 328 : // y の値が 32bit では表現できない場合 ; 329 : __UNIT_TYPE v_bit_count = sizeof(v) * 8 - _LZCNT_ALT_32(v_hi); mov edx, DWORD PTR _v_hi$12[ebp] push edx call __LZCNT_ALT_32 add esp, 4 mov ecx, 64 ; 00000040H sub ecx, eax mov DWORD PTR _v_bit_count$7[ebp], ecx ; 330 : __UNIT_TYPE w_bit_count = _MAXIMUM_UNIT(u_bit_count, v_bit_count); mov edx, DWORD PTR _v_bit_count$7[ebp] push edx mov eax, DWORD PTR _u_bit_count$13[ebp] push eax call __MAXIMUM_UNIT add esp, 8 mov DWORD PTR _w_bit_count$6[ebp], eax ; 331 : __UNIT_TYPE nw_light_check_code; ; 332 : if ((result = AllocateNumber(w, w_bit_count, &nw_light_check_code)) != PMC_STATUS_OK) lea ecx, DWORD PTR _nw_light_check_code$5[ebp] push ecx mov edx, DWORD PTR _w_bit_count$6[ebp] push edx mov eax, DWORD PTR _w$[ebp] push eax call _AllocateNumber add esp, 12 ; 0000000cH mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN16@PMC_Exclus ; 333 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN16@PMC_Exclus: ; 334 : ExclusiveOr_X_2W(u->BLOCK, u->UNIT_WORD_COUNT, v_hi, v_lo, (*w)->BLOCK); mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx+32] push eax mov ecx, DWORD PTR _v_lo$11[ebp] push ecx mov edx, DWORD PTR _v_hi$12[ebp] push edx mov eax, DWORD PTR _u$[ebp] mov ecx, DWORD PTR [eax+8] push ecx mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+32] push eax call _ExclusiveOr_X_2W add esp, 20 ; 00000014H ; 335 : if ((result = CheckBlockLight((*w)->BLOCK, nw_light_check_code)) != PMC_STATUS_OK) mov ecx, DWORD PTR _nw_light_check_code$5[ebp] push ecx mov edx, DWORD PTR _w$[ebp] mov eax, DWORD PTR [edx] mov ecx, DWORD PTR [eax+32] push ecx call _CheckBlockLight add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN13@PMC_Exclus ; 336 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN13@PMC_Exclus: ; 337 : } ; 338 : } jmp $LN11@PMC_Exclus $LN10@PMC_Exclus: ; 339 : else ; 340 : { ; 341 : // _UINT64_T が 1 ワードで表現できる場合 ; 342 : ; 343 : __UNIT_TYPE u_bit_count = u->UNIT_BIT_COUNT; mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+12] mov DWORD PTR _u_bit_count$4[ebp], eax ; 344 : __UNIT_TYPE v_bit_count = sizeof(v) * 8 - _LZCNT_ALT_UNIT((__UNIT_TYPE)v); mov ecx, DWORD PTR _v$[ebp] push ecx call __LZCNT_ALT_UNIT add esp, 4 mov edx, 64 ; 00000040H sub edx, eax mov DWORD PTR _v_bit_count$3[ebp], edx ; 345 : __UNIT_TYPE w_bit_count = _MAXIMUM_UNIT(u_bit_count, v_bit_count) + 1; mov eax, DWORD PTR _v_bit_count$3[ebp] push eax mov ecx, DWORD PTR _u_bit_count$4[ebp] push ecx call __MAXIMUM_UNIT add esp, 8 add eax, 1 mov DWORD PTR _w_bit_count$2[ebp], eax ; 346 : __UNIT_TYPE nw_light_check_code; ; 347 : if ((result = AllocateNumber(w, w_bit_count, &nw_light_check_code)) != PMC_STATUS_OK) lea edx, DWORD PTR _nw_light_check_code$1[ebp] push edx mov eax, DWORD PTR _w_bit_count$2[ebp] push eax mov ecx, DWORD PTR _w$[ebp] push ecx call _AllocateNumber add esp, 12 ; 0000000cH mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN18@PMC_Exclus ; 348 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN18@PMC_Exclus: ; 349 : ExclusiveOr_X_1W(u->BLOCK, u->UNIT_WORD_COUNT, (__UNIT_TYPE)v, (*w)->BLOCK); mov edx, DWORD PTR _w$[ebp] mov eax, DWORD PTR [edx] mov ecx, DWORD PTR [eax+32] push ecx mov edx, DWORD PTR _v$[ebp] push edx mov eax, DWORD PTR _u$[ebp] mov ecx, DWORD PTR [eax+8] push ecx mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+32] push eax call _ExclusiveOr_X_1W add esp, 16 ; 00000010H ; 350 : if ((result = CheckBlockLight((*w)->BLOCK, nw_light_check_code)) != PMC_STATUS_OK) mov ecx, DWORD PTR _nw_light_check_code$1[ebp] push ecx mov edx, DWORD PTR _w$[ebp] mov eax, DWORD PTR [edx] mov ecx, DWORD PTR [eax+32] push ecx call _CheckBlockLight add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN11@PMC_Exclus ; 351 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN11@PMC_Exclus: ; 352 : } ; 353 : CommitNumber(*w); mov edx, DWORD PTR _w$[ebp] mov eax, DWORD PTR [edx] push eax call _CommitNumber add esp, 4 ; 354 : if ((*w)->IS_ZERO) mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx+24] shr eax, 1 and eax, 1 je SHORT $LN3@PMC_Exclus ; 355 : { ; 356 : DeallocateNumber(*w); mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] push edx call _DeallocateNumber add esp, 4 ; 357 : *w = &number_zero; mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax], OFFSET _number_zero $LN3@PMC_Exclus: ; 358 : } ; 359 : } ; 360 : return (PMC_STATUS_OK); xor eax, eax $LN1@PMC_Exclus: ; 361 : } push edx mov ecx, ebp push eax lea edx, DWORD PTR $LN27@PMC_Exclus call @_RTC_CheckStackVars@8 pop eax pop edx pop edi add esp, 88 ; 00000058H cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 npad 2 $LN27@PMC_Exclus: DD 4 DD $LN26@PMC_Exclus $LN26@PMC_Exclus: DD -16 ; fffffff0H DD 4 DD $LN22@PMC_Exclus DD -40 ; ffffffd8H DD 4 DD $LN23@PMC_Exclus DD -60 ; ffffffc4H DD 4 DD $LN24@PMC_Exclus DD -84 ; ffffffacH DD 4 DD $LN25@PMC_Exclus $LN25@PMC_Exclus: DB 110 ; 0000006eH DB 119 ; 00000077H DB 95 ; 0000005fH DB 108 ; 0000006cH DB 105 ; 00000069H DB 103 ; 00000067H DB 104 ; 00000068H DB 116 ; 00000074H DB 95 ; 0000005fH DB 99 ; 00000063H DB 104 ; 00000068H DB 101 ; 00000065H DB 99 ; 00000063H DB 107 ; 0000006bH DB 95 ; 0000005fH DB 99 ; 00000063H DB 111 ; 0000006fH DB 100 ; 00000064H DB 101 ; 00000065H DB 0 $LN24@PMC_Exclus: DB 110 ; 0000006eH DB 119 ; 00000077H DB 95 ; 0000005fH DB 108 ; 0000006cH DB 105 ; 00000069H DB 103 ; 00000067H DB 104 ; 00000068H DB 116 ; 00000074H DB 95 ; 0000005fH DB 99 ; 00000063H DB 104 ; 00000068H DB 101 ; 00000065H DB 99 ; 00000063H DB 107 ; 0000006bH DB 95 ; 0000005fH DB 99 ; 00000063H DB 111 ; 0000006fH DB 100 ; 00000064H DB 101 ; 00000065H DB 0 $LN23@PMC_Exclus: DB 110 ; 0000006eH DB 119 ; 00000077H DB 95 ; 0000005fH DB 108 ; 0000006cH DB 105 ; 00000069H DB 103 ; 00000067H DB 104 ; 00000068H DB 116 ; 00000074H DB 95 ; 0000005fH DB 99 ; 00000063H DB 104 ; 00000068H DB 101 ; 00000065H DB 99 ; 00000063H DB 107 ; 0000006bH DB 95 ; 0000005fH DB 99 ; 00000063H DB 111 ; 0000006fH DB 100 ; 00000064H DB 101 ; 00000065H DB 0 $LN22@PMC_Exclus: DB 118 ; 00000076H DB 95 ; 0000005fH DB 104 ; 00000068H DB 105 ; 00000069H DB 0 _PMC_ExclusiveOr_X_L_Imp ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _nz_check_code$1 = -24 ; size = 4 _w_bit_count$2 = -16 ; size = 4 _v_bit_count$3 = -12 ; size = 4 _u_bit_count$4 = -8 ; size = 4 _result$ = -4 ; size = 4 _u$ = 8 ; size = 4 _v$ = 12 ; size = 4 _w$ = 16 ; size = 4 _PMC_ExclusiveOr_X_I_Imp PROC ; 188 : { push ebp mov ebp, esp sub esp, 28 ; 0000001cH mov eax, -858993460 ; ccccccccH mov DWORD PTR [ebp-28], eax mov DWORD PTR [ebp-24], eax mov DWORD PTR [ebp-20], eax mov DWORD PTR [ebp-16], eax mov DWORD PTR [ebp-12], eax mov DWORD PTR [ebp-8], eax mov DWORD PTR [ebp-4], eax mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 189 : PMC_STATUS_CODE result; ; 190 : if (u->IS_ZERO) mov eax, DWORD PTR _u$[ebp] mov ecx, DWORD PTR [eax+24] shr ecx, 1 and ecx, 1 je SHORT $LN2@PMC_Exclus ; 191 : { ; 192 : // u が 0 である場合 ; 193 : if (v == 0) cmp DWORD PTR _v$[ebp], 0 jne SHORT $LN4@PMC_Exclus ; 194 : { ; 195 : // v が 0 である場合 ; 196 : *w = &number_zero; mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx], OFFSET _number_zero ; 197 : } jmp SHORT $LN5@PMC_Exclus $LN4@PMC_Exclus: ; 198 : else ; 199 : { ; 200 : // v が 0 でない場合 ; 201 : if ((result = From_I_Imp(v, w)) != PMC_STATUS_OK) mov eax, DWORD PTR _w$[ebp] push eax mov ecx, DWORD PTR _v$[ebp] push ecx call _From_I_Imp add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN5@PMC_Exclus ; 202 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN5@PMC_Exclus: ; 203 : } ; 204 : } jmp $LN3@PMC_Exclus $LN2@PMC_Exclus: ; 205 : else if (v == 0) cmp DWORD PTR _v$[ebp], 0 jne SHORT $LN7@PMC_Exclus ; 206 : { ; 207 : // v が 0 である場合 ; 208 : if ((result = DuplicateNumber(u, w)) != PMC_STATUS_OK) mov edx, DWORD PTR _w$[ebp] push edx mov eax, DWORD PTR _u$[ebp] push eax call _DuplicateNumber add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN9@PMC_Exclus ; 209 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN9@PMC_Exclus: ; 210 : } jmp $LN3@PMC_Exclus $LN7@PMC_Exclus: ; 211 : else ; 212 : { ; 213 : // x と y がともに 0 ではない場合 ; 214 : __UNIT_TYPE u_bit_count = u->UNIT_BIT_COUNT; mov ecx, DWORD PTR _u$[ebp] mov edx, DWORD PTR [ecx+12] mov DWORD PTR _u_bit_count$4[ebp], edx ; 215 : __UNIT_TYPE v_bit_count = sizeof(v) * 8 - _LZCNT_ALT_32(v); mov eax, DWORD PTR _v$[ebp] push eax call __LZCNT_ALT_32 add esp, 4 mov ecx, 32 ; 00000020H sub ecx, eax mov DWORD PTR _v_bit_count$3[ebp], ecx ; 216 : __UNIT_TYPE w_bit_count = _MAXIMUM_UNIT(u_bit_count, v_bit_count) + 1; mov edx, DWORD PTR _v_bit_count$3[ebp] push edx mov eax, DWORD PTR _u_bit_count$4[ebp] push eax call __MAXIMUM_UNIT add esp, 8 add eax, 1 mov DWORD PTR _w_bit_count$2[ebp], eax ; 217 : __UNIT_TYPE nz_check_code; ; 218 : if ((result = AllocateNumber(w, w_bit_count, &nz_check_code)) != PMC_STATUS_OK) lea ecx, DWORD PTR _nz_check_code$1[ebp] push ecx mov edx, DWORD PTR _w_bit_count$2[ebp] push edx mov eax, DWORD PTR _w$[ebp] push eax call _AllocateNumber add esp, 12 ; 0000000cH mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN10@PMC_Exclus ; 219 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN10@PMC_Exclus: ; 220 : ExclusiveOr_X_1W(u->BLOCK, u->UNIT_WORD_COUNT, v, (*w)->BLOCK); mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx+32] push eax mov ecx, DWORD PTR _v$[ebp] push ecx mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+8] push eax mov ecx, DWORD PTR _u$[ebp] mov edx, DWORD PTR [ecx+32] push edx call _ExclusiveOr_X_1W add esp, 16 ; 00000010H ; 221 : if ((result = CheckBlockLight((*w)->BLOCK, nz_check_code)) != PMC_STATUS_OK) mov eax, DWORD PTR _nz_check_code$1[ebp] push eax mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx+32] push eax call _CheckBlockLight add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN11@PMC_Exclus ; 222 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN11@PMC_Exclus: ; 223 : CommitNumber(*w); mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] push edx call _CommitNumber add esp, 4 ; 224 : if ((*w)->IS_ZERO) mov eax, DWORD PTR _w$[ebp] mov ecx, DWORD PTR [eax] mov edx, DWORD PTR [ecx+24] shr edx, 1 and edx, 1 je SHORT $LN3@PMC_Exclus ; 225 : { ; 226 : DeallocateNumber(*w); mov eax, DWORD PTR _w$[ebp] mov ecx, DWORD PTR [eax] push ecx call _DeallocateNumber add esp, 4 ; 227 : *w = &number_zero; mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx], OFFSET _number_zero $LN3@PMC_Exclus: ; 228 : } ; 229 : } ; 230 : return (PMC_STATUS_OK); xor eax, eax $LN1@PMC_Exclus: ; 231 : } push edx mov ecx, ebp push eax lea edx, DWORD PTR $LN16@PMC_Exclus call @_RTC_CheckStackVars@8 pop eax pop edx add esp, 28 ; 0000001cH cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 $LN16@PMC_Exclus: DD 1 DD $LN15@PMC_Exclus $LN15@PMC_Exclus: DD -24 ; ffffffe8H DD 4 DD $LN14@PMC_Exclus $LN14@PMC_Exclus: DB 110 ; 0000006eH DB 122 ; 0000007aH DB 95 ; 0000005fH DB 99 ; 00000063H DB 104 ; 00000068H DB 101 ; 00000065H DB 99 ; 00000063H DB 107 ; 0000006bH DB 95 ; 0000005fH DB 99 ; 00000063H DB 111 ; 0000006fH DB 100 ; 00000064H DB 101 ; 00000065H DB 0 _PMC_ExclusiveOr_X_I_Imp ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _count$ = -12 ; size = 4 _cp_count$ = -8 ; size = 4 _or_count$ = -4 ; size = 4 _u$ = 8 ; size = 4 _u_count$ = 12 ; size = 4 _v$ = 16 ; size = 4 _v_count$ = 20 ; size = 4 _w$ = 24 ; size = 4 _ExclusiveOr_X_X PROC ; 73 : { push ebp mov ebp, esp sub esp, 12 ; 0000000cH push esi mov DWORD PTR [ebp-12], -858993460 ; ccccccccH mov DWORD PTR [ebp-8], -858993460 ; ccccccccH mov DWORD PTR [ebp-4], -858993460 ; ccccccccH mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 74 : __UNIT_TYPE or_count = v_count; mov eax, DWORD PTR _v_count$[ebp] mov DWORD PTR _or_count$[ebp], eax ; 75 : __UNIT_TYPE cp_count = u_count - v_count; mov ecx, DWORD PTR _u_count$[ebp] sub ecx, DWORD PTR _v_count$[ebp] mov DWORD PTR _cp_count$[ebp], ecx ; 76 : ; 77 : __UNIT_TYPE count = or_count >> 5; mov edx, DWORD PTR _or_count$[ebp] shr edx, 5 mov DWORD PTR _count$[ebp], edx $LN2@ExclusiveO: ; 78 : while (count > 0) cmp DWORD PTR _count$[ebp], 0 jbe $LN3@ExclusiveO ; 79 : { ; 80 : w[0] = u[0] ^ v[0]; mov eax, 4 imul ecx, eax, 0 mov edx, 4 imul eax, edx, 0 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 0 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 81 : w[1] = u[1] ^ v[1]; mov eax, 4 shl eax, 0 mov ecx, 4 shl ecx, 0 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [edx+eax] xor eax, DWORD PTR [esi+ecx] mov ecx, 4 shl ecx, 0 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 82 : w[2] = u[2] ^ v[2]; mov eax, 4 shl eax, 1 mov ecx, 4 shl ecx, 1 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [edx+eax] xor eax, DWORD PTR [esi+ecx] mov ecx, 4 shl ecx, 1 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 83 : w[3] = u[3] ^ v[3]; mov eax, 4 imul ecx, eax, 3 mov edx, 4 imul eax, edx, 3 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 3 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 84 : w[4] = u[4] ^ v[4]; mov eax, 4 shl eax, 2 mov ecx, 4 shl ecx, 2 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [edx+eax] xor eax, DWORD PTR [esi+ecx] mov ecx, 4 shl ecx, 2 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 85 : w[5] = u[5] ^ v[5]; mov eax, 4 imul ecx, eax, 5 mov edx, 4 imul eax, edx, 5 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 5 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 86 : w[6] = u[6] ^ v[6]; mov eax, 4 imul ecx, eax, 6 mov edx, 4 imul eax, edx, 6 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 6 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 87 : w[7] = u[7] ^ v[7]; mov eax, 4 imul ecx, eax, 7 mov edx, 4 imul eax, edx, 7 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 7 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 88 : w[8] = u[8] ^ v[8]; mov eax, 4 shl eax, 3 mov ecx, 4 shl ecx, 3 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [edx+eax] xor eax, DWORD PTR [esi+ecx] mov ecx, 4 shl ecx, 3 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 89 : w[9] = u[9] ^ v[9]; mov eax, 4 imul ecx, eax, 9 mov edx, 4 imul eax, edx, 9 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 9 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 90 : w[10] = u[10] ^ v[10]; mov eax, 4 imul ecx, eax, 10 mov edx, 4 imul eax, edx, 10 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 10 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 91 : w[11] = u[11] ^ v[11]; mov eax, 4 imul ecx, eax, 11 mov edx, 4 imul eax, edx, 11 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 11 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 92 : w[12] = u[12] ^ v[12]; mov eax, 4 imul ecx, eax, 12 mov edx, 4 imul eax, edx, 12 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 12 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 93 : w[13] = u[13] ^ v[13]; mov eax, 4 imul ecx, eax, 13 mov edx, 4 imul eax, edx, 13 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 13 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 94 : w[14] = u[14] ^ v[14]; mov eax, 4 imul ecx, eax, 14 mov edx, 4 imul eax, edx, 14 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 14 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 95 : w[15] = u[15] ^ v[15]; mov eax, 4 imul ecx, eax, 15 mov edx, 4 imul eax, edx, 15 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 15 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 96 : w[16] = u[16] ^ v[16]; mov eax, 4 shl eax, 4 mov ecx, 4 shl ecx, 4 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [edx+eax] xor eax, DWORD PTR [esi+ecx] mov ecx, 4 shl ecx, 4 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 97 : w[17] = u[17] ^ v[17]; mov eax, 4 imul ecx, eax, 17 mov edx, 4 imul eax, edx, 17 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 17 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 98 : w[18] = u[18] ^ v[18]; mov eax, 4 imul ecx, eax, 18 mov edx, 4 imul eax, edx, 18 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 18 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 99 : w[19] = u[19] ^ v[19]; mov eax, 4 imul ecx, eax, 19 mov edx, 4 imul eax, edx, 19 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 19 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 100 : w[20] = u[20] ^ v[20]; mov eax, 4 imul ecx, eax, 20 mov edx, 4 imul eax, edx, 20 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 20 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 101 : w[21] = u[21] ^ v[21]; mov eax, 4 imul ecx, eax, 21 mov edx, 4 imul eax, edx, 21 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 21 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 102 : w[22] = u[22] ^ v[22]; mov eax, 4 imul ecx, eax, 22 mov edx, 4 imul eax, edx, 22 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 22 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 103 : w[23] = u[23] ^ v[23]; mov eax, 4 imul ecx, eax, 23 mov edx, 4 imul eax, edx, 23 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 23 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 104 : w[24] = u[24] ^ v[24]; mov eax, 4 imul ecx, eax, 24 mov edx, 4 imul eax, edx, 24 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 24 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 105 : w[25] = u[25] ^ v[25]; mov eax, 4 imul ecx, eax, 25 mov edx, 4 imul eax, edx, 25 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 25 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 106 : w[26] = u[26] ^ v[26]; mov eax, 4 imul ecx, eax, 26 mov edx, 4 imul eax, edx, 26 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 26 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 107 : w[27] = u[27] ^ v[27]; mov eax, 4 imul ecx, eax, 27 mov edx, 4 imul eax, edx, 27 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 27 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 108 : w[28] = u[28] ^ v[28]; mov eax, 4 imul ecx, eax, 28 mov edx, 4 imul eax, edx, 28 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 28 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 109 : w[29] = u[29] ^ v[29]; mov eax, 4 imul ecx, eax, 29 mov edx, 4 imul eax, edx, 29 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 29 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 110 : w[30] = u[30] ^ v[30]; mov eax, 4 imul ecx, eax, 30 mov edx, 4 imul eax, edx, 30 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 30 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 111 : w[31] = u[31] ^ v[31]; mov eax, 4 imul ecx, eax, 31 mov edx, 4 imul eax, edx, 31 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 31 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 112 : u += 32; mov eax, DWORD PTR _u$[ebp] add eax, 128 ; 00000080H mov DWORD PTR _u$[ebp], eax ; 113 : v += 32; mov ecx, DWORD PTR _v$[ebp] add ecx, 128 ; 00000080H mov DWORD PTR _v$[ebp], ecx ; 114 : w += 32; mov edx, DWORD PTR _w$[ebp] add edx, 128 ; 00000080H mov DWORD PTR _w$[ebp], edx ; 115 : --count; mov eax, DWORD PTR _count$[ebp] sub eax, 1 mov DWORD PTR _count$[ebp], eax ; 116 : } jmp $LN2@ExclusiveO $LN3@ExclusiveO: ; 117 : ; 118 : if (or_count & 0x10) mov ecx, DWORD PTR _or_count$[ebp] and ecx, 16 ; 00000010H je $LN4@ExclusiveO ; 119 : { ; 120 : w[0] = u[0] ^ v[0]; mov edx, 4 imul eax, edx, 0 mov ecx, 4 imul edx, ecx, 0 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 0 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 121 : w[1] = u[1] ^ v[1]; mov edx, 4 shl edx, 0 mov eax, 4 shl eax, 0 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov edx, DWORD PTR [ecx+edx] xor edx, DWORD PTR [esi+eax] mov eax, 4 shl eax, 0 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+eax], edx ; 122 : w[2] = u[2] ^ v[2]; mov edx, 4 shl edx, 1 mov eax, 4 shl eax, 1 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov edx, DWORD PTR [ecx+edx] xor edx, DWORD PTR [esi+eax] mov eax, 4 shl eax, 1 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+eax], edx ; 123 : w[3] = u[3] ^ v[3]; mov edx, 4 imul eax, edx, 3 mov ecx, 4 imul edx, ecx, 3 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 3 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 124 : w[4] = u[4] ^ v[4]; mov edx, 4 shl edx, 2 mov eax, 4 shl eax, 2 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov edx, DWORD PTR [ecx+edx] xor edx, DWORD PTR [esi+eax] mov eax, 4 shl eax, 2 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+eax], edx ; 125 : w[5] = u[5] ^ v[5]; mov edx, 4 imul eax, edx, 5 mov ecx, 4 imul edx, ecx, 5 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 5 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 126 : w[6] = u[6] ^ v[6]; mov edx, 4 imul eax, edx, 6 mov ecx, 4 imul edx, ecx, 6 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 6 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 127 : w[7] = u[7] ^ v[7]; mov edx, 4 imul eax, edx, 7 mov ecx, 4 imul edx, ecx, 7 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 7 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 128 : w[8] = u[8] ^ v[8]; mov edx, 4 shl edx, 3 mov eax, 4 shl eax, 3 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov edx, DWORD PTR [ecx+edx] xor edx, DWORD PTR [esi+eax] mov eax, 4 shl eax, 3 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+eax], edx ; 129 : w[9] = u[9] ^ v[9]; mov edx, 4 imul eax, edx, 9 mov ecx, 4 imul edx, ecx, 9 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 9 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 130 : w[10] = u[10] ^ v[10]; mov edx, 4 imul eax, edx, 10 mov ecx, 4 imul edx, ecx, 10 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 10 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 131 : w[11] = u[11] ^ v[11]; mov edx, 4 imul eax, edx, 11 mov ecx, 4 imul edx, ecx, 11 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 11 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 132 : w[12] = u[12] ^ v[12]; mov edx, 4 imul eax, edx, 12 mov ecx, 4 imul edx, ecx, 12 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 12 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 133 : w[13] = u[13] ^ v[13]; mov edx, 4 imul eax, edx, 13 mov ecx, 4 imul edx, ecx, 13 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 13 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 134 : w[14] = u[14] ^ v[14]; mov edx, 4 imul eax, edx, 14 mov ecx, 4 imul edx, ecx, 14 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 14 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 135 : w[15] = u[15] ^ v[15]; mov edx, 4 imul eax, edx, 15 mov ecx, 4 imul edx, ecx, 15 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 15 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 136 : u += 16; mov edx, DWORD PTR _u$[ebp] add edx, 64 ; 00000040H mov DWORD PTR _u$[ebp], edx ; 137 : v += 16; mov eax, DWORD PTR _v$[ebp] add eax, 64 ; 00000040H mov DWORD PTR _v$[ebp], eax ; 138 : w += 16; mov ecx, DWORD PTR _w$[ebp] add ecx, 64 ; 00000040H mov DWORD PTR _w$[ebp], ecx $LN4@ExclusiveO: ; 139 : } ; 140 : ; 141 : if (or_count & 0x8) mov edx, DWORD PTR _or_count$[ebp] and edx, 8 je $LN5@ExclusiveO ; 142 : { ; 143 : w[0] = u[0] ^ v[0]; mov eax, 4 imul ecx, eax, 0 mov edx, 4 imul eax, edx, 0 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 0 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 144 : w[1] = u[1] ^ v[1]; mov eax, 4 shl eax, 0 mov ecx, 4 shl ecx, 0 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [edx+eax] xor eax, DWORD PTR [esi+ecx] mov ecx, 4 shl ecx, 0 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 145 : w[2] = u[2] ^ v[2]; mov eax, 4 shl eax, 1 mov ecx, 4 shl ecx, 1 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [edx+eax] xor eax, DWORD PTR [esi+ecx] mov ecx, 4 shl ecx, 1 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 146 : w[3] = u[3] ^ v[3]; mov eax, 4 imul ecx, eax, 3 mov edx, 4 imul eax, edx, 3 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 3 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 147 : w[4] = u[4] ^ v[4]; mov eax, 4 shl eax, 2 mov ecx, 4 shl ecx, 2 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [edx+eax] xor eax, DWORD PTR [esi+ecx] mov ecx, 4 shl ecx, 2 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 148 : w[5] = u[5] ^ v[5]; mov eax, 4 imul ecx, eax, 5 mov edx, 4 imul eax, edx, 5 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 5 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 149 : w[6] = u[6] ^ v[6]; mov eax, 4 imul ecx, eax, 6 mov edx, 4 imul eax, edx, 6 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 6 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 150 : w[7] = u[7] ^ v[7]; mov eax, 4 imul ecx, eax, 7 mov edx, 4 imul eax, edx, 7 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 7 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 151 : u += 8; mov eax, DWORD PTR _u$[ebp] add eax, 32 ; 00000020H mov DWORD PTR _u$[ebp], eax ; 152 : v += 8; mov ecx, DWORD PTR _v$[ebp] add ecx, 32 ; 00000020H mov DWORD PTR _v$[ebp], ecx ; 153 : w += 8; mov edx, DWORD PTR _w$[ebp] add edx, 32 ; 00000020H mov DWORD PTR _w$[ebp], edx $LN5@ExclusiveO: ; 154 : } ; 155 : ; 156 : if (or_count & 0x4) mov eax, DWORD PTR _or_count$[ebp] and eax, 4 je $LN6@ExclusiveO ; 157 : { ; 158 : w[0] = u[0] ^ v[0]; mov ecx, 4 imul edx, ecx, 0 mov eax, 4 imul ecx, eax, 0 mov eax, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov edx, DWORD PTR [eax+edx] xor edx, DWORD PTR [esi+ecx] mov eax, 4 imul ecx, eax, 0 mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax+ecx], edx ; 159 : w[1] = u[1] ^ v[1]; mov ecx, 4 shl ecx, 0 mov edx, 4 shl edx, 0 mov eax, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [eax+ecx] xor ecx, DWORD PTR [esi+edx] mov edx, 4 shl edx, 0 mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax+edx], ecx ; 160 : w[2] = u[2] ^ v[2]; mov ecx, 4 shl ecx, 1 mov edx, 4 shl edx, 1 mov eax, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [eax+ecx] xor ecx, DWORD PTR [esi+edx] mov edx, 4 shl edx, 1 mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax+edx], ecx ; 161 : w[3] = u[3] ^ v[3]; mov ecx, 4 imul edx, ecx, 3 mov eax, 4 imul ecx, eax, 3 mov eax, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov edx, DWORD PTR [eax+edx] xor edx, DWORD PTR [esi+ecx] mov eax, 4 imul ecx, eax, 3 mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax+ecx], edx ; 162 : u += 4; mov ecx, DWORD PTR _u$[ebp] add ecx, 16 ; 00000010H mov DWORD PTR _u$[ebp], ecx ; 163 : v += 4; mov edx, DWORD PTR _v$[ebp] add edx, 16 ; 00000010H mov DWORD PTR _v$[ebp], edx ; 164 : w += 4; mov eax, DWORD PTR _w$[ebp] add eax, 16 ; 00000010H mov DWORD PTR _w$[ebp], eax $LN6@ExclusiveO: ; 165 : } ; 166 : ; 167 : if (or_count & 0x2) mov ecx, DWORD PTR _or_count$[ebp] and ecx, 2 je SHORT $LN7@ExclusiveO ; 168 : { ; 169 : w[0] = u[0] ^ v[0]; mov edx, 4 imul eax, edx, 0 mov ecx, 4 imul edx, ecx, 0 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov eax, DWORD PTR [ecx+eax] xor eax, DWORD PTR [esi+edx] mov ecx, 4 imul edx, ecx, 0 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 170 : w[1] = u[1] ^ v[1]; mov edx, 4 shl edx, 0 mov eax, 4 shl eax, 0 mov ecx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov edx, DWORD PTR [ecx+edx] xor edx, DWORD PTR [esi+eax] mov eax, 4 shl eax, 0 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+eax], edx ; 171 : u += 2; mov edx, DWORD PTR _u$[ebp] add edx, 8 mov DWORD PTR _u$[ebp], edx ; 172 : v += 2; mov eax, DWORD PTR _v$[ebp] add eax, 8 mov DWORD PTR _v$[ebp], eax ; 173 : w += 2; mov ecx, DWORD PTR _w$[ebp] add ecx, 8 mov DWORD PTR _w$[ebp], ecx $LN7@ExclusiveO: ; 174 : } ; 175 : ; 176 : if (or_count & 0x1) mov edx, DWORD PTR _or_count$[ebp] and edx, 1 je SHORT $LN8@ExclusiveO ; 177 : { ; 178 : w[0] = u[0] ^ v[0]; mov eax, 4 imul ecx, eax, 0 mov edx, 4 imul eax, edx, 0 mov edx, DWORD PTR _u$[ebp] mov esi, DWORD PTR _v$[ebp] mov ecx, DWORD PTR [edx+ecx] xor ecx, DWORD PTR [esi+eax] mov edx, 4 imul eax, edx, 0 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+eax], ecx ; 179 : u += 1; mov eax, DWORD PTR _u$[ebp] add eax, 4 mov DWORD PTR _u$[ebp], eax ; 180 : v += 1; mov ecx, DWORD PTR _v$[ebp] add ecx, 4 mov DWORD PTR _v$[ebp], ecx ; 181 : w += 1; mov edx, DWORD PTR _w$[ebp] add edx, 4 mov DWORD PTR _w$[ebp], edx $LN8@ExclusiveO: ; 182 : } ; 183 : ; 184 : _COPY_MEMORY_UNIT(w, u, cp_count); mov eax, DWORD PTR _cp_count$[ebp] push eax mov ecx, DWORD PTR _u$[ebp] push ecx mov edx, DWORD PTR _w$[ebp] push edx call __COPY_MEMORY_UNIT add esp, 12 ; 0000000cH ; 185 : } pop esi add esp, 12 ; 0000000cH cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 _ExclusiveOr_X_X ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _u$ = 8 ; size = 4 _u_count$ = 12 ; size = 4 _v_hi$ = 16 ; size = 4 _v_lo$ = 20 ; size = 4 _w$ = 24 ; size = 4 _ExclusiveOr_X_2W PROC ; 52 : { push ebp mov ebp, esp mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 53 : if (u_count == 1) cmp DWORD PTR _u_count$[ebp], 1 jne SHORT $LN2@ExclusiveO ; 54 : { ; 55 : w[0] = u[0] ^ v_lo; mov eax, 4 imul ecx, eax, 0 mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+ecx] xor eax, DWORD PTR _v_lo$[ebp] mov ecx, 4 imul edx, ecx, 0 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 56 : w[1] = v_hi; mov edx, 4 shl edx, 0 mov eax, DWORD PTR _w$[ebp] mov ecx, DWORD PTR _v_hi$[ebp] mov DWORD PTR [eax+edx], ecx ; 57 : } jmp $LN1@ExclusiveO $LN2@ExclusiveO: ; 58 : else if (u_count == 2) cmp DWORD PTR _u_count$[ebp], 2 jne SHORT $LN4@ExclusiveO ; 59 : { ; 60 : w[0] = u[0] ^ v_lo; mov edx, 4 imul eax, edx, 0 mov ecx, DWORD PTR _u$[ebp] mov edx, DWORD PTR [ecx+eax] xor edx, DWORD PTR _v_lo$[ebp] mov eax, 4 imul ecx, eax, 0 mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax+ecx], edx ; 61 : w[1] = u[1] ^ v_hi; mov ecx, 4 shl ecx, 0 mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+ecx] xor eax, DWORD PTR _v_hi$[ebp] mov ecx, 4 shl ecx, 0 mov edx, DWORD PTR _w$[ebp] mov DWORD PTR [edx+ecx], eax ; 62 : } jmp SHORT $LN1@ExclusiveO $LN4@ExclusiveO: ; 63 : else ; 64 : { ; 65 : w[0] = u[0] ^ v_lo; mov eax, 4 imul ecx, eax, 0 mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+ecx] xor eax, DWORD PTR _v_lo$[ebp] mov ecx, 4 imul edx, ecx, 0 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax ; 66 : w[1] = u[1] ^ v_hi; mov edx, 4 shl edx, 0 mov eax, DWORD PTR _u$[ebp] mov ecx, DWORD PTR [eax+edx] xor ecx, DWORD PTR _v_hi$[ebp] mov edx, 4 shl edx, 0 mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax+edx], ecx ; 67 : _COPY_MEMORY_UNIT(w + 2, u + 2, u_count - 2); mov ecx, DWORD PTR _u_count$[ebp] sub ecx, 2 push ecx mov edx, DWORD PTR _u$[ebp] add edx, 8 push edx mov eax, DWORD PTR _w$[ebp] add eax, 8 push eax call __COPY_MEMORY_UNIT add esp, 12 ; 0000000cH $LN1@ExclusiveO: ; 68 : } ; 69 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 _ExclusiveOr_X_2W ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _u$ = 8 ; size = 4 _u_count$ = 12 ; size = 4 _v$ = 16 ; size = 4 _w$ = 20 ; size = 4 _ExclusiveOr_X_1W PROC ; 40 : { push ebp mov ebp, esp mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 41 : if (u_count == 1) cmp DWORD PTR _u_count$[ebp], 1 jne SHORT $LN2@ExclusiveO ; 42 : w[0] = u[0] ^ v; mov eax, 4 imul ecx, eax, 0 mov edx, DWORD PTR _u$[ebp] mov eax, DWORD PTR [edx+ecx] xor eax, DWORD PTR _v$[ebp] mov ecx, 4 imul edx, ecx, 0 mov ecx, DWORD PTR _w$[ebp] mov DWORD PTR [ecx+edx], eax jmp SHORT $LN1@ExclusiveO $LN2@ExclusiveO: ; 43 : else ; 44 : { ; 45 : w[0] = u[0] ^ v; mov edx, 4 imul eax, edx, 0 mov ecx, DWORD PTR _u$[ebp] mov edx, DWORD PTR [ecx+eax] xor edx, DWORD PTR _v$[ebp] mov eax, 4 imul ecx, eax, 0 mov eax, DWORD PTR _w$[ebp] mov DWORD PTR [eax+ecx], edx ; 46 : _COPY_MEMORY_UNIT(w + 1, u + 1, u_count - 1); mov ecx, DWORD PTR _u_count$[ebp] sub ecx, 1 push ecx mov edx, DWORD PTR _u$[ebp] add edx, 4 push edx mov eax, DWORD PTR _w$[ebp] add eax, 4 push eax call __COPY_MEMORY_UNIT add esp, 12 ; 0000000cH $LN1@ExclusiveO: ; 47 : } ; 48 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 _ExclusiveOr_X_1W ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_inline_func.h _TEXT SEGMENT _pos$ = -8 ; size = 4 _x$ = 8 ; size = 4 __LZCNT_ALT_UNIT PROC ; 629 : { push ebp mov ebp, esp sub esp, 12 ; 0000000cH mov DWORD PTR [ebp-12], -858993460 ; ccccccccH mov DWORD PTR [ebp-8], -858993460 ; ccccccccH mov DWORD PTR [ebp-4], -858993460 ; ccccccccH mov ecx, OFFSET __6B0481B0_pmc_inline_func@h call @__CheckForDebuggerJustMyCode@4 ; 630 : if (x == 0) cmp DWORD PTR _x$[ebp], 0 jne SHORT $LN2@LZCNT_ALT_ ; 631 : return (sizeof(x) * 8); mov eax, 32 ; 00000020H jmp SHORT $LN1@LZCNT_ALT_ $LN2@LZCNT_ALT_: ; 632 : #ifdef _M_IX86 ; 633 : _UINT32_T pos; ; 634 : #ifdef _MSC_VER ; 635 : _BitScanReverse(&pos, x); bsr eax, DWORD PTR _x$[ebp] mov DWORD PTR _pos$[ebp], eax ; 636 : #elif defined(__GNUC__) ; 637 : __asm__("bsrl %1, %0" : "=r"(pos) : "rm"(x)); ; 638 : #else ; 639 : #error unknown compiler ; 640 : #endif ; 641 : #elif defined(_M_X64) ; 642 : #ifdef _MSC_VER ; 643 : _UINT32_T pos; ; 644 : _BitScanReverse64(&pos, x); ; 645 : #elif defined(__GNUC__) ; 646 : _UINT64_T pos; ; 647 : __asm__("bsrq %1, %0" : "=r"(pos) : "rm"(x)); ; 648 : #else ; 649 : #error unknown compiler ; 650 : #endif ; 651 : #else ; 652 : #error unknown platform ; 653 : #endif ; 654 : return (sizeof(x) * 8 - 1 - pos); mov eax, 31 ; 0000001fH sub eax, DWORD PTR _pos$[ebp] $LN1@LZCNT_ALT_: ; 655 : } push edx mov ecx, ebp push eax lea edx, DWORD PTR $LN6@LZCNT_ALT_ call @_RTC_CheckStackVars@8 pop eax pop edx add esp, 12 ; 0000000cH cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 $LN6@LZCNT_ALT_: DD 1 DD $LN5@LZCNT_ALT_ $LN5@LZCNT_ALT_: DD -8 ; fffffff8H DD 4 DD $LN4@LZCNT_ALT_ $LN4@LZCNT_ALT_: DB 112 ; 00000070H DB 111 ; 0000006fH DB 115 ; 00000073H DB 0 __LZCNT_ALT_UNIT ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_inline_func.h _TEXT SEGMENT _pos$ = -8 ; size = 4 _x$ = 8 ; size = 4 __LZCNT_ALT_32 PROC ; 596 : { push ebp mov ebp, esp sub esp, 12 ; 0000000cH mov DWORD PTR [ebp-12], -858993460 ; ccccccccH mov DWORD PTR [ebp-8], -858993460 ; ccccccccH mov DWORD PTR [ebp-4], -858993460 ; ccccccccH mov ecx, OFFSET __6B0481B0_pmc_inline_func@h call @__CheckForDebuggerJustMyCode@4 ; 597 : if (x == 0) cmp DWORD PTR _x$[ebp], 0 jne SHORT $LN2@LZCNT_ALT_ ; 598 : return (sizeof(x) * 8); mov eax, 32 ; 00000020H jmp SHORT $LN1@LZCNT_ALT_ $LN2@LZCNT_ALT_: ; 599 : _UINT32_T pos; ; 600 : #ifdef _MSC_VER ; 601 : _BitScanReverse(&pos, x); bsr eax, DWORD PTR _x$[ebp] mov DWORD PTR _pos$[ebp], eax ; 602 : #elif defined(__GNUC__) ; 603 : __asm__("bsrl %1, %0" : "=r"(pos) : "rm"(x)); ; 604 : #else ; 605 : #error unknown compiler ; 606 : #endif ; 607 : return (sizeof(x) * 8 - 1 - pos); mov eax, 31 ; 0000001fH sub eax, DWORD PTR _pos$[ebp] $LN1@LZCNT_ALT_: ; 608 : } push edx mov ecx, ebp push eax lea edx, DWORD PTR $LN6@LZCNT_ALT_ call @_RTC_CheckStackVars@8 pop eax pop edx add esp, 12 ; 0000000cH cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 $LN6@LZCNT_ALT_: DD 1 DD $LN5@LZCNT_ALT_ $LN5@LZCNT_ALT_: DD -8 ; fffffff8H DD 4 DD $LN4@LZCNT_ALT_ $LN4@LZCNT_ALT_: DB 112 ; 00000070H DB 111 ; 0000006fH DB 115 ; 00000073H DB 0 __LZCNT_ALT_32 ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_inline_func.h _TEXT SEGMENT tv65 = -4 ; size = 4 _x$ = 8 ; size = 4 _y$ = 12 ; size = 4 __MAXIMUM_UNIT PROC ; 203 : { push ebp mov ebp, esp push ecx mov DWORD PTR [ebp-4], -858993460 ; ccccccccH mov ecx, OFFSET __6B0481B0_pmc_inline_func@h call @__CheckForDebuggerJustMyCode@4 ; 204 : return (x >= y ? x : y); mov eax, DWORD PTR _x$[ebp] cmp eax, DWORD PTR _y$[ebp] jb SHORT $LN3@MAXIMUM_UN mov ecx, DWORD PTR _x$[ebp] mov DWORD PTR tv65[ebp], ecx jmp SHORT $LN4@MAXIMUM_UN $LN3@MAXIMUM_UN: mov edx, DWORD PTR _y$[ebp] mov DWORD PTR tv65[ebp], edx $LN4@MAXIMUM_UN: mov eax, DWORD PTR tv65[ebp] ; 205 : } add esp, 4 cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 __MAXIMUM_UNIT ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_inline_func.h _TEXT SEGMENT _value$ = 8 ; size = 8 _result_high$ = 16 ; size = 4 __FROMDWORDTOWORD PROC ; 182 : { push ebp mov ebp, esp mov ecx, OFFSET __6B0481B0_pmc_inline_func@h call @__CheckForDebuggerJustMyCode@4 ; 183 : *result_high = (_UINT32_T)(value >> 32); mov eax, DWORD PTR _value$[ebp] mov edx, DWORD PTR _value$[ebp+4] mov cl, 32 ; 00000020H call __aullshr mov ecx, DWORD PTR _result_high$[ebp] mov DWORD PTR [ecx], eax ; 184 : return ((_UINT32_T)value); mov eax, DWORD PTR _value$[ebp] ; 185 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 __FROMDWORDTOWORD ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_inline_func.h _TEXT SEGMENT _d$ = 8 ; size = 4 _s$ = 12 ; size = 4 _count$ = 16 ; size = 4 __COPY_MEMORY_UNIT PROC ; 66 : { push ebp mov ebp, esp push esi push edi mov ecx, OFFSET __6B0481B0_pmc_inline_func@h call @__CheckForDebuggerJustMyCode@4 ; 67 : #ifdef _M_IX86 ; 68 : __movsd((unsigned long *)d, (unsigned long *)s, (unsigned long)count); mov edi, DWORD PTR _d$[ebp] mov esi, DWORD PTR _s$[ebp] mov ecx, DWORD PTR _count$[ebp] rep movsd ; 69 : #elif defined(_M_X64) ; 70 : __movsq(d, s, count); ; 71 : #else ; 72 : #error unknown platform ; 73 : #endif ; 74 : } pop edi pop esi cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 __COPY_MEMORY_UNIT ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _nw_light_check_code$1 = -48 ; size = 4 _w_bit_count$2 = -40 ; size = 4 _v_bit_count$3 = -36 ; size = 4 _u_bit_count$4 = -32 ; size = 4 _t$5 = -28 ; size = 4 _nw$ = -20 ; size = 4 _result$ = -12 ; size = 4 _nv$ = -8 ; size = 4 _nu$ = -4 ; size = 4 _u$ = 8 ; size = 4 _v$ = 12 ; size = 4 _w$ = 16 ; size = 4 _PMC_ExclusiveOr_X_X@12 PROC ; 412 : { push ebp mov ebp, esp sub esp, 52 ; 00000034H push edi lea edi, DWORD PTR [ebp-52] mov ecx, 13 ; 0000000dH mov eax, -858993460 ; ccccccccH rep stosd mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 413 : if (u == NULL) cmp DWORD PTR _u$[ebp], 0 jne SHORT $LN2@PMC_Exclus ; 414 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp $LN1@PMC_Exclus $LN2@PMC_Exclus: ; 415 : if (v == NULL) cmp DWORD PTR _v$[ebp], 0 jne SHORT $LN3@PMC_Exclus ; 416 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp $LN1@PMC_Exclus $LN3@PMC_Exclus: ; 417 : if (w == NULL) cmp DWORD PTR _w$[ebp], 0 jne SHORT $LN4@PMC_Exclus ; 418 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp $LN1@PMC_Exclus $LN4@PMC_Exclus: ; 419 : NUMBER_HEADER* nu = (NUMBER_HEADER*)u; mov eax, DWORD PTR _u$[ebp] mov DWORD PTR _nu$[ebp], eax ; 420 : NUMBER_HEADER* nv = (NUMBER_HEADER*)v; mov ecx, DWORD PTR _v$[ebp] mov DWORD PTR _nv$[ebp], ecx ; 421 : PMC_STATUS_CODE result; ; 422 : if ((result = CheckNumber(nu)) != PMC_STATUS_OK) mov edx, DWORD PTR _nu$[ebp] push edx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN5@PMC_Exclus ; 423 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN5@PMC_Exclus: ; 424 : if ((result = CheckNumber(nv)) != PMC_STATUS_OK) mov eax, DWORD PTR _nv$[ebp] push eax call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN6@PMC_Exclus ; 425 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN6@PMC_Exclus: ; 426 : NUMBER_HEADER* nw; ; 427 : if (nu->IS_ZERO) mov ecx, DWORD PTR _nu$[ebp] mov edx, DWORD PTR [ecx+24] shr edx, 1 and edx, 1 je SHORT $LN7@PMC_Exclus ; 428 : { ; 429 : if ((result = DuplicateNumber(nv, &nw)) != PMC_STATUS_OK) lea eax, DWORD PTR _nw$[ebp] push eax mov ecx, DWORD PTR _nv$[ebp] push ecx call _DuplicateNumber add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN9@PMC_Exclus ; 430 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN9@PMC_Exclus: ; 431 : } jmp $LN8@PMC_Exclus $LN7@PMC_Exclus: ; 432 : else if (nv->IS_ZERO) mov edx, DWORD PTR _nv$[ebp] mov eax, DWORD PTR [edx+24] shr eax, 1 and eax, 1 je SHORT $LN10@PMC_Exclus ; 433 : { ; 434 : if ((result = DuplicateNumber(nu, &nw)) != PMC_STATUS_OK) lea ecx, DWORD PTR _nw$[ebp] push ecx mov edx, DWORD PTR _nu$[ebp] push edx call _DuplicateNumber add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN12@PMC_Exclus ; 435 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN12@PMC_Exclus: ; 436 : } jmp $LN8@PMC_Exclus $LN10@PMC_Exclus: ; 437 : else ; 438 : { ; 439 : if (nu->UNIT_WORD_COUNT < nv->UNIT_WORD_COUNT) mov eax, DWORD PTR _nu$[ebp] mov ecx, DWORD PTR _nv$[ebp] mov edx, DWORD PTR [eax+8] cmp edx, DWORD PTR [ecx+8] jae SHORT $LN13@PMC_Exclus ; 440 : { ; 441 : NUMBER_HEADER* t = nu; mov eax, DWORD PTR _nu$[ebp] mov DWORD PTR _t$5[ebp], eax ; 442 : nu = nv; mov ecx, DWORD PTR _nv$[ebp] mov DWORD PTR _nu$[ebp], ecx ; 443 : nv = t; mov edx, DWORD PTR _t$5[ebp] mov DWORD PTR _nv$[ebp], edx $LN13@PMC_Exclus: ; 444 : } ; 445 : __UNIT_TYPE u_bit_count = nu->UNIT_BIT_COUNT; mov eax, DWORD PTR _nu$[ebp] mov ecx, DWORD PTR [eax+12] mov DWORD PTR _u_bit_count$4[ebp], ecx ; 446 : __UNIT_TYPE v_bit_count = nv->UNIT_BIT_COUNT; mov edx, DWORD PTR _nv$[ebp] mov eax, DWORD PTR [edx+12] mov DWORD PTR _v_bit_count$3[ebp], eax ; 447 : __UNIT_TYPE w_bit_count = _MAXIMUM_UNIT(u_bit_count, v_bit_count); mov ecx, DWORD PTR _v_bit_count$3[ebp] push ecx mov edx, DWORD PTR _u_bit_count$4[ebp] push edx call __MAXIMUM_UNIT add esp, 8 mov DWORD PTR _w_bit_count$2[ebp], eax ; 448 : __UNIT_TYPE nw_light_check_code; ; 449 : if ((result = AllocateNumber(&nw, w_bit_count, &nw_light_check_code)) != PMC_STATUS_OK) lea eax, DWORD PTR _nw_light_check_code$1[ebp] push eax mov ecx, DWORD PTR _w_bit_count$2[ebp] push ecx lea edx, DWORD PTR _nw$[ebp] push edx call _AllocateNumber add esp, 12 ; 0000000cH mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN14@PMC_Exclus ; 450 : return (result); mov eax, DWORD PTR _result$[ebp] jmp $LN1@PMC_Exclus $LN14@PMC_Exclus: ; 451 : ExclusiveOr_X_X(nu->BLOCK, nu->UNIT_WORD_COUNT, nv->BLOCK, nv->UNIT_WORD_COUNT, nw->BLOCK); mov eax, DWORD PTR _nw$[ebp] mov ecx, DWORD PTR [eax+32] push ecx mov edx, DWORD PTR _nv$[ebp] mov eax, DWORD PTR [edx+8] push eax mov ecx, DWORD PTR _nv$[ebp] mov edx, DWORD PTR [ecx+32] push edx mov eax, DWORD PTR _nu$[ebp] mov ecx, DWORD PTR [eax+8] push ecx mov edx, DWORD PTR _nu$[ebp] mov eax, DWORD PTR [edx+32] push eax call _ExclusiveOr_X_X add esp, 20 ; 00000014H ; 452 : if ((result = CheckBlockLight(nw->BLOCK, nw_light_check_code)) != PMC_STATUS_OK) mov ecx, DWORD PTR _nw_light_check_code$1[ebp] push ecx mov edx, DWORD PTR _nw$[ebp] mov eax, DWORD PTR [edx+32] push eax call _CheckBlockLight add esp, 8 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN15@PMC_Exclus ; 453 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN15@PMC_Exclus: ; 454 : CommitNumber(nw); mov ecx, DWORD PTR _nw$[ebp] push ecx call _CommitNumber add esp, 4 ; 455 : if (nw->IS_ZERO) mov edx, DWORD PTR _nw$[ebp] mov eax, DWORD PTR [edx+24] shr eax, 1 and eax, 1 je SHORT $LN8@PMC_Exclus ; 456 : { ; 457 : DeallocateNumber(nw); mov ecx, DWORD PTR _nw$[ebp] push ecx call _DeallocateNumber add esp, 4 ; 458 : nw = &number_zero; mov DWORD PTR _nw$[ebp], OFFSET _number_zero $LN8@PMC_Exclus: ; 459 : } ; 460 : } ; 461 : *w = nw; mov edx, DWORD PTR _w$[ebp] mov eax, DWORD PTR _nw$[ebp] mov DWORD PTR [edx], eax ; 462 : #ifdef _DEBUG ; 463 : if ((result = CheckNumber(*w)) != PMC_STATUS_OK) mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] push edx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN17@PMC_Exclus ; 464 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN17@PMC_Exclus: ; 465 : #endif ; 466 : return (PMC_STATUS_OK); xor eax, eax $LN1@PMC_Exclus: ; 467 : } push edx mov ecx, ebp push eax lea edx, DWORD PTR $LN22@PMC_Exclus call @_RTC_CheckStackVars@8 pop eax pop edx pop edi add esp, 52 ; 00000034H cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 12 ; 0000000cH $LN22@PMC_Exclus: DD 2 DD $LN21@PMC_Exclus $LN21@PMC_Exclus: DD -20 ; ffffffecH DD 4 DD $LN19@PMC_Exclus DD -48 ; ffffffd0H DD 4 DD $LN20@PMC_Exclus $LN20@PMC_Exclus: DB 110 ; 0000006eH DB 119 ; 00000077H DB 95 ; 0000005fH DB 108 ; 0000006cH DB 105 ; 00000069H DB 103 ; 00000067H DB 104 ; 00000068H DB 116 ; 00000074H DB 95 ; 0000005fH DB 99 ; 00000063H DB 104 ; 00000068H DB 101 ; 00000065H DB 99 ; 00000063H DB 107 ; 0000006bH DB 95 ; 0000005fH DB 99 ; 00000063H DB 111 ; 0000006fH DB 100 ; 00000064H DB 101 ; 00000065H DB 0 $LN19@PMC_Exclus: DB 110 ; 0000006eH DB 119 ; 00000077H DB 0 _PMC_ExclusiveOr_X_X@12 ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _result$ = -8 ; size = 4 _nu$ = -4 ; size = 4 _u$ = 8 ; size = 4 _v$ = 12 ; size = 8 _w$ = 20 ; size = 4 _PMC_ExclusiveOr_X_L@16 PROC ; 388 : { push ebp mov ebp, esp sub esp, 8 mov DWORD PTR [ebp-8], -858993460 ; ccccccccH mov DWORD PTR [ebp-4], -858993460 ; ccccccccH mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 389 : if (__UNIT_TYPE_BIT_COUNT * 2 < sizeof(v) * 8) xor eax, eax je SHORT $LN2@PMC_Exclus ; 390 : { ; 391 : // _UINT64_T が 2 ワードで表現しきれない処理系には対応しない ; 392 : return (PMC_STATUS_INTERNAL_ERROR); mov eax, -256 ; ffffff00H jmp SHORT $LN1@PMC_Exclus $LN2@PMC_Exclus: ; 393 : } ; 394 : if (u == NULL) cmp DWORD PTR _u$[ebp], 0 jne SHORT $LN3@PMC_Exclus ; 395 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp SHORT $LN1@PMC_Exclus $LN3@PMC_Exclus: ; 396 : if (w == NULL) cmp DWORD PTR _w$[ebp], 0 jne SHORT $LN4@PMC_Exclus ; 397 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp SHORT $LN1@PMC_Exclus $LN4@PMC_Exclus: ; 398 : NUMBER_HEADER* nu = (NUMBER_HEADER*)u; mov ecx, DWORD PTR _u$[ebp] mov DWORD PTR _nu$[ebp], ecx ; 399 : PMC_STATUS_CODE result; ; 400 : if ((result = CheckNumber(nu)) != PMC_STATUS_OK) mov edx, DWORD PTR _nu$[ebp] push edx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN5@PMC_Exclus ; 401 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN5@PMC_Exclus: ; 402 : if ((result = PMC_ExclusiveOr_X_L_Imp((NUMBER_HEADER*)u, v, (NUMBER_HEADER**)w)) != PMC_STATUS_OK) mov eax, DWORD PTR _w$[ebp] push eax mov ecx, DWORD PTR _v$[ebp+4] push ecx mov edx, DWORD PTR _v$[ebp] push edx mov eax, DWORD PTR _u$[ebp] push eax call _PMC_ExclusiveOr_X_L_Imp add esp, 16 ; 00000010H mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN6@PMC_Exclus ; 403 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN6@PMC_Exclus: ; 404 : #ifdef _DEBUG ; 405 : if ((result = CheckNumber(*w)) != PMC_STATUS_OK) mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] push edx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN7@PMC_Exclus ; 406 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN7@PMC_Exclus: ; 407 : #endif ; 408 : return (PMC_STATUS_OK); xor eax, eax $LN1@PMC_Exclus: ; 409 : } add esp, 8 cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 16 ; 00000010H _PMC_ExclusiveOr_X_L@16 ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _result$ = -8 ; size = 4 _nu$ = -4 ; size = 4 _u$ = 8 ; size = 4 _v$ = 12 ; size = 4 _w$ = 16 ; size = 4 _PMC_ExclusiveOr_X_I@12 PROC ; 258 : { push ebp mov ebp, esp sub esp, 8 mov DWORD PTR [ebp-8], -858993460 ; ccccccccH mov DWORD PTR [ebp-4], -858993460 ; ccccccccH mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 259 : if (__UNIT_TYPE_BIT_COUNT < sizeof(v) * 8) xor eax, eax je SHORT $LN2@PMC_Exclus ; 260 : { ; 261 : // _UINT32_T が 1 ワードで表現しきれない処理系には対応しない ; 262 : return (PMC_STATUS_INTERNAL_ERROR); mov eax, -256 ; ffffff00H jmp SHORT $LN1@PMC_Exclus $LN2@PMC_Exclus: ; 263 : } ; 264 : if (u == NULL) cmp DWORD PTR _u$[ebp], 0 jne SHORT $LN3@PMC_Exclus ; 265 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp SHORT $LN1@PMC_Exclus $LN3@PMC_Exclus: ; 266 : if (w == NULL) cmp DWORD PTR _w$[ebp], 0 jne SHORT $LN4@PMC_Exclus ; 267 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp SHORT $LN1@PMC_Exclus $LN4@PMC_Exclus: ; 268 : NUMBER_HEADER* nu = (NUMBER_HEADER*)u; mov ecx, DWORD PTR _u$[ebp] mov DWORD PTR _nu$[ebp], ecx ; 269 : PMC_STATUS_CODE result; ; 270 : if ((result = CheckNumber(nu)) != PMC_STATUS_OK) mov edx, DWORD PTR _nu$[ebp] push edx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN5@PMC_Exclus ; 271 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN5@PMC_Exclus: ; 272 : if ((result = PMC_ExclusiveOr_X_I_Imp((NUMBER_HEADER*)u, v, (NUMBER_HEADER**)w)) != PMC_STATUS_OK) mov eax, DWORD PTR _w$[ebp] push eax mov ecx, DWORD PTR _v$[ebp] push ecx mov edx, DWORD PTR _u$[ebp] push edx call _PMC_ExclusiveOr_X_I_Imp add esp, 12 ; 0000000cH mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN6@PMC_Exclus ; 273 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN6@PMC_Exclus: ; 274 : #ifdef _DEBUG ; 275 : if ((result = CheckNumber(*w)) != PMC_STATUS_OK) mov eax, DWORD PTR _w$[ebp] mov ecx, DWORD PTR [eax] push ecx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN7@PMC_Exclus ; 276 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN7@PMC_Exclus: ; 277 : #endif ; 278 : return (PMC_STATUS_OK); xor eax, eax $LN1@PMC_Exclus: ; 279 : } add esp, 8 cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 12 ; 0000000cH _PMC_ExclusiveOr_X_I@12 ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _result$ = -8 ; size = 4 _nu$ = -4 ; size = 4 _u$ = 8 ; size = 8 _v$ = 16 ; size = 4 _w$ = 20 ; size = 4 _PMC_ExclusiveOr_L_X@16 PROC ; 364 : { push ebp mov ebp, esp sub esp, 8 mov DWORD PTR [ebp-8], -858993460 ; ccccccccH mov DWORD PTR [ebp-4], -858993460 ; ccccccccH mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 365 : if (__UNIT_TYPE_BIT_COUNT * 2 < sizeof(u) * 8) xor eax, eax je SHORT $LN2@PMC_Exclus ; 366 : { ; 367 : // _UINT64_T が 2 ワードで表現しきれない処理系には対応しない ; 368 : return (PMC_STATUS_INTERNAL_ERROR); mov eax, -256 ; ffffff00H jmp SHORT $LN1@PMC_Exclus $LN2@PMC_Exclus: ; 369 : } ; 370 : if (v == NULL) cmp DWORD PTR _v$[ebp], 0 jne SHORT $LN3@PMC_Exclus ; 371 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp SHORT $LN1@PMC_Exclus $LN3@PMC_Exclus: ; 372 : if (w == NULL) cmp DWORD PTR _w$[ebp], 0 jne SHORT $LN4@PMC_Exclus ; 373 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp SHORT $LN1@PMC_Exclus $LN4@PMC_Exclus: ; 374 : NUMBER_HEADER* nu = (NUMBER_HEADER*)v; mov ecx, DWORD PTR _v$[ebp] mov DWORD PTR _nu$[ebp], ecx ; 375 : PMC_STATUS_CODE result; ; 376 : if ((result = CheckNumber(nu)) != PMC_STATUS_OK) mov edx, DWORD PTR _nu$[ebp] push edx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN5@PMC_Exclus ; 377 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN5@PMC_Exclus: ; 378 : if ((result = PMC_ExclusiveOr_X_L_Imp((NUMBER_HEADER*)v, u, (NUMBER_HEADER**)w)) != PMC_STATUS_OK) mov eax, DWORD PTR _w$[ebp] push eax mov ecx, DWORD PTR _u$[ebp+4] push ecx mov edx, DWORD PTR _u$[ebp] push edx mov eax, DWORD PTR _v$[ebp] push eax call _PMC_ExclusiveOr_X_L_Imp add esp, 16 ; 00000010H mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN6@PMC_Exclus ; 379 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN6@PMC_Exclus: ; 380 : #ifdef _DEBUG ; 381 : if ((result = CheckNumber(*w)) != PMC_STATUS_OK) mov ecx, DWORD PTR _w$[ebp] mov edx, DWORD PTR [ecx] push edx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN7@PMC_Exclus ; 382 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN7@PMC_Exclus: ; 383 : #endif ; 384 : return (PMC_STATUS_OK); xor eax, eax $LN1@PMC_Exclus: ; 385 : } add esp, 8 cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 16 ; 00000010H _PMC_ExclusiveOr_L_X@16 ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _result$ = -8 ; size = 4 _nu$ = -4 ; size = 4 _u$ = 8 ; size = 4 _v$ = 12 ; size = 4 _w$ = 16 ; size = 4 _PMC_ExclusiveOr_I_X@12 PROC ; 234 : { push ebp mov ebp, esp sub esp, 8 mov DWORD PTR [ebp-8], -858993460 ; ccccccccH mov DWORD PTR [ebp-4], -858993460 ; ccccccccH mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 235 : if (__UNIT_TYPE_BIT_COUNT < sizeof(u) * 8) xor eax, eax je SHORT $LN2@PMC_Exclus ; 236 : { ; 237 : // _UINT32_T が 1 ワードで表現しきれない処理系には対応しない ; 238 : return (PMC_STATUS_INTERNAL_ERROR); mov eax, -256 ; ffffff00H jmp SHORT $LN1@PMC_Exclus $LN2@PMC_Exclus: ; 239 : } ; 240 : if (v == NULL) cmp DWORD PTR _v$[ebp], 0 jne SHORT $LN3@PMC_Exclus ; 241 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp SHORT $LN1@PMC_Exclus $LN3@PMC_Exclus: ; 242 : if (w == NULL) cmp DWORD PTR _w$[ebp], 0 jne SHORT $LN4@PMC_Exclus ; 243 : return (PMC_STATUS_ARGUMENT_ERROR); or eax, -1 jmp SHORT $LN1@PMC_Exclus $LN4@PMC_Exclus: ; 244 : NUMBER_HEADER* nu = (NUMBER_HEADER*)v; mov ecx, DWORD PTR _v$[ebp] mov DWORD PTR _nu$[ebp], ecx ; 245 : PMC_STATUS_CODE result; ; 246 : if ((result = CheckNumber(nu)) != PMC_STATUS_OK) mov edx, DWORD PTR _nu$[ebp] push edx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN5@PMC_Exclus ; 247 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN5@PMC_Exclus: ; 248 : if ((result = PMC_ExclusiveOr_X_I_Imp((NUMBER_HEADER*)v, u, (NUMBER_HEADER**)w)) != PMC_STATUS_OK) mov eax, DWORD PTR _w$[ebp] push eax mov ecx, DWORD PTR _u$[ebp] push ecx mov edx, DWORD PTR _v$[ebp] push edx call _PMC_ExclusiveOr_X_I_Imp add esp, 12 ; 0000000cH mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN6@PMC_Exclus ; 249 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN6@PMC_Exclus: ; 250 : #ifdef _DEBUG ; 251 : if ((result = CheckNumber(*w)) != PMC_STATUS_OK) mov eax, DWORD PTR _w$[ebp] mov ecx, DWORD PTR [eax] push ecx call _CheckNumber add esp, 4 mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 je SHORT $LN7@PMC_Exclus ; 252 : return (result); mov eax, DWORD PTR _result$[ebp] jmp SHORT $LN1@PMC_Exclus $LN7@PMC_Exclus: ; 253 : #endif ; 254 : return (PMC_STATUS_OK); xor eax, eax $LN1@PMC_Exclus: ; 255 : } add esp, 8 cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 12 ; 0000000cH _PMC_ExclusiveOr_I_X@12 ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.implements\palmtree.math.core.implements\pmc_exclusiveor.c _TEXT SEGMENT _feature$ = 8 ; size = 4 _Initialize_ExclusiveOr PROC ; 470 : { push ebp mov ebp, esp mov ecx, OFFSET __6904D90E_pmc_exclusiveor@c call @__CheckForDebuggerJustMyCode@4 ; 471 : return (PMC_STATUS_OK); xor eax, eax ; 472 : } cmp ebp, esp call __RTC_CheckEsp pop ebp ret 0 _Initialize_ExclusiveOr ENDP _TEXT ENDS END
// Copyright 2020 Tier IV, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef OBSTACLE_COLLISION_CHECKER__OBSTACLE_COLLISION_CHECKER_NODE_HPP_ #define OBSTACLE_COLLISION_CHECKER__OBSTACLE_COLLISION_CHECKER_NODE_HPP_ #include "obstacle_collision_checker/obstacle_collision_checker.hpp" #include <autoware_utils/geometry/geometry.hpp> #include <autoware_utils/ros/debug_publisher.hpp> #include <autoware_utils/ros/processing_time_publisher.hpp> #include <autoware_utils/ros/self_pose_listener.hpp> #include <autoware_utils/ros/transform_listener.hpp> #include <diagnostic_updater/diagnostic_updater.hpp> #include <rclcpp/rclcpp.hpp> #include <autoware_planning_msgs/msg/route.hpp> #include <autoware_planning_msgs/msg/trajectory.hpp> #include <geometry_msgs/msg/pose_stamped.hpp> #include <sensor_msgs/msg/point_cloud2.hpp> #include <visualization_msgs/msg/marker_array.hpp> #include <memory> #include <vector> namespace obstacle_collision_checker { struct NodeParam { double update_rate; }; class ObstacleCollisionCheckerNode : public rclcpp::Node { public: explicit ObstacleCollisionCheckerNode(const rclcpp::NodeOptions & node_options); private: // Subscriber std::shared_ptr<autoware_utils::SelfPoseListener> self_pose_listener_; std::shared_ptr<autoware_utils::TransformListener> transform_listener_; rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr sub_obstacle_pointcloud_; rclcpp::Subscription<autoware_planning_msgs::msg::Trajectory>::SharedPtr sub_reference_trajectory_; rclcpp::Subscription<autoware_planning_msgs::msg::Trajectory>::SharedPtr sub_predicted_trajectory_; rclcpp::Subscription<geometry_msgs::msg::TwistStamped>::SharedPtr sub_twist_; // Data Buffer geometry_msgs::msg::PoseStamped::ConstSharedPtr current_pose_; geometry_msgs::msg::TwistStamped::ConstSharedPtr current_twist_; sensor_msgs::msg::PointCloud2::ConstSharedPtr obstacle_pointcloud_; geometry_msgs::msg::TransformStamped::ConstSharedPtr obstacle_transform_; autoware_planning_msgs::msg::Trajectory::ConstSharedPtr reference_trajectory_; autoware_planning_msgs::msg::Trajectory::ConstSharedPtr predicted_trajectory_; // Callback void onObstaclePointcloud(const sensor_msgs::msg::PointCloud2::SharedPtr msg); void onReferenceTrajectory(const autoware_planning_msgs::msg::Trajectory::SharedPtr msg); void onPredictedTrajectory(const autoware_planning_msgs::msg::Trajectory::SharedPtr msg); void onTwist(const geometry_msgs::msg::TwistStamped::SharedPtr msg); // Publisher std::shared_ptr<autoware_utils::DebugPublisher> debug_publisher_; std::shared_ptr<autoware_utils::ProcessingTimePublisher> time_publisher_; // Timer rclcpp::TimerBase::SharedPtr timer_; void initTimer(double period_s); bool isDataReady(); bool isDataTimeout(); void onTimer(); // Parameter NodeParam node_param_; Param param_; // Dynamic Reconfigure OnSetParametersCallbackHandle::SharedPtr set_param_res_; rcl_interfaces::msg::SetParametersResult paramCallback( const std::vector<rclcpp::Parameter> & parameters); // Core Input input_; Output output_; std::unique_ptr<ObstacleCollisionChecker> obstacle_collision_checker_; // Diagnostic Updater diagnostic_updater::Updater updater_; void checkLaneDeparture(diagnostic_updater::DiagnosticStatusWrapper & stat); // Visualization visualization_msgs::msg::MarkerArray createMarkerArray() const; }; } // namespace obstacle_collision_checker #endif // OBSTACLE_COLLISION_CHECKER__OBSTACLE_COLLISION_CHECKER_NODE_HPP_
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r15 push %r8 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x1623, %rsi lea addresses_UC_ht+0xd7b1, %rdi clflush (%rdi) nop nop nop xor %r10, %r10 mov $85, %rcx rep movsl nop sub $31939, %r10 lea addresses_UC_ht+0x1c423, %rdi cmp %r10, %r10 movw $0x6162, (%rdi) nop nop dec %r10 lea addresses_WC_ht+0xfc23, %rdx nop cmp %r8, %r8 vmovups (%rdx), %ymm4 vextracti128 $1, %ymm4, %xmm4 vpextrq $0, %xmm4, %r10 and %rdx, %rdx lea addresses_normal_ht+0x795b, %rsi lea addresses_normal_ht+0x1a9e3, %rdi nop nop nop sub $51237, %rbp mov $40, %rcx rep movsq nop nop nop nop sub $51563, %r10 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r8 pop %r15 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %r9 push %rax push %rsi // Store lea addresses_A+0x18b23, %rax add $63688, %r13 mov $0x5152535455565758, %r12 movq %r12, %xmm4 vmovups %ymm4, (%rax) nop nop add %r11, %r11 // Store lea addresses_PSE+0xa4a3, %r10 nop nop nop nop nop add $23768, %rsi mov $0x5152535455565758, %r9 movq %r9, (%r10) nop nop nop nop sub $468, %rsi // Faulty Load lea addresses_US+0xde23, %rsi nop dec %rax mov (%rsi), %r9d lea oracles, %r11 and $0xff, %r9 shlq $12, %r9 mov (%r11,%r9,1), %r9 pop %rsi pop %rax pop %r9 pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 8, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 4, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}} {'00': 5} 00 00 00 00 00 */
;M328 ADC Recorder .nolist .include "m328pdef.inc" .list .def TEMP = R16 .def ADCin = R24 .def ButtonInput = R18 .def DBcount = R17 .equ SamplePer = 48 .equ ADCwriteAdd = SRAM_START + $10 .equ ADCreadAdd = SRAM_START + $12 .equ ADCtable = SRAM_START + $20 .equ ADCtableEnd = $07FF .equ PWmin = 800 .ORG $0000 rjmp RESET .ORG INT0addr rjmp Record .ORG INT1addr rjmp Play .ORG OC0Aaddr reti .ORG OVF0addr rjmp PlayNextValue .ORG ADCCaddr rjmp ADCcomplete .ORG INT_VECTORS_SIZE RESET: ldi TEMP, high(RAMEND) out SPH, TEMP ldi TEMP, low(RAMEND) out SPL, TEMP ldi YH, high(ADCwriteAdd) ldi YL, low(ADCwriteAdd) ldi TEMP, low(ADCtable) st Y+, TEMP ldi TEMP, high(ADCtable) st Y, TEMP sbi DDRB, PB0 ;Record Indicator sbi PORTD, PD2 ;INT0 Record Start/Stop sbi PORTD, PD3 ;INT1 Play Start/Stop ldi TEMP, (1<<ISC11)|(1<<ISC01) sts EICRA, TEMP sbi EIMSK, INT0 sbi EIMSK, INT1 ldi TEMP, (1<<REFS1)|(1<<ADLAR) sts ADMUX, TEMP ldi TEMP, (1<<ADTS1)|(1<<ADTS0) sts ADCSRB, TEMP ; ldi TEMP, (1<<ADEN)|(1<<ADATE)|(1<<ADIE)|(1<<ADPS1)|(1<<ADPS0) ; sts ADCSRA, TEMP ldi TEMP, SamplePer out OCR0A, TEMP ldi TEMP, (1<<WGM02)|(1<<WGM01)|(1<<WGM00) out TCCR0A, TEMP ldi TEMP, (1<<OCIE0A)|(0<<TOIE0) sts TIMSK0, TEMP ; ldi TEMP, (1<<WGM02)|(1<<CS02)|(0<<CS01)|(1<<CS00) ; out TCCR0B, TEMP sei MAIN: nop nop nop nop rjmp MAIN ;------------------------------------------------------------------------------ ADCcomplete: ;ADC Start triggered by TO Overflow OCR0A = TOP lds ADCin, ADCH ldi YH, high(ADCwriteAdd) ldi YL, low(ADCwriteAdd) ld XL, Y+ ld XH, Y ldi TEMP, low(ADCtableEnd) cp XL, TEMP ldi TEMP, high(ADCtableEnd) cpc XH, TEMP breq RecordFull andi XH, $07 st X+, ADCin st Y, XH st -Y, XL nop reti RecordFull: clr TEMP out TCCR0B, TEMP ;Stop T0 ldi TEMP, (0<<ADEN)|(0<<ADATE)|(0<<ADIE)|(1<<ADPS1)|(1<<ADPS0) sts ADCSRA, TEMP ;Stop ADC ldi YH, high(ADCwriteAdd) ldi YL, low(ADCwriteAdd) ldi TEMP, low(ADCtable) st Y+, TEMP ldi TEMP, high(ADCtable) st Y, TEMP ;Reset ADCwriteAdd to ADCtable begin reti ;------------------------------------------------------------------------------ Record: ;INT0 isr Enable ADC and start T0 rcall DBint sbic GPIOR0, 0 rjmp StopRecord ldi TEMP, (1<<ADEN)|(1<<ADATE)|(1<<ADIE)|(1<<ADPS1)|(1<<ADPS0) sts ADCSRA, TEMP ldi TEMP, (1<<WGM02)|(1<<CS02)|(0<<CS01)|(1<<CS00) out TCCR0B, TEMP sbi PORTB, PB0 ;Record Indicator On sbi GPIOR0, 0 reti StopRecord: clr TEMP out TCCR0B, TEMP ;Stop T0 cbi PORTB, PB0 ;Record Indicator Off cbi GPIOR0, 0 reti ;------------------------------------------------------------------------------ ;Get ADC data table index stored in SRAM at ADCreadAdd ;Enable OVF0 interrupt and Start T0 Play: ;INT1 isr rcall DBint sbic GPIOR0, 1 rjmp StopPlay lds XH, high(ADCreadAdd) lds XL, low(ADCreadAdd) lds YH, high(ADCwriteAdd) lds YL, low(ADCwriteAdd) cp YL, XL cpc YH, XH breq StopPlay ldi TEMP, low(ADCtableEnd) cp XL, TEMP ldi TEMP, high(ADCtableEnd) cpc XH, TEMP breq StopPlay cbi EIMSK, INT0 ldi TEMP, (1<<TOIE0) sts TIMSK0, TEMP ldi TEMP, (1<<WGM02)|(1<<CS02)|(0<<CS01)|(1<<CS00) out TCCR0B, TEMP sbi GPIOR0, 1 reti StopPlay: ;Enable OCIE1A OCIE1A function stops T1 clock after OC1A Pin goes Low ; and disables OCIE1A for one time event. ;Stop T0 clock lds YH, high(ADCreadAdd) lds YL, low(ADCreadAdd) sbi EIMSK, INT0 reti ;------------------------------------------------------------------------------ ;Check if at end of written data or end of table ;Read ADC Data, Multiply by 6 and output to OCR1A PlayNextValue: ;TODO Read values and write to OCR1A ld ADCin, X+ ldi TEMP, $06 mul ADCin, TEMP ldi TEMP, low(PWmin) add R0, TEMP ldi TEMP, high(PWmin) adc R1, TEMP sts OCR1AH, R1 sts OCR1AL, R0 reti ;------------------------------------------------------------------------------ DBint: ldi DBcount, $50 in ButtonInput, PIND andi ButtonInput, $C0 NextRead: in TEMP, PIND andi TEMP, $C0 cp TEMP, ButtonInput brne DBint dec DBcount brne NextRead sbi EIFR, INTF0 ret
TITIE Troubleshoot.asm INCLUDE Irvine32.asm rows = 2 * 3 PressKey equ <Press a Key to continue. > .data a word ae32h b dword 015b c byte 32d astr byte "this is a string" anArr word ? , 32, 32h, word "th", 'is', ah .code main PROC mov eax, 0 mov ebx, eax mov eax, a; put a in eax mov ebx, b; put b in ebx mov a, b; a = b add a, b; a = c + b mov c; ebx; c = ebx mov bl, [anArray + 3] exit main END main
<% from pwnlib.shellcraft.mips.linux import syscall %> <%page args="fd, buf, nbytes, offset"/> <%docstring> Invokes the syscall pread. See 'man 2 pread' for more information. Arguments: fd(int): fd buf(void): buf nbytes(size_t): nbytes offset(off_t): offset </%docstring> ${syscall('SYS_pread', fd, buf, nbytes, offset)}
#include <iostream> #include <fstream> #include <cerrno> #include <cstring> #include <chrono> #include <memory> using namespace std; // Implemented with a buffer and C style char arrays. Can sometimes be slightly faster than C++ strings. class totalWithLen { // container for returning both a total and the size public: totalWithLen(unsigned long long int total, unsigned long long int len) : total(total), len(len) {}; const unsigned long long int total; const unsigned long long int len; }; totalWithLen get_file_contents(const char *filename) { ifstream in(filename, ios::binary | ios::ate); if (in) { unsigned long long int total = 0; const streamoff len = in.tellg(); // streamoff (should be type long long) used to cast tellg() in.seekg(0, ios::beg); constexpr unsigned int bufferSize = 1024*1024; unique_ptr<char[]> buffer(new char[bufferSize]); const streamoff maxPos = len - bufferSize; unsigned int i = 0; while (in) { if ((streamoff) in.tellg() >= maxPos) { // when the buffer exceeds the length of file (last section) streamoff currentPosition = len-in.tellg(); in.read(buffer.get(), currentPosition); // read to end of file for (unsigned int i = 0; i < currentPosition; i++) { // do stuff if (buffer.get()[i]%2) { total++; } } break; } in.read(buffer.get(), bufferSize); for (; i < bufferSize; i++) { // calculate total of even numbers in buffer if (buffer.get()[i]%2) { total++; } } i = 0; } in.close(); totalWithLen result(total, len); return result; } cerr << "Error: " << strerror(errno) << endl; throw(errno); } int main(int argc, char *argv[]) { if (argc == 1) { cerr << "Error: Missing filename argument" << endl; return 0; } auto start = chrono::high_resolution_clock::now(); totalWithLen result = get_file_contents(argv[1]); auto finish = chrono::high_resolution_clock::now(); chrono::duration<double> elapsed = finish - start; cout << "Total: " << result.total << endl; cout << "Filesize: " << result.len << endl; cout << "Ratio: " << result.total/(long double) result.len << endl; cout << "Elapsed time: " << elapsed.count() << " s" << endl; }
// Copyright 2020 The XLS 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 "xls/passes/bdd_function.h" #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/memory/memory.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "xls/common/logging/log_lines.h" #include "xls/common/logging/logging.h" #include "xls/common/status/ret_check.h" #include "xls/common/status/status_macros.h" #include "xls/interpreter/ir_interpreter.h" #include "xls/ir/abstract_evaluator.h" #include "xls/ir/abstract_node_evaluator.h" #include "xls/ir/dfs_visitor.h" #include "xls/ir/node.h" #include "xls/ir/node_iterator.h" namespace xls { namespace { // Construct a BDD-based abstract evaluator. The expressions in the BDD // saturates at a particular number of paths from the expression node to the // terminal nodes 0 and 1 in the BDD. When the path limit is met, a new BDD // variable is created in its place effective forgetting any information about // the value. This avoids exponential blowup problems when constructing the BDD // at the cost of precision. The primitive bit element of the abstract evaluator // is a sum type consisting of a BDD node and a sentinel value TooManyPaths. The // TooManyPaths value is produced if the number of paths in the computed // expression exceed some limit. Any logical operation performed with a // TooManyPaths value produces a TooManyPaths value. struct TooManyPaths {}; using SaturatingBddNodeIndex = absl::variant<BddNodeIndex, TooManyPaths>; using SaturatingBddNodeVector = std::vector<SaturatingBddNodeIndex>; // The AbstractEvaluator requires equals to and not equals to operations on the // primitive element. bool operator==(const SaturatingBddNodeIndex& a, const SaturatingBddNodeIndex& b) { if (absl::holds_alternative<TooManyPaths>(a) || absl::holds_alternative<TooManyPaths>(b)) { return false; } return absl::get<BddNodeIndex>(a) == absl::get<BddNodeIndex>(b); } bool operator!=(const SaturatingBddNodeIndex& a, const SaturatingBddNodeIndex& b) { return !(a == b); } // Converts the given saturating BDD vector to a normal vector of BDD nodes. The // input vector must not contain any TooManyPaths values. BddNodeVector ToBddNodeVector(const SaturatingBddNodeVector& input) { BddNodeVector result(input.size()); for (int64_t i = 0; i < input.size(); ++i) { XLS_CHECK(absl::holds_alternative<BddNodeIndex>(input[i])); result[i] = absl::get<BddNodeIndex>(input[i]); } return result; } // The abstract evaluator based on a BDD with path-saturating logic. class SaturatingBddEvaluator : public AbstractEvaluator<SaturatingBddNodeIndex, SaturatingBddEvaluator> { public: SaturatingBddEvaluator(int64_t path_limit, BinaryDecisionDiagram* bdd) : path_limit_(path_limit), bdd_(bdd) {} SaturatingBddNodeIndex One() const { return bdd_->one(); } SaturatingBddNodeIndex Zero() const { return bdd_->zero(); } SaturatingBddNodeIndex Not(const SaturatingBddNodeIndex& input) const { if (absl::holds_alternative<TooManyPaths>(input)) { return TooManyPaths(); } BddNodeIndex result = bdd_->Not(absl::get<BddNodeIndex>(input)); if (path_limit_ > 0 && bdd_->path_count(result) > path_limit_) { return TooManyPaths(); } return result; } SaturatingBddNodeIndex And(const SaturatingBddNodeIndex& a, const SaturatingBddNodeIndex& b) const { if (absl::holds_alternative<TooManyPaths>(a) || absl::holds_alternative<TooManyPaths>(b)) { return TooManyPaths(); } BddNodeIndex result = bdd_->And(absl::get<BddNodeIndex>(a), absl::get<BddNodeIndex>(b)); if (path_limit_ > 0 && bdd_->path_count(result) > path_limit_) { return TooManyPaths(); } return result; } SaturatingBddNodeIndex Or(const SaturatingBddNodeIndex& a, const SaturatingBddNodeIndex& b) const { if (absl::holds_alternative<TooManyPaths>(a) || absl::holds_alternative<TooManyPaths>(b)) { return TooManyPaths(); } BddNodeIndex result = bdd_->Or(absl::get<BddNodeIndex>(a), absl::get<BddNodeIndex>(b)); if (path_limit_ > 0 && bdd_->path_count(result) > path_limit_) { return TooManyPaths(); } return result; } private: int64_t path_limit_; BinaryDecisionDiagram* bdd_; }; // Returns whether the given op should be included in BDD computations. bool ShouldEvaluate(Node* node) { if (!node->GetType()->IsBits()) { return false; } switch (node->op()) { // Logical ops. case Op::kAnd: case Op::kNand: case Op::kNor: case Op::kNot: case Op::kOr: case Op::kXor: return true; // Extension ops. case Op::kSignExt: case Op::kZeroExt: return true; case Op::kLiteral: return true; // Bit moving ops. case Op::kBitSlice: case Op::kDynamicBitSlice: case Op::kConcat: case Op::kReverse: case Op::kIdentity: return true; // Select operations. case Op::kOneHot: case Op::kOneHotSel: case Op::kSel: return true; // Encode/decode operations: case Op::kDecode: case Op::kEncode: return true; // Comparison operation are only expressed if at least one of the operands // is a literal. This avoids the potential exponential explosion of BDD // nodes which can occur with pathological variable ordering. case Op::kUGe: case Op::kUGt: case Op::kULe: case Op::kULt: case Op::kEq: case Op::kNe: return node->operand(0)->Is<Literal>() || node->operand(1)->Is<Literal>(); // Arithmetic ops case Op::kAdd: case Op::kSMul: case Op::kUMul: case Op::kNeg: case Op::kSDiv: case Op::kSub: case Op::kUDiv: case Op::kSMod: case Op::kUMod: return false; // Reduction ops. case Op::kAndReduce: case Op::kOrReduce: case Op::kXorReduce: return true; // Weirdo ops. case Op::kAfterAll: case Op::kArray: case Op::kArrayConcat: case Op::kArrayIndex: case Op::kArraySlice: case Op::kArrayUpdate: case Op::kAssert: case Op::kCountedFor: case Op::kCover: case Op::kDynamicCountedFor: case Op::kGate: case Op::kInputPort: case Op::kInvoke: case Op::kMap: case Op::kOutputPort: case Op::kParam: case Op::kReceive: case Op::kRegisterRead: case Op::kRegisterWrite: case Op::kSend: case Op::kTrace: case Op::kTuple: case Op::kTupleIndex: case Op::kInstantiationInput: case Op::kInstantiationOutput: return false; // Unsupported comparison operations. case Op::kSGt: case Op::kSGe: case Op::kSLe: case Op::kSLt: return false; // Shift operations and related ops. // Shifts are very intensive to compute because they decompose into many, // many gates and they don't seem to provide much benefit. Turn-off for now. // TODO(meheff): Consider enabling shifts. case Op::kShll: case Op::kShra: case Op::kShrl: case Op::kBitSliceUpdate: return false; } XLS_LOG(FATAL) << "Invalid op: " << static_cast<int64_t>(node->op()); } } // namespace /* static */ absl::StatusOr<std::unique_ptr<BddFunction>> BddFunction::Run( FunctionBase* f, int64_t path_limit, absl::Span<const Op> do_not_evaluate_ops) { XLS_VLOG(1) << absl::StreamFormat("BddFunction::Run(%s):", f->name()); XLS_VLOG_LINES(5, f->DumpIr()); auto bdd_function = absl::WrapUnique(new BddFunction(f)); SaturatingBddEvaluator evaluator(path_limit, &bdd_function->bdd()); absl::flat_hash_set<Op> do_not_evaluate_ops_set; for (Op op : do_not_evaluate_ops) { do_not_evaluate_ops_set.insert(op); } // Create and return a vector containing newly defined BDD variables. auto create_new_node_vector = [&](Node* n) { SaturatingBddNodeVector v; for (int64_t i = 0; i < n->BitCountOrDie(); ++i) { v.push_back(bdd_function->bdd().NewVariable()); } bdd_function->saturated_expressions_.insert(n); return v; }; XLS_VLOG(3) << "BDD expressions:"; absl::flat_hash_map<Node*, SaturatingBddNodeVector> values; for (Node* node : TopoSort(f)) { if (!node->GetType()->IsBits()) { continue; } // If we shouldn't evaluate this node, the node is to be modeled as // variables, or the node includes some non-bits-typed operands, then just // create a vector of new BDD variables for this node. if (!ShouldEvaluate(node) || do_not_evaluate_ops_set.contains(node->op()) || std::any_of(node->operands().begin(), node->operands().end(), [](Node* o) { return !o->GetType()->IsBits(); })) { values[node] = create_new_node_vector(node); } else { std::vector<SaturatingBddNodeVector> operand_values; for (Node* operand : node->operands()) { operand_values.push_back(values.at(operand)); } XLS_ASSIGN_OR_RETURN( values[node], AbstractEvaluate(node, operand_values, &evaluator, /*default_handler=*/create_new_node_vector)); // Associate a new BDD variable with each bit that exceeded the path // limit. for (SaturatingBddNodeIndex& value : values.at(node)) { if (absl::holds_alternative<TooManyPaths>(value)) { bdd_function->saturated_expressions_.insert(node); value = bdd_function->bdd().NewVariable(); } } } XLS_VLOG(5) << " " << node->GetName() << ":"; for (int64_t i = 0; i < node->BitCountOrDie(); ++i) { XLS_VLOG(5) << absl::StreamFormat( " bit %d : %s", i, bdd_function->bdd().ToStringDnf( absl::get<BddNodeIndex>(values.at(node)[i]), /*minterm_limit=*/15)); } } // Copy over the vector and BDD variables into the node map which is exposed // via the BddFunction interface. At this point any TooManyPaths sentinel // values have been replaced with new Bdd variables. for (const auto& pair : values) { bdd_function->node_map_[pair.first] = ToBddNodeVector(pair.second); } return std::move(bdd_function); } absl::StatusOr<Value> BddFunction::Evaluate( absl::Span<const Value> args) const { if (!func_base_->IsFunction()) { return absl::InvalidArgumentError( "Can only evaluate functions with BddFunction , not procs."); } Function* function = func_base_->AsFunctionOrDie(); // Map containing the result of each node. absl::flat_hash_map<const Node*, Value> values; // Map of the BDD variable values. absl::flat_hash_map<BddNodeIndex, bool> bdd_variable_values; XLS_RET_CHECK_EQ(args.size(), function->params().size()); for (Node* node : TopoSort(function)) { XLS_VLOG(2) << "node: " << node; Value result; if (node->Is<Param>()) { XLS_ASSIGN_OR_RETURN(int64_t param_index, function->GetParamIndex(node->As<Param>())); result = args.at(param_index); } else if (OpIsSideEffecting(node->op()) && node->GetType()->IsToken()) { // Don't evaluate side-effecting ops that return tokens (e.g. assert, // trace, cover), but conjure a placeholder token so that values.at(node) // doesn't have to deal with missing nodes. result = Value::Token(); } else if (!node->GetType()->IsBits() || saturated_expressions_.contains(node)) { std::vector<Value> operand_values; for (Node* operand : node->operands()) { operand_values.push_back(values.at(operand)); } XLS_ASSIGN_OR_RETURN(result, InterpretNode(node, operand_values)); } else { const BddNodeVector& bdd_vector = node_map_.at(node); absl::InlinedVector<bool, 64> bits; for (int64_t i = 0; i < bdd_vector.size(); ++i) { XLS_ASSIGN_OR_RETURN(bool bit_result, bdd_.Evaluate(bdd_vector[i], bdd_variable_values)); bits.push_back(bit_result); } result = Value(Bits(bits)); } values[node] = result; XLS_VLOG(2) << " result: " << result; // Write BDD variable values into the map used for evaluation. if (node_map_.contains(node)) { const BddNodeVector& bdd_vector = node_map_.at(node); for (int64_t i = 0; i < bdd_vector.size(); ++i) { if (bdd_.IsVariableBaseNode(bdd_vector.at(i))) { bdd_variable_values[bdd_vector.at(i)] = result.bits().Get(i); } } } } return values.at(function->return_value()); } } // namespace xls
assume cs:code code segment mov ax,0ffffh mov ds,ax mov ax,0020h mov es,ax mov bx,0 ; EA mov cx,12 ; loop counter s: mov ds:[bx],dl ; (dl) <- (ffff:EA) mov es:[bx],dl ; (0020:EA) <- (dl) inc bx ; EA++ loop s mov ax,4c00h int 21h code ends end
; @author Changlon <changlong.a2@gmail.com> ; @github https://github.com/Changlon ; @date 2022-02-05 15:33:03 ; IF 中断标志位,1 ->接受 INTER 中断信号 ; cli ->清除IF -> 0 ; sti -> 设置IF -> 1 ; iret -> pop : ip ,cs ,flags ; test r/m , r/imm 相当于and 但不保存结果,影响 zf,sf,pf ; test al, 0000 1000b 测试al 位3 从而影响 zf ; not r/m 求反指令 ; hlt 使cpu 进入睡眠状态 ; int r/imm 软中断,发生一个中断去处理中断指令 ; int3 断点调试中断 ; into 溢出中断指令 of 为1处理四号中断程序
// Copyright 2019 The Fuchsia 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 <lib/fidl/coding.h> #include <lib/fidl/internal.h> #include <lib/fidl/transformer.h> #include <cassert> #include <cinttypes> #include <cstdio> #include <cstring> #include <string> // Disable warning about implicit fallthrough, since it's intentionally used a // lot in this code, and the switch()es end up being harder to read without it. // Note that "#pragma GCC" works for both GCC & Clang. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" namespace { // This is an array of 32-bit ordinals that's intended to help debugging. The // array is normally empty, but you can add an ordinal to this array in your // local tree if you encounter a message in-the-field that the transformer is // having issues with. constexpr uint64_t kDebugOrdinals[] = { // 0x61f19458'00000000, // example ordinal }; enum struct WireFormat { kOld, kV1, }; // Call this macro instead of assert() when inside a TransformerBase method: it // will print out useful debugging information. This macro inlines the code in // order to get precise line number information, and to know the assertion being // evaluated. #define TRANSFORMER_ASSERT(assertion, position) \ { \ const auto ok = static_cast<bool>(assertion); \ if (!ok) { \ debug_info_->RecordFailure(__LINE__, (#assertion), (position)); \ assert(assertion); \ } \ } // Call this macro instead of the TransformerBase::Fail() method. This is a simple wrapper to pass // the current __LINE__ number to Fail(). #define TRANSFORMER_FAIL(status, position, error_message) \ Fail(status, position, __LINE__, error_message); // Every Transform() method outputs a TraversalResult, which indicates how many out-of-line bytes // that transform method consumed, and the actual (not max) number of handles that were encountered // during the transformation. This is needed for writing the correct size and handle information in // an envelope. (This isn't a great name. A better name would be welcome!) struct TraversalResult { uint32_t src_out_of_line_size = 0u; uint32_t dst_out_of_line_size = 0u; uint32_t handle_count = 0u; TraversalResult& operator+=(const TraversalResult rhs) { src_out_of_line_size += rhs.src_out_of_line_size; dst_out_of_line_size += rhs.dst_out_of_line_size; handle_count += rhs.handle_count; return *this; } }; constexpr uint32_t PrimitiveSize(const FidlCodedPrimitive primitive) { switch (primitive) { case kFidlCodedPrimitive_Bool: case kFidlCodedPrimitive_Int8: case kFidlCodedPrimitive_Uint8: return 1; case kFidlCodedPrimitive_Int16: case kFidlCodedPrimitive_Uint16: return 2; case kFidlCodedPrimitive_Int32: case kFidlCodedPrimitive_Uint32: case kFidlCodedPrimitive_Float32: return 4; case kFidlCodedPrimitive_Int64: case kFidlCodedPrimitive_Uint64: case kFidlCodedPrimitive_Float64: return 8; } __builtin_unreachable(); } // This function is named UnsafeInlineSize since it assumes that |type| will be // non-null. Don't call this function directly; instead, call // TransformerBase::InlineSize(). uint32_t UnsafeInlineSize(const fidl_type_t* type, WireFormat wire_format) { assert(type); switch (type->type_tag) { case kFidlTypePrimitive: return PrimitiveSize(type->coded_primitive); case kFidlTypeEnum: return PrimitiveSize(type->coded_enum.underlying_type); case kFidlTypeBits: return PrimitiveSize(type->coded_bits.underlying_type); case kFidlTypeStructPointer: return 8; case kFidlTypeUnionPointer: assert(wire_format == WireFormat::kOld); return 8; case kFidlTypeVector: case kFidlTypeString: return 16; case kFidlTypeStruct: return type->coded_struct.size; case kFidlTypeUnion: assert(wire_format == WireFormat::kOld); return type->coded_union.size; case kFidlTypeArray: return type->coded_array.array_size; case kFidlTypeXUnion: return 24; case kFidlTypeHandle: return 4; case kFidlTypeTable: return 16; } // This is needed to suppress a GCC warning "control reaches end of non-void function", since GCC // treats switch() on enums as non-exhaustive without a default case. assert(false && "unexpected non-exhaustive switch on FidlTypeTag"); return 0; } struct Position { uint32_t src_inline_offset = 0; uint32_t src_out_of_line_offset = 0; uint32_t dst_inline_offset = 0; uint32_t dst_out_of_line_offset = 0; Position(uint32_t src_inline_offset, uint32_t src_out_of_line_offset, uint32_t dst_inline_offset, uint32_t dst_out_of_line_offset) : src_inline_offset(src_inline_offset), src_out_of_line_offset(src_out_of_line_offset), dst_inline_offset(dst_inline_offset), dst_out_of_line_offset(dst_out_of_line_offset) {} Position(const Position&) = default; Position& operator=(const Position&) = default; inline Position IncreaseInlineOffset(uint32_t increase) const __attribute__((warn_unused_result)) { return IncreaseSrcInlineOffset(increase).IncreaseDstInlineOffset(increase); } inline Position IncreaseSrcInlineOffset(uint32_t increase) const __attribute__((warn_unused_result)) { return Position(src_inline_offset + increase, src_out_of_line_offset, dst_inline_offset, dst_out_of_line_offset); } inline Position IncreaseSrcOutOfLineOffset(uint32_t increase) const __attribute__((warn_unused_result)) { return Position(src_inline_offset, src_out_of_line_offset + increase, dst_inline_offset, dst_out_of_line_offset); } inline Position IncreaseDstInlineOffset(uint32_t increase) const __attribute__((warn_unused_result)) { return Position(src_inline_offset, src_out_of_line_offset, dst_inline_offset + increase, dst_out_of_line_offset); } inline Position IncreaseDstOutOfLineOffset(uint32_t increase) const __attribute__((warn_unused_result)) { return Position(src_inline_offset, src_out_of_line_offset, dst_inline_offset, dst_out_of_line_offset + increase); } std::string ToString() const { char buffer[32]; snprintf(buffer, sizeof(buffer), "{0x%02x, 0x%02x, 0x%02x, 0x%02x}", src_inline_offset, src_out_of_line_offset, dst_inline_offset, dst_out_of_line_offset); return std::string(buffer); } }; class SrcDst final { public: SrcDst(const uint8_t* src_bytes, const uint32_t src_num_bytes, uint8_t* dst_bytes, uint32_t dst_num_bytes_capacity) : src_bytes_(src_bytes), src_max_offset_(src_num_bytes), dst_bytes_(dst_bytes), dst_max_offset_(dst_num_bytes_capacity) {} SrcDst(const SrcDst&) = delete; // Reads |T| from |src_bytes|. // This may update the max src read offset if needed. template <typename T> const T* __attribute__((warn_unused_result)) Read(const Position& position) { return Read<T>(position, sizeof(T)); } // Reads |size| bytes from |src_bytes|, but only returns a pointer to |T| // which may be smaller, i.e. |sizeof(T)| can be smaller than |size|. // This may update the max src read offset if needed. template <typename T> const T* __attribute__((warn_unused_result)) Read(const Position& position, uint32_t size) { assert(sizeof(T) <= size); const auto status = src_max_offset_.Update(position.src_inline_offset + size); if (status != ZX_OK) { return nullptr; } return reinterpret_cast<const T*>(src_bytes_ + position.src_inline_offset); } // Copies |size| bytes from |src_bytes| to |dst_bytes|. // This may update the max src read offset if needed. // This may update the max dst written offset if needed. zx_status_t __attribute__((warn_unused_result)) Copy(const Position& position, uint32_t size) { const auto src_status = src_max_offset_.Update(position.src_inline_offset + size); if (src_status != ZX_OK) { return src_status; } const auto dst_status = dst_max_offset_.Update(position.dst_inline_offset + size); if (dst_status != ZX_OK) { return dst_status; } memcpy(dst_bytes_ + position.dst_inline_offset, src_bytes_ + position.src_inline_offset, size); return ZX_OK; } // Pads |size| bytes in |dst_bytes|. // This may update the max dst written offset if needed. zx_status_t __attribute__((warn_unused_result)) Pad(const Position& position, uint32_t size) { const auto status = dst_max_offset_.Update(position.dst_inline_offset + size); if (status != ZX_OK) { return status; } memset(dst_bytes_ + position.dst_inline_offset, 0, size); return ZX_OK; } // Writes |value| in |dst_bytes|. // This may update the max dst written offset if needed. template <typename T> zx_status_t __attribute__((warn_unused_result)) Write(const Position& position, T value) { const auto size = static_cast<uint32_t>(sizeof(value)); const auto status = dst_max_offset_.Update(position.dst_inline_offset + size); if (status != ZX_OK) { return status; } auto ptr = reinterpret_cast<T*>(dst_bytes_ + position.dst_inline_offset); *ptr = value; return ZX_OK; } const uint8_t* src_bytes() const { return src_bytes_; } uint32_t src_num_bytes() const { return src_max_offset_.capacity_; } uint32_t src_max_offset_read() const { return src_max_offset_.max_offset_; } uint8_t* dst_bytes() const { return dst_bytes_; } uint32_t dst_num_bytes_capacity() const { return dst_max_offset_.capacity_; } uint32_t dst_max_offset_written() const { return dst_max_offset_.max_offset_; } private: struct MaxOffset { MaxOffset(uint32_t capacity) : capacity_(capacity) {} const uint32_t capacity_; uint32_t max_offset_ = 0; zx_status_t __attribute__((warn_unused_result)) Update(uint32_t offset) { if (offset > capacity_) { return ZX_ERR_BAD_STATE; } if (offset > max_offset_) { max_offset_ = offset; } return ZX_OK; } }; const uint8_t* src_bytes_; MaxOffset src_max_offset_; uint8_t* dst_bytes_; MaxOffset dst_max_offset_; }; // Debug related information, which is set both on construction, and as we // transform. On destruction, this object writes any collected error message // if an |out_error_msg| is provided. class DebugInfo final { public: DebugInfo(fidl_transformation_t transformation, const fidl_type_t* type, const SrcDst& src_dst, const char** out_error_msg) : transformation_(transformation), type_(type), src_dst_(src_dst), out_error_msg_(out_error_msg) {} DebugInfo(const DebugInfo&) = delete; ~DebugInfo() { if (has_failed_) { Print("ERROR"); } if (out_error_msg_) { *out_error_msg_ = error_msg_; } } void RecordFailure(int line_number, const char* error_msg) { has_failed_ = true; error_msg_ = error_msg; line_number_ = line_number; } void RecordFailure(int line_number, const char* error_msg, const Position& position) { RecordFailure(line_number, error_msg); position_ = position; } void DebugPrint(int line_number, const char* error_msg, const Position& position) const { DebugInfo dup(transformation_, type_, src_dst_, nullptr); dup.RecordFailure(line_number, error_msg, position); dup.Print("INFO"); // Avoid printing twice. dup.has_failed_ = false; } private: void Print(const std::string& failure_type) const { printf("=== TRANSFORMER %s ===\n", failure_type.c_str()); char type_desc[256] = {}; fidl_format_type_name(type_, type_desc, sizeof(type_desc)); printf("src: " __FILE__ "\n"); printf("direction: %s\n", direction().c_str()); printf("transformer.cc:%d: %s\n", line_number_, error_msg_); printf("top level type: %s\n", type_desc); printf("position: %s\n", position_.ToString().c_str()); auto print_bytes = [&](const uint8_t* buffer, uint32_t size, uint32_t out_of_line_offset) { for (uint32_t i = 0; i < size; i++) { if (i == out_of_line_offset) { printf(" // out-of-line\n"); } if (i % 8 == 0) { printf(" "); } printf("0x%02x, ", buffer[i]); if (i % 0x10 == 0x07) { printf(" // 0x%02x\n", i - 7); } else if (i % 0x08 == 0x07) { printf("\n"); } } }; printf("uint8_t src_bytes[0x%02x] = {\n", src_dst_.src_num_bytes()); print_bytes(src_dst_.src_bytes(), src_dst_.src_num_bytes(), position_.src_out_of_line_offset); printf("}\n"); printf("uint8_t dst_bytes[0x%02x] = { // capacity = 0x%02x\n", src_dst_.dst_max_offset_written(), src_dst_.dst_num_bytes_capacity()); print_bytes(src_dst_.dst_bytes(), src_dst_.dst_max_offset_written(), position_.dst_out_of_line_offset); printf("}\n"); printf("=== END TRANSFORMER %s ===\n", failure_type.c_str()); } std::string direction() const { switch (transformation_) { case FIDL_TRANSFORMATION_NONE: return "none"; case FIDL_TRANSFORMATION_V1_TO_OLD: return "v1 to old"; case FIDL_TRANSFORMATION_OLD_TO_V1: return "old to v1"; default: return "unknown"; } } // Set on construction, and duplicated. const fidl_transformation_t transformation_; const fidl_type_t* type_; const SrcDst& src_dst_; // Set on construction, never duplicated. const char** out_error_msg_; // Set post construction, never duplicated. bool has_failed_ = false; const char* error_msg_ = nullptr; int line_number_ = -1; Position position_{0, 0, 0, 0}; }; class TransformerBase { public: TransformerBase(SrcDst* src_dst, const fidl_type_t* top_level_src_type, DebugInfo* debug_info) : src_dst(src_dst), debug_info_(debug_info), top_level_src_type_(top_level_src_type) {} virtual ~TransformerBase() = default; uint32_t InlineSize(const fidl_type_t* type, WireFormat wire_format, const Position& position) { TRANSFORMER_ASSERT(type, position); return UnsafeInlineSize(type, wire_format); } uint32_t AltInlineSize(const fidl_type_t* type, const Position& position) { TRANSFORMER_ASSERT(type, position); switch (type->type_tag) { case kFidlTypeStruct: return InlineSize(type->coded_struct.alt_type, To(), position); case kFidlTypeUnion: return InlineSize(type->coded_union.alt_type, To(), position); case kFidlTypeArray: return InlineSize(type->coded_array.alt_type, To(), position); case kFidlTypeXUnion: return InlineSize(type->coded_xunion.alt_type, To(), position); case kFidlTypePrimitive: case kFidlTypeEnum: case kFidlTypeBits: case kFidlTypeStructPointer: case kFidlTypeUnionPointer: case kFidlTypeVector: case kFidlTypeString: case kFidlTypeHandle: case kFidlTypeTable: return InlineSize(type, To(), position); } TRANSFORMER_ASSERT(false && "unexpected non-exhaustive switch on FidlTypeTag", position); return 0; } void MaybeDebugPrintTopLevelStruct(const Position& position) { if (sizeof(kDebugOrdinals) == 0) { return; } auto maybe_ordinal = src_dst->Read<uint64_t>( position.IncreaseSrcInlineOffset(offsetof(fidl_message_header_t, ordinal))); if (!maybe_ordinal) { return; } for (uint64_t debug_ordinal : kDebugOrdinals) { if (debug_ordinal != *maybe_ordinal) { continue; } char buffer[16]; snprintf(buffer, sizeof(buffer), "0x%016" PRIx64, debug_ordinal); debug_info_->DebugPrint(__LINE__, buffer, position); } } zx_status_t TransformTopLevelStruct() { if (top_level_src_type_->type_tag != kFidlTypeStruct) { return TRANSFORMER_FAIL(ZX_ERR_INVALID_ARGS, (Position{0, 0, 0, 0}), "only top-level structs supported"); } const auto& src_coded_struct = top_level_src_type_->coded_struct; const auto& dst_coded_struct = src_coded_struct.alt_type->coded_struct; // Since this is the top-level struct, the first secondary object (i.e. // out-of-line offset) is exactly placed after this struct, i.e. the // struct's inline size. const auto start_position = Position(0, src_coded_struct.size, 0, dst_coded_struct.size); TraversalResult discarded_traversal_result; const zx_status_t status = TransformStruct(src_coded_struct, dst_coded_struct, start_position, FIDL_ALIGN(dst_coded_struct.size), &discarded_traversal_result); MaybeDebugPrintTopLevelStruct(start_position); return status; } protected: zx_status_t Transform(const fidl_type_t* type, const Position& position, const uint32_t dst_size, TraversalResult* out_traversal_result) { if (!type) { return src_dst->Copy(position, dst_size); } switch (type->type_tag) { case kFidlTypeHandle: return TransformHandle(position, dst_size, out_traversal_result); case kFidlTypePrimitive: case kFidlTypeEnum: case kFidlTypeBits: return src_dst->Copy(position, dst_size); case kFidlTypeStructPointer: { const auto& src_coded_struct = *type->coded_struct_pointer.struct_type; const auto& dst_coded_struct = src_coded_struct.alt_type->coded_struct; return TransformStructPointer(src_coded_struct, dst_coded_struct, position, out_traversal_result); } case kFidlTypeUnionPointer: { const auto& src_coded_union = *type->coded_union_pointer.union_type; const auto& dst_coded_xunion = src_coded_union.alt_type->coded_xunion; return TransformUnionPointerToOptionalXUnion(src_coded_union, dst_coded_xunion, position, out_traversal_result); } case kFidlTypeStruct: { const auto& src_coded_struct = type->coded_struct; const auto& dst_coded_struct = src_coded_struct.alt_type->coded_struct; return TransformStruct(src_coded_struct, dst_coded_struct, position, dst_size, out_traversal_result); } case kFidlTypeUnion: { const auto& src_coded_union = type->coded_union; const auto& dst_coded_union = src_coded_union.alt_type->coded_xunion; return TransformUnionToXUnion(src_coded_union, dst_coded_union, position, dst_size, out_traversal_result); } case kFidlTypeArray: { const auto convert = [](const FidlCodedArray& coded_array) { FidlCodedArrayNew result = { .element = coded_array.element, .element_count = coded_array.array_size / coded_array.element_size, .element_size = coded_array.element_size, .element_padding = 0, .alt_type = nullptr /* alt_type unused, we provide both src and dst */}; return result; }; auto src_coded_array = convert(type->coded_array); auto dst_coded_array = convert(type->coded_array.alt_type->coded_array); return TransformArray(src_coded_array, dst_coded_array, position, dst_size, out_traversal_result); } case kFidlTypeString: return TransformString(position, out_traversal_result); case kFidlTypeVector: { const auto& src_coded_vector = type->coded_vector; const auto& dst_coded_vector = src_coded_vector.alt_type->coded_vector; return TransformVector(src_coded_vector, dst_coded_vector, position, out_traversal_result); } case kFidlTypeTable: return TransformTable(type->coded_table, position, out_traversal_result); case kFidlTypeXUnion: TRANSFORMER_ASSERT(type->coded_xunion.alt_type, position); switch (type->coded_xunion.alt_type->type_tag) { case kFidlTypeUnion: return TransformXUnionToUnion(type->coded_xunion, type->coded_xunion.alt_type->coded_union, position, dst_size, out_traversal_result); case kFidlTypeUnionPointer: return TransformOptionalXUnionToUnionPointer( type->coded_xunion, *type->coded_xunion.alt_type->coded_union_pointer.union_type, position, out_traversal_result); case kFidlTypeXUnion: // NOTE: after https://fuchsia-review.googlesource.com/c/fuchsia/+/365937, // the alt type of a xunion should always be a union, so this path should // never be exercised return TransformXUnion(type->coded_xunion, position, out_traversal_result); case kFidlTypePrimitive: case kFidlTypeEnum: case kFidlTypeBits: case kFidlTypeStruct: case kFidlTypeStructPointer: case kFidlTypeArray: case kFidlTypeString: case kFidlTypeHandle: case kFidlTypeVector: case kFidlTypeTable: TRANSFORMER_ASSERT(false && "Invalid src_xunion alt_type->type_tag", position); __builtin_unreachable(); } } return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "unknown type tag"); // TODO(apang): Think about putting logic for updating out_traversal_result in Copy/etc // functions. } zx_status_t TransformHandle(const Position& position, uint32_t dst_size, TraversalResult* out_traversal_result) { auto presence = src_dst->Read<uint32_t>(position); if (!presence) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "handle presence missing"); } switch (*presence) { case FIDL_HANDLE_ABSENT: // Ok break; case FIDL_HANDLE_PRESENT: out_traversal_result->handle_count++; break; default: return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "handle presence invalid"); } return src_dst->Copy(position, dst_size); } zx_status_t TransformStructPointer(const FidlCodedStruct& src_coded_struct, const FidlCodedStruct& dst_coded_struct, const Position& position, TraversalResult* out_traversal_result) { auto presence = src_dst->Read<uint64_t>(position); if (!presence) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "struct pointer missing"); } auto status_copy_struct_pointer = src_dst->Copy(position, sizeof(uint64_t)); if (status_copy_struct_pointer != ZX_OK) { return status_copy_struct_pointer; } switch (*presence) { case FIDL_ALLOC_ABSENT: // Early exit on absent struct. return ZX_OK; case FIDL_ALLOC_PRESENT: // Ok break; default: return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "struct pointer invalid"); } uint32_t src_aligned_size = FIDL_ALIGN(src_coded_struct.size); uint32_t dst_aligned_size = FIDL_ALIGN(dst_coded_struct.size); const auto struct_position = Position{ position.src_out_of_line_offset, position.src_out_of_line_offset + src_aligned_size, position.dst_out_of_line_offset, position.dst_out_of_line_offset + dst_aligned_size, }; out_traversal_result->src_out_of_line_size += src_aligned_size; out_traversal_result->dst_out_of_line_size += dst_aligned_size; return TransformStruct(src_coded_struct, dst_coded_struct, struct_position, dst_aligned_size, out_traversal_result); } zx_status_t TransformStruct(const FidlCodedStruct& src_coded_struct, const FidlCodedStruct& dst_coded_struct, const Position& position, uint32_t dst_size, TraversalResult* out_traversal_result) { TRANSFORMER_ASSERT(src_coded_struct.field_count == dst_coded_struct.field_count, position); // Note: we cannot use dst_coded_struct.size, and must instead rely on // the provided dst_size since this struct could be placed in an alignment // context that is larger than its inherent size. // Copy structs without any coded fields, and done. if (src_coded_struct.field_count == 0) { return src_dst->Copy(position, dst_size); } const uint32_t src_start_of_struct = position.src_inline_offset; const uint32_t dst_start_of_struct = position.dst_inline_offset; auto current_position = position; for (uint32_t field_index = 0; field_index < src_coded_struct.field_count; field_index++) { const auto& src_field = src_coded_struct.fields[field_index]; const auto& dst_field = dst_coded_struct.fields[field_index]; if (!src_field.type) { const uint32_t dst_field_size = src_start_of_struct + src_field.padding_offset - current_position.src_inline_offset; const auto status_copy_field = src_dst->Copy(current_position, dst_field_size); if (status_copy_field != ZX_OK) { return status_copy_field; } current_position = current_position.IncreaseInlineOffset(dst_field_size); } else { // The only case where the amount we've written shouldn't match the specified offset is // for request/response structs, where the txn header is not specified in the coding table. if (current_position.src_inline_offset != src_start_of_struct + src_field.offset) { TRANSFORMER_ASSERT(src_field.offset == dst_field.offset, current_position); const auto status_copy_field = src_dst->Copy(current_position, src_field.offset); if (status_copy_field != ZX_OK) { return status_copy_field; } current_position = current_position.IncreaseInlineOffset(src_field.offset); } TRANSFORMER_ASSERT( current_position.src_inline_offset == src_start_of_struct + src_field.offset, current_position); TRANSFORMER_ASSERT( current_position.dst_inline_offset == dst_start_of_struct + dst_field.offset, current_position); // Transform field. uint32_t src_next_field_offset = current_position.src_inline_offset + InlineSize(src_field.type, From(), current_position); uint32_t dst_next_field_offset = current_position.dst_inline_offset + InlineSize(dst_field.type, To(), current_position); uint32_t dst_field_size = dst_next_field_offset - (dst_start_of_struct + dst_field.offset); TraversalResult field_traversal_result; const zx_status_t status = Transform(src_field.type, current_position, dst_field_size, &field_traversal_result); if (status != ZX_OK) { return status; } *out_traversal_result += field_traversal_result; // Update current position for next iteration. current_position.src_inline_offset = src_next_field_offset; current_position.dst_inline_offset = dst_next_field_offset; current_position.src_out_of_line_offset += field_traversal_result.src_out_of_line_size; current_position.dst_out_of_line_offset += field_traversal_result.dst_out_of_line_size; } // Pad (possibly with 0 bytes). const auto status_pad = src_dst->Pad(current_position, dst_field.padding); if (status_pad != ZX_OK) { return TRANSFORMER_FAIL(status_pad, current_position, "unable to pad end of struct element"); } current_position = current_position.IncreaseDstInlineOffset(dst_field.padding); current_position = current_position.IncreaseSrcInlineOffset(src_field.padding); } // Pad (possibly with 0 bytes). const uint32_t dst_end_of_struct = position.dst_inline_offset + dst_size; const auto status_pad = src_dst->Pad(current_position, dst_end_of_struct - current_position.dst_inline_offset); if (status_pad != ZX_OK) { return TRANSFORMER_FAIL(status_pad, current_position, "unable to pad end of struct"); } return ZX_OK; } zx_status_t TransformVector(const FidlCodedVector& src_coded_vector, const FidlCodedVector& dst_coded_vector, const Position& position, TraversalResult* out_traversal_result) { const auto src_vector = src_dst->Read<fidl_vector_t>(position); if (!src_vector) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "vector missing"); } // Copy vector header. const auto status_copy_vector_hdr = src_dst->Copy(position, sizeof(fidl_vector_t)); if (status_copy_vector_hdr != ZX_OK) { return status_copy_vector_hdr; } const auto presence = reinterpret_cast<uint64_t>(src_vector->data); switch (presence) { case FIDL_ALLOC_ABSENT: // Early exit on nullable vectors. return ZX_OK; case FIDL_ALLOC_PRESENT: // OK break; default: return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "vector presence invalid"); } const auto convert = [&](const FidlCodedVector& coded_vector) { FidlCodedArrayNew result = { .element = coded_vector.element, .element_count = static_cast<uint32_t>(src_vector->count), .element_size = coded_vector.element_size, .element_padding = 0, .alt_type = nullptr /* alt_type unused, we provide both src and dst */}; return result; }; const auto src_vector_data_as_coded_array = convert(src_coded_vector); const auto dst_vector_data_as_coded_array = convert(dst_coded_vector); // Calculate vector size. They fit in uint32_t due to automatic bounds. uint32_t src_vector_size = FIDL_ALIGN(static_cast<uint32_t>(src_vector->count * (src_coded_vector.element_size))); uint32_t dst_vector_size = FIDL_ALIGN(static_cast<uint32_t>(src_vector->count * (dst_coded_vector.element_size))); // Transform elements. auto vector_data_position = Position{ position.src_out_of_line_offset, position.src_out_of_line_offset + src_vector_size, position.dst_out_of_line_offset, position.dst_out_of_line_offset + dst_vector_size}; const zx_status_t status = TransformArray(src_vector_data_as_coded_array, dst_vector_data_as_coded_array, vector_data_position, dst_vector_size, out_traversal_result); if (status != ZX_OK) { return status; } out_traversal_result->src_out_of_line_size += src_vector_size; out_traversal_result->dst_out_of_line_size += dst_vector_size; return ZX_OK; } zx_status_t TransformString(const Position& position, TraversalResult* out_traversal_result) { FidlCodedVector string_as_coded_vector = { .element = nullptr, .max_count = 0 /*unused*/, .element_size = 1, .nullable = kFidlNullability_Nullable, /* constraints are not checked, i.e. unused */ .alt_type = nullptr /* alt_type unused, we provide both src and dst */}; return TransformVector(string_as_coded_vector, string_as_coded_vector, position, out_traversal_result); } // TODO(apang): Replace |known_type| & |type| parameters below with a single fit::optional<const // fidl_type_t*> parameter. zx_status_t TransformEnvelope(bool known_type, const fidl_type_t* type, const Position& position, TraversalResult* out_traversal_result) { auto src_envelope = src_dst->Read<const fidl_envelope_t>(position); if (!src_envelope) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "envelope missing"); } switch (src_envelope->presence) { case FIDL_ALLOC_ABSENT: { const auto status = src_dst->Copy(position, sizeof(fidl_envelope_t)); if (status != ZX_OK) { return TRANSFORMER_FAIL(status, position, "unable to copy envelope header"); } return ZX_OK; } case FIDL_ALLOC_PRESENT: // We write the transformed envelope after the transformation, since // the num_bytes may be different in the dst. break; default: return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "envelope presence invalid"); } if (!known_type) { // When we encounter an unknown type, the best we can do is to copy the // envelope header (which includes the num_bytes and num_handles), and // copy the envelope's data. While it's possible that transformation was // needed, since we do not have the type, we cannot perform it. const auto status_copy_hdr = src_dst->Copy(position, sizeof(fidl_envelope_t)); if (status_copy_hdr != ZX_OK) { return TRANSFORMER_FAIL(status_copy_hdr, position, "unable to copy envelope header (unknown type)"); } const auto data_position = Position{position.src_out_of_line_offset, position.src_out_of_line_offset + src_envelope->num_bytes, position.dst_out_of_line_offset, position.dst_out_of_line_offset + src_envelope->num_bytes}; const auto status_copy_data = src_dst->Copy(data_position, src_envelope->num_bytes); if (status_copy_data != ZX_OK) { return TRANSFORMER_FAIL(status_copy_data, data_position, "unable to copy envelope data (unknown type)"); } out_traversal_result->src_out_of_line_size += src_envelope->num_bytes; out_traversal_result->dst_out_of_line_size += src_envelope->num_bytes; out_traversal_result->handle_count += src_envelope->num_handles; return ZX_OK; } const uint32_t src_contents_inline_size = [&] { if (!type) { // The envelope contents are either a primitive or an array of primitives, // because |type| is nullptr. There's no size information // available for the type in the coding tables, but since the data is a // primitive or array of primitives, there can never be any out-of-line // data, so it's safe to use the envelope's num_bytes to determine the // content's inline size. return src_envelope->num_bytes; } // TODO(apang): Add test to verify that we should _not_ FIDL_ALIGN below. return InlineSize(type, From(), position); }(); const uint32_t dst_contents_inline_size = FIDL_ALIGN(AltInlineSize(type, position)); Position data_position = Position{position.src_out_of_line_offset, position.src_out_of_line_offset + src_contents_inline_size, position.dst_out_of_line_offset, position.dst_out_of_line_offset + dst_contents_inline_size}; TraversalResult contents_traversal_result; zx_status_t result = Transform(type, data_position, dst_contents_inline_size, &contents_traversal_result); if (result != ZX_OK) { return result; } const uint32_t src_contents_size = FIDL_ALIGN(src_contents_inline_size) + contents_traversal_result.src_out_of_line_size; const uint32_t dst_contents_size = dst_contents_inline_size + contents_traversal_result.dst_out_of_line_size; fidl_envelope_t dst_envelope = *src_envelope; dst_envelope.num_bytes = dst_contents_size; const auto status_write = src_dst->Write(position, dst_envelope); if (status_write != ZX_OK) { return TRANSFORMER_FAIL(status_write, position, "unable to write envelope"); } out_traversal_result->src_out_of_line_size += src_contents_size; out_traversal_result->dst_out_of_line_size += dst_contents_size; out_traversal_result->handle_count += src_envelope->num_handles; return ZX_OK; } zx_status_t TransformXUnion(const FidlCodedXUnion& coded_xunion, const Position& position, TraversalResult* out_traversal_result) { auto xunion = src_dst->Read<const fidl_xunion_t>(position); if (!xunion) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "xunion missing"); } const auto status_copy_xunion_hdr = src_dst->Copy(position, sizeof(fidl_xunion_t)); if (status_copy_xunion_hdr != ZX_OK) { return status_copy_xunion_hdr; } const FidlXUnionField* field = nullptr; for (uint32_t i = 0; i < coded_xunion.field_count; i++) { const FidlXUnionField* candidate_field = coded_xunion.fields + i; if (candidate_field->ordinal == xunion->tag) { field = candidate_field; break; } } const Position envelope_position = { position.src_inline_offset + static_cast<uint32_t>(offsetof(fidl_xunion_t, envelope)), position.src_out_of_line_offset, position.dst_inline_offset + static_cast<uint32_t>(offsetof(fidl_xunion_t, envelope)), position.dst_out_of_line_offset, }; return TransformEnvelope(field != nullptr, field ? field->type : nullptr, envelope_position, out_traversal_result); } zx_status_t TransformTable(const FidlCodedTable& coded_table, const Position& position, TraversalResult* out_traversal_result) { auto table = src_dst->Read<const fidl_table_t>(position); if (!table) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "table header missing"); } const auto status_copy_table_hdr = src_dst->Copy(position, sizeof(fidl_table_t)); if (status_copy_table_hdr != ZX_OK) { return TRANSFORMER_FAIL(status_copy_table_hdr, position, "unable to copy table header"); } const uint32_t envelopes_vector_size = static_cast<uint32_t>(table->envelopes.count * sizeof(fidl_envelope_t)); out_traversal_result->src_out_of_line_size += envelopes_vector_size; out_traversal_result->dst_out_of_line_size += envelopes_vector_size; auto current_envelope_position = Position{ position.src_out_of_line_offset, position.src_out_of_line_offset + envelopes_vector_size, position.dst_out_of_line_offset, position.dst_out_of_line_offset + envelopes_vector_size, }; const auto max_field_index = coded_table.field_count - 1; for (uint32_t ordinal = 1, field_index = 0; ordinal <= table->envelopes.count; ordinal++) { const FidlTableField& field = coded_table.fields[field_index]; const bool known_field = (ordinal == field.ordinal); if (known_field) { if (field_index < max_field_index) field_index++; } TraversalResult envelope_traversal_result; zx_status_t status = TransformEnvelope(known_field, known_field ? field.type : nullptr, current_envelope_position, &envelope_traversal_result); if (status != ZX_OK) { return status; } current_envelope_position.src_inline_offset += static_cast<uint32_t>(sizeof(fidl_envelope_t)); current_envelope_position.dst_inline_offset += static_cast<uint32_t>(sizeof(fidl_envelope_t)); current_envelope_position.src_out_of_line_offset += envelope_traversal_result.src_out_of_line_size; current_envelope_position.dst_out_of_line_offset += envelope_traversal_result.dst_out_of_line_size; *out_traversal_result += envelope_traversal_result; } return ZX_OK; } zx_status_t TransformArray(const FidlCodedArrayNew& src_coded_array, const FidlCodedArrayNew& dst_coded_array, const Position& position, uint32_t dst_array_size, TraversalResult* out_traversal_result) { TRANSFORMER_ASSERT(src_coded_array.element_count == dst_coded_array.element_count, position); // Fast path for elements without coding tables (e.g. strings). if (!src_coded_array.element) { return src_dst->Copy(position, dst_array_size); } // Slow path otherwise. auto current_element_position = position; for (uint32_t i = 0; i < src_coded_array.element_count; i++) { TraversalResult element_traversal_result; const zx_status_t status = Transform(src_coded_array.element, current_element_position, dst_coded_array.element_size, &element_traversal_result); if (status != ZX_OK) { return status; } // Pad end of an element. auto padding_position = current_element_position.IncreaseSrcInlineOffset(src_coded_array.element_size) .IncreaseDstInlineOffset(dst_coded_array.element_size); const auto status_pad = src_dst->Pad(padding_position, dst_coded_array.element_padding); if (status_pad != ZX_OK) { return TRANSFORMER_FAIL(status_pad, padding_position, "unable to pad array element"); } current_element_position = padding_position.IncreaseSrcInlineOffset(src_coded_array.element_padding) .IncreaseDstInlineOffset(dst_coded_array.element_padding) .IncreaseSrcOutOfLineOffset(element_traversal_result.src_out_of_line_size) .IncreaseDstOutOfLineOffset(element_traversal_result.dst_out_of_line_size); *out_traversal_result += element_traversal_result; } // Pad end of elements. uint32_t padding = dst_array_size + position.dst_inline_offset - current_element_position.dst_inline_offset; const auto status_pad = src_dst->Pad(current_element_position, padding); if (status_pad != ZX_OK) { return TRANSFORMER_FAIL(status_pad, current_element_position, "unable to pad end of array"); } return ZX_OK; } zx_status_t TransformUnionPointerToOptionalXUnion(const FidlCodedUnion& src_coded_union, const FidlCodedXUnion& dst_coded_xunion, const Position& position, TraversalResult* out_traversal_result) { auto presence = src_dst->Read<uint64_t>(position); if (!presence) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "union pointer missing"); } switch (*presence) { case FIDL_ALLOC_ABSENT: { fidl_xunion_t absent = {}; const auto status = src_dst->Write(position, absent); if (status != ZX_OK) { return TRANSFORMER_FAIL(status, position, "unable to write union pointer absense"); } return ZX_OK; } case FIDL_ALLOC_PRESENT: // Ok break; default: return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "union pointer invalid"); } uint32_t src_aligned_size = FIDL_ALIGN(src_coded_union.size); const auto union_position = Position{ position.src_out_of_line_offset, position.src_out_of_line_offset + src_aligned_size, position.dst_inline_offset, position.dst_out_of_line_offset, }; out_traversal_result->src_out_of_line_size += src_aligned_size; return TransformUnionToXUnion(src_coded_union, dst_coded_xunion, union_position, 0 /* unused: xunions are FIDL_ALIGNed */, out_traversal_result); } zx_status_t TransformUnionToXUnion(const FidlCodedUnion& src_coded_union, const FidlCodedXUnion& dst_coded_xunion, const Position& position, uint32_t /* unused: dst_size */, TraversalResult* out_traversal_result) { TRANSFORMER_ASSERT(src_coded_union.field_count == dst_coded_xunion.field_count, position); // Read: union tag. const auto union_tag_ptr = src_dst->Read<const fidl_union_tag_t>(position, src_coded_union.size); if (!union_tag_ptr) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "union tag missing"); } const auto union_tag = *union_tag_ptr; // Retrieve: union field/variant. if (union_tag >= src_coded_union.field_count) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "invalid union tag"); } const FidlUnionField& src_field = src_coded_union.fields[union_tag]; const FidlXUnionField& dst_field = dst_coded_xunion.fields[union_tag]; // Write: xunion tag & envelope. const uint32_t dst_inline_field_size = [&] { if (src_field.type) { return AltInlineSize(src_field.type, position); } else { return src_coded_union.size - src_coded_union.data_offset - src_field.padding; } }(); // Transform: static-union field to xunion field. auto field_position = Position{ position.src_inline_offset + src_coded_union.data_offset, position.src_out_of_line_offset, position.dst_out_of_line_offset, position.dst_out_of_line_offset + FIDL_ALIGN(dst_inline_field_size), }; TraversalResult field_traversal_result; zx_status_t status = Transform(src_field.type, field_position, dst_inline_field_size, &field_traversal_result); if (status != ZX_OK) { return status; } // Pad field (if needed). const uint32_t dst_field_size = dst_inline_field_size + field_traversal_result.dst_out_of_line_size; const uint32_t dst_padding = FIDL_ALIGN(dst_field_size) - dst_field_size; const auto status_pad_field = src_dst->Pad(field_position.IncreaseDstInlineOffset(dst_field_size), dst_padding); if (status_pad_field != ZX_OK) { return TRANSFORMER_FAIL(status_pad_field, field_position, "unable to pad union-as-xunion variant"); } // Write envelope header. fidl_xunion_t xunion; xunion.tag = dst_field.ordinal; xunion.envelope.num_bytes = FIDL_ALIGN(dst_field_size); xunion.envelope.num_handles = field_traversal_result.handle_count; xunion.envelope.presence = FIDL_ALLOC_PRESENT; const auto status_write_xunion = src_dst->Write(position, xunion); if (status_write_xunion != ZX_OK) { return TRANSFORMER_FAIL(status_write_xunion, position, "unable to write union-as-xunion header"); } out_traversal_result->src_out_of_line_size += field_traversal_result.src_out_of_line_size; out_traversal_result->dst_out_of_line_size += FIDL_ALIGN(dst_field_size); out_traversal_result->handle_count += field_traversal_result.handle_count; return ZX_OK; } zx_status_t TransformOptionalXUnionToUnionPointer(const FidlCodedXUnion& src_coded_xunion, const FidlCodedUnion& dst_coded_union, const Position& position, TraversalResult* out_traversal_result) { auto src_xunion = src_dst->Read<const fidl_xunion_t>(position); if (!src_xunion) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "union-as-xunion missing"); } switch (src_xunion->envelope.presence) { case FIDL_ALLOC_ABSENT: case FIDL_ALLOC_PRESENT: { const auto status = src_dst->Write(position, src_xunion->envelope.presence); if (status != ZX_OK) { return TRANSFORMER_FAIL(status, position, "unable to write union pointer absence"); } if (src_xunion->envelope.presence == FIDL_ALLOC_ABSENT) { return ZX_OK; } break; } default: return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "union-as-xunion envelope presence invalid"); } const uint32_t dst_aligned_size = FIDL_ALIGN(dst_coded_union.size); const auto union_position = Position{ position.src_inline_offset, position.src_out_of_line_offset, position.dst_out_of_line_offset, position.dst_out_of_line_offset + dst_aligned_size, }; out_traversal_result->dst_out_of_line_size += dst_aligned_size; return TransformXUnionToUnion(src_coded_xunion, dst_coded_union, union_position, FIDL_ALIGN(dst_coded_union.size), out_traversal_result); } zx_status_t TransformXUnionToUnion(const FidlCodedXUnion& src_coded_xunion, const FidlCodedUnion& dst_coded_union, const Position& position, uint32_t dst_size, TraversalResult* out_traversal_result) { TRANSFORMER_ASSERT(src_coded_xunion.field_count == dst_coded_union.field_count, position); // Read: extensible-union ordinal. const auto src_xunion = src_dst->Read<const fidl_xunion_t>(position); if (!src_xunion) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "union-as-xunion missing"); } switch (src_xunion->envelope.presence) { case FIDL_ALLOC_PRESENT: // OK break; case FIDL_ALLOC_ABSENT: return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "union-as-xunion envelope is invalid FIDL_ALLOC_ABSENT"); default: return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "union-as-xunion envelope presence invalid"); } // Retrieve: flexible-union field (or variant). bool src_field_found = false; uint32_t src_field_index = 0; const FidlXUnionField* src_field = nullptr; for (/* src_field_index needed after the loop */; src_field_index < src_coded_xunion.field_count; src_field_index++) { const FidlXUnionField* candidate_src_field = &src_coded_xunion.fields[src_field_index]; if (candidate_src_field->ordinal == src_xunion->tag) { src_field_found = true; src_field = candidate_src_field; break; } } if (!src_field_found) { return TRANSFORMER_FAIL(ZX_ERR_BAD_STATE, position, "ordinal has no corresponding variant"); } const FidlUnionField& dst_field = dst_coded_union.fields[src_field_index]; // Write: static-union tag, and pad (if needed). switch (dst_coded_union.data_offset) { case 4: { const auto status = src_dst->Write(position, src_field_index); if (status != ZX_OK) { return TRANSFORMER_FAIL(status, position, "unable to write union tag"); } break; } case 8: { const auto status = src_dst->Write(position, static_cast<uint64_t>(src_field_index)); if (status != ZX_OK) { return TRANSFORMER_FAIL(status, position, "unable to write union tag"); } break; } default: TRANSFORMER_ASSERT(false && "static-union data offset can only be 4 or 8", position); } // TODO(apang): The code below also in TransformEnvelope(). We should // refactor this method to call TransformEnvelope() if possible, instead of // re-implementing parts of it here. const uint32_t src_field_inline_size = [&] { if (!src_field->type) { // src_field's type is either a primitive or an array of primitives, // because src_field->type is nullptr. There's no size information // available for the field in the coding tables, but since the data is a // primitive or array of primitives, there can never be any out-of-line // data, so it's safe to use the envelope's num_bytes to determine the // field's inline size. return src_xunion->envelope.num_bytes; } // TODO(apang): Add test to verify that we _should_ FIDL_ALIGN below. return FIDL_ALIGN(InlineSize(src_field->type, From(), position)); }(); // Transform: xunion field to static-union field (or variant). auto field_position = Position{ position.src_out_of_line_offset, position.src_out_of_line_offset + src_field_inline_size, position.dst_inline_offset + dst_coded_union.data_offset, position.dst_out_of_line_offset, }; uint32_t dst_field_unpadded_size = dst_coded_union.size - dst_coded_union.data_offset - dst_field.padding; zx_status_t status = Transform(src_field->type, field_position, dst_field_unpadded_size, out_traversal_result); if (status != ZX_OK) { return status; } // Pad after static-union data. auto field_padding_position = field_position.IncreaseDstInlineOffset(dst_field_unpadded_size); const auto dst_padding = (dst_size - dst_coded_union.size) + dst_field.padding; const auto status_pad_field = src_dst->Pad(field_padding_position, dst_padding); if (status_pad_field != ZX_OK) { return TRANSFORMER_FAIL(status_pad_field, field_padding_position, "unable to pad union variant"); } out_traversal_result->src_out_of_line_size += src_field_inline_size; return ZX_OK; } virtual WireFormat From() const = 0; virtual WireFormat To() const = 0; inline zx_status_t Fail(zx_status_t status, const Position& position, const int line_number, const char* error_msg) { debug_info_->RecordFailure(line_number, error_msg, position); return status; } SrcDst* src_dst; DebugInfo* const debug_info_; private: const fidl_type_t* top_level_src_type_; }; // TODO(apang): Mark everything override // TODO(apang): We can remove the V1ToOld & OldToV1 classes since they only have From() and To() // methods now, which can be passed into the constructor of TransformerBase. class V1ToOld final : public TransformerBase { public: V1ToOld(SrcDst* src_dst, const fidl_type_t* top_level_src_type, DebugInfo* debug_info) : TransformerBase(src_dst, top_level_src_type, debug_info) {} WireFormat From() const { return WireFormat::kV1; } WireFormat To() const { return WireFormat::kOld; } }; class OldToV1 final : public TransformerBase { public: OldToV1(SrcDst* src_dst, const fidl_type_t* top_level_src_type, DebugInfo* debug_info) : TransformerBase(src_dst, top_level_src_type, debug_info) {} private: // TODO(apang): Could CRTP this. WireFormat From() const { return WireFormat::kOld; } WireFormat To() const { return WireFormat::kV1; } }; } // namespace zx_status_t fidl_transform(fidl_transformation_t transformation, const fidl_type_t* src_type, const uint8_t* src_bytes, uint32_t src_num_bytes, uint8_t* dst_bytes, uint32_t dst_num_bytes_capacity, uint32_t* out_dst_num_bytes, const char** out_error_msg) { if (!src_type || !src_bytes || !dst_bytes || !out_dst_num_bytes || !FidlIsAligned(src_bytes) || !FidlIsAligned(dst_bytes)) { return ZX_ERR_INVALID_ARGS; } SrcDst src_dst(src_bytes, src_num_bytes, dst_bytes, dst_num_bytes_capacity); DebugInfo debug_info(transformation, src_type, src_dst, out_error_msg); const zx_status_t status = [&] { switch (transformation) { case FIDL_TRANSFORMATION_NONE: { const auto start = Position{ 0, UINT16_MAX, /* unused: src_out_of_line_offset */ 0, UINT16_MAX, /* unused: dst_out_of_line_offset */ }; return src_dst.Copy(start, src_num_bytes); } case FIDL_TRANSFORMATION_V1_TO_OLD: return V1ToOld(&src_dst, src_type, &debug_info).TransformTopLevelStruct(); case FIDL_TRANSFORMATION_OLD_TO_V1: return OldToV1(&src_dst, src_type, &debug_info).TransformTopLevelStruct(); default: debug_info.RecordFailure(__LINE__, "unsupported transformation"); return ZX_ERR_INVALID_ARGS; } }(); if (status != ZX_OK) { return status; } if (FIDL_ALIGN(src_dst.src_max_offset_read()) != src_num_bytes) { debug_info.RecordFailure(__LINE__, "did not read all provided bytes during transformation"); return ZX_ERR_INVALID_ARGS; } *out_dst_num_bytes = src_dst.dst_max_offset_written(); return ZX_OK; } #pragma GCC diagnostic pop // "-Wimplicit-fallthrough"
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r15 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_WT_ht+0x16d8a, %r9 xor %rsi, %rsi mov (%r9), %r15d nop nop nop nop nop lfence lea addresses_UC_ht+0x14c50, %rsi lea addresses_WC_ht+0x1db3c, %rdi add $23931, %r15 mov $70, %rcx rep movsl nop nop nop nop nop add %rdi, %rdi lea addresses_UC_ht+0x1d3a2, %rbx nop dec %r11 mov $0x6162636465666768, %rcx movq %rcx, (%rbx) nop nop nop nop sub $57548, %rbx lea addresses_WC_ht+0x15d8a, %rbx nop nop nop nop nop cmp $59070, %rdi mov (%rbx), %ecx nop nop nop inc %rbx lea addresses_normal_ht+0xa38a, %r15 nop nop nop and %rcx, %rcx movb $0x61, (%r15) nop nop nop add %r9, %r9 lea addresses_A_ht+0x898a, %r11 nop nop nop cmp $23883, %r15 movb $0x61, (%r11) nop nop nop nop inc %r11 lea addresses_A_ht+0x12ca2, %rsi lea addresses_D_ht+0x1d7a8, %rdi nop nop nop nop nop cmp $35589, %r12 mov $115, %rcx rep movsb nop xor $26648, %rsi lea addresses_D_ht+0xda7a, %rdi and $8980, %rcx vmovups (%rdi), %ymm1 vextracti128 $1, %ymm1, %xmm1 vpextrq $0, %xmm1, %rbx nop nop nop nop and %r9, %r9 lea addresses_WT_ht+0xa45e, %r11 nop nop nop nop nop add $44994, %rdi movw $0x6162, (%r11) sub %r11, %r11 lea addresses_WC_ht+0x1a58a, %rsi lea addresses_normal_ht+0x1610a, %rdi clflush (%rsi) clflush (%rdi) nop nop nop xor %r15, %r15 mov $18, %rcx rep movsb nop nop nop inc %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r15 push %rbx push %rcx push %rdi push %rsi // REPMOV lea addresses_PSE+0x6082, %rsi lea addresses_UC+0x1158a, %rdi nop nop sub $60079, %r13 mov $97, %rcx rep movsl nop nop nop nop dec %r14 // Store lea addresses_WT+0x1795a, %r13 nop nop nop sub %rdi, %rdi mov $0x5152535455565758, %rsi movq %rsi, %xmm1 vmovups %ymm1, (%r13) nop nop nop nop nop xor $51170, %r15 // Store lea addresses_WT+0xc392, %rdi nop nop inc %rbx mov $0x5152535455565758, %rsi movq %rsi, (%rdi) nop nop cmp $49959, %rcx // Faulty Load lea addresses_D+0x1758a, %r14 nop nop nop nop nop xor %r15, %r15 mov (%r14), %rdi lea oracles, %rsi and $0xff, %rdi shlq $12, %rdi mov (%rsi,%rdi,1), %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %r15 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_PSE', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC', 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 2}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 3}} [Faulty Load] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 11}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': True, 'size': 8, 'NT': False, 'same': False, 'congruent': 2}} {'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 11}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': True, 'size': 1, 'NT': False, 'same': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 10}} {'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 3}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 2}} {'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
# Zeynep Cankara -- 20/02/2019 # isPalindrome.asm -- Takes a string as user input checks isPalindrome # Registers used: ## Text Section ## .globl __start .text __start: # prompt the task on screen li $v0, 4 la $a0, task syscall # ask user enter the string li $v0, 4 la $a0, prompt syscall # read the string li $v0,8 # read str la $a0, strBuffer #load byte space into address li $a1, 20 # allot the byte space for strings sw $a0, strBuffer # store string in the buffer syscall # $t0 points to the address of the string la $a0, strBuffer jal size # obtain size of the string move $a0, $v0 # save the last character adress jal isPalindrome # test ispalindrome function move $s0, $v0 # return result isPalindrome li $v0, 4 la $a0, isPalindromeMsg syscall # test ispalindrome function move $a0, $s0 li $v0, 1 syscall li $v0,10 # exit program syscall ## Function for counting number of characters in the string ## reg used: v0: returns the address of the last char in the string size: # $a0 have the address of the string move $t0, $a0 # store string in $t0 reg addi $t2, $0, 0 # cnt = 0, counter for characters in the string startCnt: lbu $t3, 0($t0) # load current character in t3 beq $t3, $0, done # finish when encounter a NULL character addi $t2, $t2, 1 # cnt += 1 addi $t0, $t0, 1 # go to next char j startCnt done: subi $t2, $t2, 1 # exclude enter character sw $t2, strSize # store the size of the string subi $t0, $t0, 2 # go back 2 chars (1 for ENTER 1 for 00(end of string)) move $v0, $t0 # return the sadress of the last char jr $ra # goto the next instruction ## Function Takes the last char address of the string (a0) loads adress of the first char from the buffer (strBuffer) ## Compares and return 1 if the string is palindrome 0 otherwise ## reg used: a0,t0, t1, v0 isPalindrome: la $t0, strBuffer # address of the first char move, $t1, $a0 # adress of the last char next: lb $t3, 0($t0) # load the first character lb $t4, 0($t1) # load the last character bne $t3, $t4, false # characters not equal return 0 ble $t1, $t0, true # address of last char <= adress of first char return 1 addi $t0, $t0, 1 subi $t1, $t1, 1 j next false: li $v0, 0 # return 0 j finish true: li $v0, 1 # return 1 finish: jr $ra # goto the next instruction ## Data Section ## .data strBuffer: .space 20 # 1 char (1 byte), string can have max 20 letters task: .asciiz "Program checks whether string is palindrome or not \n" prompt: .asciiz "Please enter the string: \n" strSize: .word 0 # number of characters in string isPalindromeMsg: .asciiz "String is palindrome if result is 1, 0 otherwise \n"
; A022099: Fibonacci sequence beginning 1, 9. ; 1,9,10,19,29,48,77,125,202,327,529,856,1385,2241,3626,5867,9493,15360,24853,40213,65066,105279,170345,275624,445969,721593,1167562,1889155,3056717,4945872,8002589,12948461,20951050,33899511,54850561,88750072,143600633,232350705 mov $1,4 mov $3,36 lpb $0 sub $0,1 mov $2,$1 mov $1,$3 add $3,$2 lpe div $1,4 mov $0,$1
;****************************************************************************** ;* x86-SIMD-optimized IDCT for prores ;* this is identical to "simple" IDCT written by Michael Niedermayer ;* except for the clip range ;* ;* Copyright (c) 2011 Ronald S. Bultje <rsbultje@gmail.com> ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* FFmpeg is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser General Public ;* License along with FFmpeg; if not, write to the Free Software ;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "x86inc.asm" %include "x86util.asm" %define W1sh2 22725 ; W1 = 90901 = 22725<<2 + 1 %define W2sh2 21407 ; W2 = 85627 = 21407<<2 - 1 %define W3sh2 19265 ; W3 = 77062 = 19265<<2 + 2 %define W4sh2 16384 ; W4 = 65535 = 16384<<2 - 1 %define W5sh2 12873 ; W5 = 51491 = 12873<<2 - 1 %define W6sh2 8867 ; W6 = 35468 = 8867<<2 %define W7sh2 4520 ; W7 = 18081 = 4520<<2 + 1 %ifdef ARCH_X86_64 SECTION_RODATA w4_plus_w2: times 4 dw W4sh2, +W2sh2 w4_min_w2: times 4 dw W4sh2, -W2sh2 w4_plus_w6: times 4 dw W4sh2, +W6sh2 w4_min_w6: times 4 dw W4sh2, -W6sh2 w1_plus_w3: times 4 dw W1sh2, +W3sh2 w3_min_w1: times 4 dw W3sh2, -W1sh2 w7_plus_w3: times 4 dw W7sh2, +W3sh2 w3_min_w7: times 4 dw W3sh2, -W7sh2 w1_plus_w5: times 4 dw W1sh2, +W5sh2 w5_min_w1: times 4 dw W5sh2, -W1sh2 w5_plus_w7: times 4 dw W5sh2, +W7sh2 w7_min_w5: times 4 dw W7sh2, -W5sh2 pw_88: times 8 dw 0x2008 cextern pw_1 cextern pw_4 cextern pw_512 cextern pw_1019 section .text align=16 ; interleave data while maintaining source ; %1=type, %2=dstlo, %3=dsthi, %4=src, %5=interleave %macro SBUTTERFLY3 5 punpckl%1 m%2, m%4, m%5 punpckh%1 m%3, m%4, m%5 %endmacro ; %1/%2=src1/dst1, %3/%4=dst2, %5/%6=src2, %7=shift ; action: %3/%4 = %1/%2 - %5/%6; %1/%2 += %5/%6 ; %1/%2/%3/%4 >>= %7; dword -> word (in %1/%3) %macro SUMSUB_SHPK 7 psubd %3, %1, %5 ; { a0 - b0 }[0-3] psubd %4, %2, %6 ; { a0 - b0 }[4-7] paddd %1, %5 ; { a0 + b0 }[0-3] paddd %2, %6 ; { a0 + b0 }[4-7] psrad %1, %7 psrad %2, %7 psrad %3, %7 psrad %4, %7 packssdw %1, %2 ; row[0] packssdw %3, %4 ; row[7] %endmacro ; %1 = row or col (for rounding variable) ; %2 = number of bits to shift at the end ; %3 = optimization %macro IDCT_1D 3 ; a0 = (W4 * row[0]) + (1 << (15 - 1)); ; a1 = a0; ; a2 = a0; ; a3 = a0; ; a0 += W2 * row[2]; ; a1 += W6 * row[2]; ; a2 -= W6 * row[2]; ; a3 -= W2 * row[2]; %ifidn %1, col paddw m10,[pw_88] %endif %ifidn %1, row paddw m10,[pw_1] %endif SBUTTERFLY3 wd, 0, 1, 10, 8 ; { row[0], row[2] }[0-3]/[4-7] pmaddwd m2, m0, [w4_plus_w6] pmaddwd m3, m1, [w4_plus_w6] pmaddwd m4, m0, [w4_min_w6] pmaddwd m5, m1, [w4_min_w6] pmaddwd m6, m0, [w4_min_w2] pmaddwd m7, m1, [w4_min_w2] pmaddwd m0, [w4_plus_w2] pmaddwd m1, [w4_plus_w2] ; a0: -1*row[0]-1*row[2] ; a1: -1*row[0] ; a2: -1*row[0] ; a3: -1*row[0]+1*row[2] ; a0 += W4*row[4] + W6*row[6]; i.e. -1*row[4] ; a1 -= W4*row[4] + W2*row[6]; i.e. -1*row[4]-1*row[6] ; a2 -= W4*row[4] - W2*row[6]; i.e. -1*row[4]+1*row[6] ; a3 += W4*row[4] - W6*row[6]; i.e. -1*row[4] SBUTTERFLY3 wd, 8, 9, 13, 12 ; { row[4], row[6] }[0-3]/[4-7] pmaddwd m10, m8, [w4_plus_w6] pmaddwd m11, m9, [w4_plus_w6] paddd m0, m10 ; a0[0-3] paddd m1, m11 ; a0[4-7] pmaddwd m10, m8, [w4_min_w6] pmaddwd m11, m9, [w4_min_w6] paddd m6, m10 ; a3[0-3] paddd m7, m11 ; a3[4-7] pmaddwd m10, m8, [w4_min_w2] pmaddwd m11, m9, [w4_min_w2] pmaddwd m8, [w4_plus_w2] pmaddwd m9, [w4_plus_w2] psubd m4, m10 ; a2[0-3] intermediate psubd m5, m11 ; a2[4-7] intermediate psubd m2, m8 ; a1[0-3] intermediate psubd m3, m9 ; a1[4-7] intermediate ; load/store mova [r2+ 0], m0 mova [r2+ 32], m2 mova [r2+ 64], m4 mova [r2+ 96], m6 mova m10,[r2+ 16] ; { row[1] }[0-7] mova m8, [r2+ 48] ; { row[3] }[0-7] mova m13,[r2+ 80] ; { row[5] }[0-7] mova m14,[r2+112] ; { row[7] }[0-7] mova [r2+ 16], m1 mova [r2+ 48], m3 mova [r2+ 80], m5 mova [r2+112], m7 %ifidn %1, row pmullw m10,[r3+ 16] pmullw m8, [r3+ 48] pmullw m13,[r3+ 80] pmullw m14,[r3+112] %endif ; b0 = MUL(W1, row[1]); ; MAC(b0, W3, row[3]); ; b1 = MUL(W3, row[1]); ; MAC(b1, -W7, row[3]); ; b2 = MUL(W5, row[1]); ; MAC(b2, -W1, row[3]); ; b3 = MUL(W7, row[1]); ; MAC(b3, -W5, row[3]); SBUTTERFLY3 wd, 0, 1, 10, 8 ; { row[1], row[3] }[0-3]/[4-7] pmaddwd m2, m0, [w3_min_w7] pmaddwd m3, m1, [w3_min_w7] pmaddwd m4, m0, [w5_min_w1] pmaddwd m5, m1, [w5_min_w1] pmaddwd m6, m0, [w7_min_w5] pmaddwd m7, m1, [w7_min_w5] pmaddwd m0, [w1_plus_w3] pmaddwd m1, [w1_plus_w3] ; b0: +1*row[1]+2*row[3] ; b1: +2*row[1]-1*row[3] ; b2: -1*row[1]-1*row[3] ; b3: +1*row[1]+1*row[3] ; MAC(b0, W5, row[5]); ; MAC(b0, W7, row[7]); ; MAC(b1, -W1, row[5]); ; MAC(b1, -W5, row[7]); ; MAC(b2, W7, row[5]); ; MAC(b2, W3, row[7]); ; MAC(b3, W3, row[5]); ; MAC(b3, -W1, row[7]); SBUTTERFLY3 wd, 8, 9, 13, 14 ; { row[5], row[7] }[0-3]/[4-7] ; b0: -1*row[5]+1*row[7] ; b1: -1*row[5]+1*row[7] ; b2: +1*row[5]+2*row[7] ; b3: +2*row[5]-1*row[7] pmaddwd m10, m8, [w1_plus_w5] pmaddwd m11, m9, [w1_plus_w5] pmaddwd m12, m8, [w5_plus_w7] pmaddwd m13, m9, [w5_plus_w7] psubd m2, m10 ; b1[0-3] psubd m3, m11 ; b1[4-7] paddd m0, m12 ; b0[0-3] paddd m1, m13 ; b0[4-7] pmaddwd m12, m8, [w7_plus_w3] pmaddwd m13, m9, [w7_plus_w3] pmaddwd m8, [w3_min_w1] pmaddwd m9, [w3_min_w1] paddd m4, m12 ; b2[0-3] paddd m5, m13 ; b2[4-7] paddd m6, m8 ; b3[0-3] paddd m7, m9 ; b3[4-7] ; row[0] = (a0 + b0) >> 15; ; row[7] = (a0 - b0) >> 15; ; row[1] = (a1 + b1) >> 15; ; row[6] = (a1 - b1) >> 15; ; row[2] = (a2 + b2) >> 15; ; row[5] = (a2 - b2) >> 15; ; row[3] = (a3 + b3) >> 15; ; row[4] = (a3 - b3) >> 15; mova m8, [r2+ 0] ; a0[0-3] mova m9, [r2+16] ; a0[4-7] SUMSUB_SHPK m8, m9, m10, m11, m0, m1, %2 mova m0, [r2+32] ; a1[0-3] mova m1, [r2+48] ; a1[4-7] SUMSUB_SHPK m0, m1, m9, m11, m2, m3, %2 mova m1, [r2+64] ; a2[0-3] mova m2, [r2+80] ; a2[4-7] SUMSUB_SHPK m1, m2, m11, m3, m4, m5, %2 mova m2, [r2+96] ; a3[0-3] mova m3, [r2+112] ; a3[4-7] SUMSUB_SHPK m2, m3, m4, m5, m6, m7, %2 %endmacro ; void prores_idct_put_10_<opt>(uint8_t *pixels, int stride, ; DCTELEM *block, const int16_t *qmat); %macro idct_put_fn 2 cglobal prores_idct_put_10_%1, 4, 4, %2 movsxd r1, r1d pxor m15, m15 ; zero ; for (i = 0; i < 8; i++) ; idctRowCondDC(block + i*8); mova m10,[r2+ 0] ; { row[0] }[0-7] mova m8, [r2+32] ; { row[2] }[0-7] mova m13,[r2+64] ; { row[4] }[0-7] mova m12,[r2+96] ; { row[6] }[0-7] pmullw m10,[r3+ 0] pmullw m8, [r3+32] pmullw m13,[r3+64] pmullw m12,[r3+96] IDCT_1D row, 15, %1 ; transpose for second part of IDCT TRANSPOSE8x8W 8, 0, 1, 2, 4, 11, 9, 10, 3 mova [r2+ 16], m0 mova [r2+ 48], m2 mova [r2+ 80], m11 mova [r2+112], m10 SWAP 8, 10 SWAP 1, 8 SWAP 4, 13 SWAP 9, 12 ; for (i = 0; i < 8; i++) ; idctSparseColAdd(dest + i, line_size, block + i); IDCT_1D col, 18, %1 ; clip/store mova m3, [pw_4] mova m5, [pw_1019] pmaxsw m8, m3 pmaxsw m0, m3 pmaxsw m1, m3 pmaxsw m2, m3 pmaxsw m4, m3 pmaxsw m11, m3 pmaxsw m9, m3 pmaxsw m10, m3 pminsw m8, m5 pminsw m0, m5 pminsw m1, m5 pminsw m2, m5 pminsw m4, m5 pminsw m11, m5 pminsw m9, m5 pminsw m10, m5 lea r2, [r1*3] mova [r0 ], m8 mova [r0+r1 ], m0 mova [r0+r1*2], m1 mova [r0+r2 ], m2 lea r0, [r0+r1*4] mova [r0 ], m4 mova [r0+r1 ], m11 mova [r0+r1*2], m9 mova [r0+r2 ], m10 RET %endmacro INIT_XMM idct_put_fn sse2, 16 INIT_XMM idct_put_fn sse4, 16 %ifdef HAVE_AVX INIT_AVX idct_put_fn avx, 16 %endif %endif
; Ellipse Workstation 1100 (fictitious computer) ; Ellipse DOS execution/task functions ; ; Copyright (c) 2020 Sampo Hippeläinen (hisahi) ; ; 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. ; ; Written for the WLA-DX assembler ; DOSLOADEXEC: ACC8 LDA DOSTMP7.B STA DOSIOBANK.B ACC16 LDY #$1E LDA (DOSTMP5.B),Y STA DOSTMP8.B LDX #$0100 - PHX LDY DOSTMP8.B JSR DOSLOADCHUNK.W BCS @ERRC LDX DOSTMP8.B JSR DOSNEXTCHUNK.W BCS @ERRC STX DOSTMP8.B CPX #$FFFF BEQ + PLA CLC ADC #$0400 TAX BRA - + PLA ACC8 LDA #$80 STA DOSIOBANK.B ACC16 CLC LDA #0 RTS @ERRC PLX @ERR PHA ACC8 LDA #$80 STA DOSIOBANK.B ACC16 PLA SEC RTS DOSLAUNCH: ; $38 = launch program PHX PHY JSR DOSCOPYBXSTRBUFUC.W AXY16 LDA 1,S TAX LDA 3,S TAY ENTERDOSRAM JSR DOSPAGEINDIR.W JSR DOSRESOLVEPATHFILE.W BCS @ERR JSR DOSALLOCRAMBANK_EXEC.W BCS @ERR STA DOSTMP7.B ACC16 LDA DOSNEXTFILEOFF.B CLC ADC #DIRCHUNKCACHE.W STA DOSTMP5.B LDY #$1A LDA (DOSTMP5.B),Y CMP #65280 BCC + LDA #DOS_ERR_EXEC_TOO_LARGE BRA @ERR + INY INY LDA (DOSTMP5.B),Y BEQ + LDA #DOS_ERR_EXEC_TOO_LARGE @ERR EXITDOSRAM PLY PLX SEC RTS + ; load executable into memory JSR DOSLOADEXEC.W BCS @ERR ; prepare executable header ; stack: X, Y, B, D LDA 4,S STA DOSTMP8.B ; copy command line from B:X LDA #$0081 STA DOSTMP6.B ACC8 PHB ; stack: X, Y, B, D, B LDA 4,S PHA PLB ACC16 LDY #0 LDA (DOSTMP8.B),Y STA DOSTMP3.B ACC8 LDY #0 - LDA (DOSTMP3.B),Y STA [DOSTMP6.B],Y BEQ + INY CPY #$7E BCC - LDA #0 STA [DOSTMP6.B],Y + ; store length of command line ACC16 DEC DOSTMP6.B ACC8 TYA LDY #0 STA [DOSTMP6.B],Y ACC16 ; copy environment pointer LDA #$0007 STA DOSTMP6.B INC DOSTMP8.B INC DOSTMP8.B LDA (DOSTMP8.B),Y BEQ ++ ; non-zero pointer, apply LDY #0 STA [DOSTMP6.B],Y ACC8 PHB PLA LDY #2 CMP #$81 BNE + DEC A + STA [DOSTMP6.B],Y BRA +++ ++ ; inherit from current process ; stack: ORIG_ADDR(24), DOSCALLEXIT(16), X, Y, B, D, B ACC8 ; load old program bank LDA 12,S PHA PLB LDY #0 LDA $0007.W STA [DOSTMP6.B],Y INY LDA $0008.W STA [DOSTMP6.B],Y INY LDA $0009.W STA [DOSTMP6.B],Y +++ ACC16 PLB ; stack: ORIG_ADDR(24), DOSCALLEXIT(16), X, Y, B, D ; initialize local process file list LDA #$0020 STA DOSTMP6.B LDA #$0000 LDY #30 - STA [DOSTMP6.B],Y DEY DEY BPL - ; initialize stdin, stdout, stderr LDY #0 LDA #$0001 STA [DOSTMP6.B],Y LDY #2 STA [DOSTMP6.B],Y LDY #4 STA [DOSTMP6.B],Y STZ DOSTMP6.B ; job ID LDY #$0E LDA DOSTMP7.B AND #$7F STA [DOSTMP6.B],Y ; DOS version LDY #0 JSR DOSGETVER.W STA [DOSTMP6.B],Y ; stack pointer ACC8 LDA IOBANK|ESTKBANK.L LDY #$06 STA [DOSTMP6.B],Y ; discard old X, Y from stack PLX ; D PLA ; B PLY ; wasted PLY ; wasted PHA ; B PHX ; D ; stack: ORIG_ADDR(24), DOSCALLEXIT(16), B, D ACC16 TSC LDY #$04 STA [DOSTMP6.B],Y LDA #$0079 STA DOSTMP6.B ; trampoline LDY #0 LDA #((DOSBUSY&$FF)<<8)|$8F ; STA ...|DOSBUSY.L STA [DOSTMP6.B],Y LDA #(DOSLD>>8) ; ... DOSLD... LDY #2 STA [DOSTMP6.B],Y LDA #$004C ; JMP... abs LDY #4 STA [DOSTMP6.B],Y LDA #$0100 LDY #5 STA [DOSTMP6.B],Y LDX #0 LDY #0 ACC8 LDA #$5C STA DOSTMP5+1.B LDA DOSTMP7.B PHA ; store bank since we need it later PHA PLB ; stack: ORIG_ADDR(24), DOSCALLEXIT(16), B, D, B AXY16 LDA #0 TCD DOSJUMPPROG: JSL DOSLD|DOSTMP5+1.L ; go to STA+JML vector and ; start running program DOSJUMPPROGRTL: ; in case the program RTLs AXY16 LDA #$0000 PEA $0000 PEA $0000 ; assumed stack: RTL24(K8 PC16) RTS16 DOSTERMINATE: ; $00 = terminate program ACC8 STA DOSLD|DOSLASTEXITCODE.L ; set data bank to be equal to program bank LDA 5,S PHA PLB ACC16 AND #$FF TAY ACC8 ; restore old stack bank LDA $0006.W STA IOBANK|ESTKBANK.L ; restore old stack pointer ACC16 LDA $0004.W TCS EXITDOSRAM ENTERDOSRAM ACC16 STY DOSTMP8.B LDA #$0020 STA DOSTMP7.B @CLOSEFILEHANDLES: ; close file handles PHY LDY #0 - LDA [DOSTMP7.B],Y CMP #DOSFILETABLE BCC + TAX PHY LDA #$FFFF JSR DOSCLOSEHANDLE.W PLY + INY INY CPY #$0020 BCC - PLY ; TODO: free allocated blocks ; free program bank TYX JSR DOSUNALLOCRAMBANK.W DOSLAUNCHRETURN: JSR DOSWRITEBACK.W EXITDOSRAM DOSGETEXITCODE: ; $39 = get exit code ACC8 LDA DOSLD|DOSLASTEXITCODE.L ACC16 AND #$FF CLC RTS
;***************************************************************************** ;* x86inc.asm: x264asm abstraction layer ;***************************************************************************** ;* Copyright (C) 2005-2014 x264 project ;* ;* Authors: Loren Merritt <lorenm@u.washington.edu> ;* Anton Mitrofanov <BugMaster@narod.ru> ;* Jason Garrett-Glaser <darkshikari@gmail.com> ;* Henrik Gramner <henrik@gramner.com> ;* ;* Permission to use, copy, modify, and/or distribute this software for any ;* purpose with or without fee is hereby granted, provided that the above ;* copyright notice and this permission notice appear in all copies. ;* ;* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES ;* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF ;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ;* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ;* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF ;* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ;***************************************************************************** ; This is a header file for the x264ASM assembly language, which uses ; NASM/YASM syntax combined with a large number of macros to provide easy ; abstraction between different calling conventions (x86_32, win64, linux64). ; It also has various other useful features to simplify writing the kind of ; DSP functions that are most often used in x264. ; Unlike the rest of x264, this file is available under an ISC license, as it ; has significant usefulness outside of x264 and we want it to be available ; to the largest audience possible. Of course, if you modify it for your own ; purposes to add a new feature, we strongly encourage contributing a patch ; as this feature might be useful for others as well. Send patches or ideas ; to x264-devel@videolan.org . %ifndef private_prefix %define private_prefix kvz %endif %ifndef public_prefix %define public_prefix private_prefix %endif %define WIN64 0 %define UNIX64 0 %if ARCH_X86_64 %ifidn __OUTPUT_FORMAT__,win32 %define WIN64 1 %elifidn __OUTPUT_FORMAT__,win64 %define WIN64 1 %elifidn __OUTPUT_FORMAT__,x64 %define WIN64 1 %else %define UNIX64 1 %endif %endif %ifdef PREFIX %define mangle(x) _ %+ x %else %define mangle(x) x %endif %macro SECTION_RODATA 0-1 16 SECTION .rodata align=%1 %endmacro %macro SECTION_TEXT 0-1 16 SECTION .text align=%1 %endmacro %if WIN64 %define PIC %elif ARCH_X86_64 == 0 ; x86_32 doesn't require PIC. ; Some distros prefer shared objects to be PIC, but nothing breaks if ; the code contains a few textrels, so we'll skip that complexity. %undef PIC %endif %ifdef PIC default rel %endif %macro CPUNOP 1 %ifdef __YASM_MAJOR__ CPU %1 %endif %endmacro ; Always use long nops (reduces 0x90 spam in disassembly on x86_32) CPUNOP amdnop ; Macros to eliminate most code duplication between x86_32 and x86_64: ; Currently this works only for leaf functions which load all their arguments ; into registers at the start, and make no other use of the stack. Luckily that ; covers most of x264's asm. ; PROLOGUE: ; %1 = number of arguments. loads them from stack if needed. ; %2 = number of registers used. pushes callee-saved regs if needed. ; %3 = number of xmm registers used. pushes callee-saved xmm regs if needed. ; %4 = (optional) stack size to be allocated. If not aligned (x86-32 ICC 10.x, ; MSVC or YMM), the stack will be manually aligned (to 16 or 32 bytes), ; and an extra register will be allocated to hold the original stack ; pointer (to not invalidate r0m etc.). To prevent the use of an extra ; register as stack pointer, request a negative stack size. ; %4+/%5+ = list of names to define to registers ; PROLOGUE can also be invoked by adding the same options to cglobal ; e.g. ; cglobal foo, 2,3,0, dst, src, tmp ; declares a function (foo), taking two args (dst and src) and one local variable (tmp) ; TODO Some functions can use some args directly from the stack. If they're the ; last args then you can just not declare them, but if they're in the middle ; we need more flexible macro. ; RET: ; Pops anything that was pushed by PROLOGUE, and returns. ; REP_RET: ; Use this instead of RET if it's a branch target. ; registers: ; rN and rNq are the native-size register holding function argument N ; rNd, rNw, rNb are dword, word, and byte size ; rNh is the high 8 bits of the word size ; rNm is the original location of arg N (a register or on the stack), dword ; rNmp is native size %macro DECLARE_REG 2-3 %define r%1q %2 %define r%1d %2d %define r%1w %2w %define r%1b %2b %define r%1h %2h %if %0 == 2 %define r%1m %2d %define r%1mp %2 %elif ARCH_X86_64 ; memory %define r%1m [rstk + stack_offset + %3] %define r%1mp qword r %+ %1 %+ m %else %define r%1m [rstk + stack_offset + %3] %define r%1mp dword r %+ %1 %+ m %endif %define r%1 %2 %endmacro %macro DECLARE_REG_SIZE 3 %define r%1q r%1 %define e%1q r%1 %define r%1d e%1 %define e%1d e%1 %define r%1w %1 %define e%1w %1 %define r%1h %3 %define e%1h %3 %define r%1b %2 %define e%1b %2 %if ARCH_X86_64 == 0 %define r%1 e%1 %endif %endmacro DECLARE_REG_SIZE ax, al, ah DECLARE_REG_SIZE bx, bl, bh DECLARE_REG_SIZE cx, cl, ch DECLARE_REG_SIZE dx, dl, dh DECLARE_REG_SIZE si, sil, null DECLARE_REG_SIZE di, dil, null DECLARE_REG_SIZE bp, bpl, null ; t# defines for when per-arch register allocation is more complex than just function arguments %macro DECLARE_REG_TMP 1-* %assign %%i 0 %rep %0 CAT_XDEFINE t, %%i, r%1 %assign %%i %%i+1 %rotate 1 %endrep %endmacro %macro DECLARE_REG_TMP_SIZE 0-* %rep %0 %define t%1q t%1 %+ q %define t%1d t%1 %+ d %define t%1w t%1 %+ w %define t%1h t%1 %+ h %define t%1b t%1 %+ b %rotate 1 %endrep %endmacro DECLARE_REG_TMP_SIZE 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14 %if ARCH_X86_64 %define gprsize 8 %else %define gprsize 4 %endif %macro PUSH 1 push %1 %ifidn rstk, rsp %assign stack_offset stack_offset+gprsize %endif %endmacro %macro POP 1 pop %1 %ifidn rstk, rsp %assign stack_offset stack_offset-gprsize %endif %endmacro %macro PUSH_IF_USED 1-* %rep %0 %if %1 < regs_used PUSH r%1 %endif %rotate 1 %endrep %endmacro %macro POP_IF_USED 1-* %rep %0 %if %1 < regs_used pop r%1 %endif %rotate 1 %endrep %endmacro %macro LOAD_IF_USED 1-* %rep %0 %if %1 < num_args mov r%1, r %+ %1 %+ mp %endif %rotate 1 %endrep %endmacro %macro SUB 2 sub %1, %2 %ifidn %1, rstk %assign stack_offset stack_offset+(%2) %endif %endmacro %macro ADD 2 add %1, %2 %ifidn %1, rstk %assign stack_offset stack_offset-(%2) %endif %endmacro %macro movifnidn 2 %ifnidn %1, %2 mov %1, %2 %endif %endmacro %macro movsxdifnidn 2 %ifnidn %1, %2 movsxd %1, %2 %endif %endmacro %macro ASSERT 1 %if (%1) == 0 %error assert failed %endif %endmacro %macro DEFINE_ARGS 0-* %ifdef n_arg_names %assign %%i 0 %rep n_arg_names CAT_UNDEF arg_name %+ %%i, q CAT_UNDEF arg_name %+ %%i, d CAT_UNDEF arg_name %+ %%i, w CAT_UNDEF arg_name %+ %%i, h CAT_UNDEF arg_name %+ %%i, b CAT_UNDEF arg_name %+ %%i, m CAT_UNDEF arg_name %+ %%i, mp CAT_UNDEF arg_name, %%i %assign %%i %%i+1 %endrep %endif %xdefine %%stack_offset stack_offset %undef stack_offset ; so that the current value of stack_offset doesn't get baked in by xdefine %assign %%i 0 %rep %0 %xdefine %1q r %+ %%i %+ q %xdefine %1d r %+ %%i %+ d %xdefine %1w r %+ %%i %+ w %xdefine %1h r %+ %%i %+ h %xdefine %1b r %+ %%i %+ b %xdefine %1m r %+ %%i %+ m %xdefine %1mp r %+ %%i %+ mp CAT_XDEFINE arg_name, %%i, %1 %assign %%i %%i+1 %rotate 1 %endrep %xdefine stack_offset %%stack_offset %assign n_arg_names %0 %endmacro %macro ALLOC_STACK 1-2 0 ; stack_size, n_xmm_regs (for win64 only) %ifnum %1 %if %1 != 0 %assign %%stack_alignment ((mmsize + 15) & ~15) %assign stack_size %1 %if stack_size < 0 %assign stack_size -stack_size %endif %assign stack_size_padded stack_size %if WIN64 %assign stack_size_padded stack_size_padded + 32 ; reserve 32 bytes for shadow space %if mmsize != 8 %assign xmm_regs_used %2 %if xmm_regs_used > 8 %assign stack_size_padded stack_size_padded + (xmm_regs_used-8)*16 %endif %endif %endif %if mmsize <= 16 && HAVE_ALIGNED_STACK %assign stack_size_padded stack_size_padded + %%stack_alignment - gprsize - (stack_offset & (%%stack_alignment - 1)) SUB rsp, stack_size_padded %else %assign %%reg_num (regs_used - 1) %xdefine rstk r %+ %%reg_num ; align stack, and save original stack location directly above ; it, i.e. in [rsp+stack_size_padded], so we can restore the ; stack in a single instruction (i.e. mov rsp, rstk or mov ; rsp, [rsp+stack_size_padded]) mov rstk, rsp %if %1 < 0 ; need to store rsp on stack sub rsp, gprsize+stack_size_padded and rsp, ~(%%stack_alignment-1) %xdefine rstkm [rsp+stack_size_padded] mov rstkm, rstk %else ; can keep rsp in rstk during whole function sub rsp, stack_size_padded and rsp, ~(%%stack_alignment-1) %xdefine rstkm rstk %endif %endif WIN64_PUSH_XMM %endif %endif %endmacro %macro SETUP_STACK_POINTER 1 %ifnum %1 %if %1 != 0 && (HAVE_ALIGNED_STACK == 0 || mmsize == 32) %if %1 > 0 %assign regs_used (regs_used + 1) %elif ARCH_X86_64 && regs_used == num_args && num_args <= 4 + UNIX64 * 2 %warning "Stack pointer will overwrite register argument" %endif %endif %endif %endmacro %macro DEFINE_ARGS_INTERNAL 3+ %ifnum %2 DEFINE_ARGS %3 %elif %1 == 4 DEFINE_ARGS %2 %elif %1 > 4 DEFINE_ARGS %2, %3 %endif %endmacro %if WIN64 ; Windows x64 ;================================================= DECLARE_REG 0, rcx DECLARE_REG 1, rdx DECLARE_REG 2, R8 DECLARE_REG 3, R9 DECLARE_REG 4, R10, 40 DECLARE_REG 5, R11, 48 DECLARE_REG 6, rax, 56 DECLARE_REG 7, rdi, 64 DECLARE_REG 8, rsi, 72 DECLARE_REG 9, rbx, 80 DECLARE_REG 10, rbp, 88 DECLARE_REG 11, R12, 96 DECLARE_REG 12, R13, 104 DECLARE_REG 13, R14, 112 DECLARE_REG 14, R15, 120 %macro PROLOGUE 2-5+ 0 ; #args, #regs, #xmm_regs, [stack_size,] arg_names... %assign num_args %1 %assign regs_used %2 ASSERT regs_used >= num_args SETUP_STACK_POINTER %4 ASSERT regs_used <= 15 PUSH_IF_USED 7, 8, 9, 10, 11, 12, 13, 14 ALLOC_STACK %4, %3 %if mmsize != 8 && stack_size == 0 WIN64_SPILL_XMM %3 %endif LOAD_IF_USED 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 DEFINE_ARGS_INTERNAL %0, %4, %5 %endmacro %macro WIN64_PUSH_XMM 0 ; Use the shadow space to store XMM6 and XMM7, the rest needs stack space allocated. %if xmm_regs_used > 6 movaps [rstk + stack_offset + 8], xmm6 %endif %if xmm_regs_used > 7 movaps [rstk + stack_offset + 24], xmm7 %endif %if xmm_regs_used > 8 %assign %%i 8 %rep xmm_regs_used-8 movaps [rsp + (%%i-8)*16 + stack_size + 32], xmm %+ %%i %assign %%i %%i+1 %endrep %endif %endmacro %macro WIN64_SPILL_XMM 1 %assign xmm_regs_used %1 ASSERT xmm_regs_used <= 16 %if xmm_regs_used > 8 %assign stack_size_padded (xmm_regs_used-8)*16 + (~stack_offset&8) + 32 SUB rsp, stack_size_padded %endif WIN64_PUSH_XMM %endmacro %macro WIN64_RESTORE_XMM_INTERNAL 1 %assign %%pad_size 0 %if xmm_regs_used > 8 %assign %%i xmm_regs_used %rep xmm_regs_used-8 %assign %%i %%i-1 movaps xmm %+ %%i, [%1 + (%%i-8)*16 + stack_size + 32] %endrep %endif %if stack_size_padded > 0 %if stack_size > 0 && (mmsize == 32 || HAVE_ALIGNED_STACK == 0) mov rsp, rstkm %else add %1, stack_size_padded %assign %%pad_size stack_size_padded %endif %endif %if xmm_regs_used > 7 movaps xmm7, [%1 + stack_offset - %%pad_size + 24] %endif %if xmm_regs_used > 6 movaps xmm6, [%1 + stack_offset - %%pad_size + 8] %endif %endmacro %macro WIN64_RESTORE_XMM 1 WIN64_RESTORE_XMM_INTERNAL %1 %assign stack_offset (stack_offset-stack_size_padded) %assign xmm_regs_used 0 %endmacro %define has_epilogue regs_used > 7 || xmm_regs_used > 6 || mmsize == 32 || stack_size > 0 %macro RET 0 WIN64_RESTORE_XMM_INTERNAL rsp POP_IF_USED 14, 13, 12, 11, 10, 9, 8, 7 %if mmsize == 32 vzeroupper %endif AUTO_REP_RET %endmacro %elif ARCH_X86_64 ; *nix x64 ;============================================= DECLARE_REG 0, rdi DECLARE_REG 1, rsi DECLARE_REG 2, rdx DECLARE_REG 3, rcx DECLARE_REG 4, R8 DECLARE_REG 5, R9 DECLARE_REG 6, rax, 8 DECLARE_REG 7, R10, 16 DECLARE_REG 8, R11, 24 DECLARE_REG 9, rbx, 32 DECLARE_REG 10, rbp, 40 DECLARE_REG 11, R12, 48 DECLARE_REG 12, R13, 56 DECLARE_REG 13, R14, 64 DECLARE_REG 14, R15, 72 %macro PROLOGUE 2-5+ ; #args, #regs, #xmm_regs, [stack_size,] arg_names... %assign num_args %1 %assign regs_used %2 ASSERT regs_used >= num_args SETUP_STACK_POINTER %4 ASSERT regs_used <= 15 PUSH_IF_USED 9, 10, 11, 12, 13, 14 ALLOC_STACK %4 LOAD_IF_USED 6, 7, 8, 9, 10, 11, 12, 13, 14 DEFINE_ARGS_INTERNAL %0, %4, %5 %endmacro %define has_epilogue regs_used > 9 || mmsize == 32 || stack_size > 0 %macro RET 0 %if stack_size_padded > 0 %if mmsize == 32 || HAVE_ALIGNED_STACK == 0 mov rsp, rstkm %else add rsp, stack_size_padded %endif %endif POP_IF_USED 14, 13, 12, 11, 10, 9 %if mmsize == 32 vzeroupper %endif AUTO_REP_RET %endmacro %else ; X86_32 ;============================================================== DECLARE_REG 0, eax, 4 DECLARE_REG 1, ecx, 8 DECLARE_REG 2, edx, 12 DECLARE_REG 3, ebx, 16 DECLARE_REG 4, esi, 20 DECLARE_REG 5, edi, 24 DECLARE_REG 6, ebp, 28 %define rsp esp %macro DECLARE_ARG 1-* %rep %0 %define r%1m [rstk + stack_offset + 4*%1 + 4] %define r%1mp dword r%1m %rotate 1 %endrep %endmacro DECLARE_ARG 7, 8, 9, 10, 11, 12, 13, 14 %macro PROLOGUE 2-5+ ; #args, #regs, #xmm_regs, [stack_size,] arg_names... %assign num_args %1 %assign regs_used %2 ASSERT regs_used >= num_args %if num_args > 7 %assign num_args 7 %endif %if regs_used > 7 %assign regs_used 7 %endif SETUP_STACK_POINTER %4 ASSERT regs_used <= 7 PUSH_IF_USED 3, 4, 5, 6 ALLOC_STACK %4 LOAD_IF_USED 0, 1, 2, 3, 4, 5, 6 DEFINE_ARGS_INTERNAL %0, %4, %5 %endmacro %define has_epilogue regs_used > 3 || mmsize == 32 || stack_size > 0 %macro RET 0 %if stack_size_padded > 0 %if mmsize == 32 || HAVE_ALIGNED_STACK == 0 mov rsp, rstkm %else add rsp, stack_size_padded %endif %endif POP_IF_USED 6, 5, 4, 3 %if mmsize == 32 vzeroupper %endif AUTO_REP_RET %endmacro %endif ;====================================================================== %if WIN64 == 0 %macro WIN64_SPILL_XMM 1 %endmacro %macro WIN64_RESTORE_XMM 1 %endmacro %macro WIN64_PUSH_XMM 0 %endmacro %endif ; On AMD cpus <=K10, an ordinary ret is slow if it immediately follows either ; a branch or a branch target. So switch to a 2-byte form of ret in that case. ; We can automatically detect "follows a branch", but not a branch target. ; (SSSE3 is a sufficient condition to know that your cpu doesn't have this problem.) %macro REP_RET 0 %if has_epilogue RET %else rep ret %endif %endmacro %define last_branch_adr $$ %macro AUTO_REP_RET 0 %ifndef cpuflags times ((last_branch_adr-$)>>31)+1 rep ; times 1 iff $ != last_branch_adr. %elif notcpuflag(ssse3) times ((last_branch_adr-$)>>31)+1 rep %endif ret %endmacro %macro BRANCH_INSTR 0-* %rep %0 %macro %1 1-2 %1 %2 %1 %%branch_instr: %xdefine last_branch_adr %%branch_instr %endmacro %rotate 1 %endrep %endmacro BRANCH_INSTR jz, je, jnz, jne, jl, jle, jnl, jnle, jg, jge, jng, jnge, ja, jae, jna, jnae, jb, jbe, jnb, jnbe, jc, jnc, js, jns, jo, jno, jp, jnp %macro TAIL_CALL 2 ; callee, is_nonadjacent %if has_epilogue call %1 RET %elif %2 jmp %1 %endif %endmacro ;============================================================================= ; arch-independent part ;============================================================================= %assign function_align 16 ; Begin a function. ; Applies any symbol mangling needed for C linkage, and sets up a define such that ; subsequent uses of the function name automatically refer to the mangled version. ; Appends cpuflags to the function name if cpuflags has been specified. ; The "" empty default parameter is a workaround for nasm, which fails if SUFFIX ; is empty and we call cglobal_internal with just %1 %+ SUFFIX (without %2). %macro cglobal 1-2+ "" ; name, [PROLOGUE args] cglobal_internal 1, %1 %+ SUFFIX, %2 %endmacro %macro cvisible 1-2+ "" ; name, [PROLOGUE args] cglobal_internal 0, %1 %+ SUFFIX, %2 %endmacro %macro cglobal_internal 2-3+ %if %1 %xdefine %%FUNCTION_PREFIX private_prefix %xdefine %%VISIBILITY hidden %else %xdefine %%FUNCTION_PREFIX public_prefix %xdefine %%VISIBILITY %endif %ifndef cglobaled_%2 %xdefine %2 mangle(%%FUNCTION_PREFIX %+ _ %+ %2) %xdefine %2.skip_prologue %2 %+ .skip_prologue CAT_XDEFINE cglobaled_, %2, 1 %endif %xdefine current_function %2 %ifidn __OUTPUT_FORMAT__,elf global %2:function %%VISIBILITY %else global %2 %endif align function_align %2: RESET_MM_PERMUTATION ; needed for x86-64, also makes disassembly somewhat nicer %xdefine rstk rsp ; copy of the original stack pointer, used when greater alignment than the known stack alignment is required %assign stack_offset 0 ; stack pointer offset relative to the return address %assign stack_size 0 ; amount of stack space that can be freely used inside a function %assign stack_size_padded 0 ; total amount of allocated stack space, including space for callee-saved xmm registers on WIN64 and alignment padding %assign xmm_regs_used 0 ; number of XMM registers requested, used for dealing with callee-saved registers on WIN64 %ifnidn %3, "" PROLOGUE %3 %endif %endmacro %macro cextern 1 %xdefine %1 mangle(private_prefix %+ _ %+ %1) CAT_XDEFINE cglobaled_, %1, 1 extern %1 %endmacro ; like cextern, but without the prefix %macro cextern_naked 1 %xdefine %1 mangle(%1) CAT_XDEFINE cglobaled_, %1, 1 extern %1 %endmacro %macro const 1-2+ %xdefine %1 mangle(private_prefix %+ _ %+ %1) %ifidn __OUTPUT_FORMAT__,elf global %1:data hidden %else global %1 %endif %1: %2 %endmacro ; This is needed for ELF, otherwise the GNU linker assumes the stack is ; executable by default. %ifidn __OUTPUT_FORMAT__,elf SECTION .note.GNU-stack noalloc noexec nowrite progbits %endif ; cpuflags %assign cpuflags_mmx (1<<0) %assign cpuflags_mmx2 (1<<1) | cpuflags_mmx %assign cpuflags_3dnow (1<<2) | cpuflags_mmx %assign cpuflags_3dnowext (1<<3) | cpuflags_3dnow %assign cpuflags_sse (1<<4) | cpuflags_mmx2 %assign cpuflags_sse2 (1<<5) | cpuflags_sse %assign cpuflags_sse2slow (1<<6) | cpuflags_sse2 %assign cpuflags_sse3 (1<<7) | cpuflags_sse2 %assign cpuflags_ssse3 (1<<8) | cpuflags_sse3 %assign cpuflags_sse4 (1<<9) | cpuflags_ssse3 %assign cpuflags_sse42 (1<<10)| cpuflags_sse4 %assign cpuflags_avx (1<<11)| cpuflags_sse42 %assign cpuflags_xop (1<<12)| cpuflags_avx %assign cpuflags_fma4 (1<<13)| cpuflags_avx %assign cpuflags_avx2 (1<<14)| cpuflags_avx %assign cpuflags_fma3 (1<<15)| cpuflags_avx %assign cpuflags_cache32 (1<<16) %assign cpuflags_cache64 (1<<17) %assign cpuflags_slowctz (1<<18) %assign cpuflags_lzcnt (1<<19) %assign cpuflags_aligned (1<<20) ; not a cpu feature, but a function variant %assign cpuflags_atom (1<<21) %assign cpuflags_bmi1 (1<<22)|cpuflags_lzcnt %assign cpuflags_bmi2 (1<<23)|cpuflags_bmi1 %define cpuflag(x) ((cpuflags & (cpuflags_ %+ x)) == (cpuflags_ %+ x)) %define notcpuflag(x) ((cpuflags & (cpuflags_ %+ x)) != (cpuflags_ %+ x)) ; Takes up to 2 cpuflags from the above list. ; All subsequent functions (up to the next INIT_CPUFLAGS) is built for the specified cpu. ; You shouldn't need to invoke this macro directly, it's a subroutine for INIT_MMX &co. %macro INIT_CPUFLAGS 0-2 CPUNOP amdnop %if %0 >= 1 %xdefine cpuname %1 %assign cpuflags cpuflags_%1 %if %0 >= 2 %xdefine cpuname %1_%2 %assign cpuflags cpuflags | cpuflags_%2 %endif %xdefine SUFFIX _ %+ cpuname %if cpuflag(avx) %assign avx_enabled 1 %endif %if (mmsize == 16 && notcpuflag(sse2)) || (mmsize == 32 && notcpuflag(avx2)) %define mova movaps %define movu movups %define movnta movntps %endif %if cpuflag(aligned) %define movu mova %elifidn %1, sse3 %define movu lddqu %endif %if ARCH_X86_64 == 0 && notcpuflag(sse2) CPUNOP basicnop %endif %else %xdefine SUFFIX %undef cpuname %undef cpuflags %endif %endmacro ; Merge mmx and sse* ; m# is a simd register of the currently selected size ; xm# is the corresponding xmm register if mmsize >= 16, otherwise the same as m# ; ym# is the corresponding ymm register if mmsize >= 32, otherwise the same as m# ; (All 3 remain in sync through SWAP.) %macro CAT_XDEFINE 3 %xdefine %1%2 %3 %endmacro %macro CAT_UNDEF 2 %undef %1%2 %endmacro %macro INIT_MMX 0-1+ %assign avx_enabled 0 %define RESET_MM_PERMUTATION INIT_MMX %1 %define mmsize 8 %define num_mmregs 8 %define mova movq %define movu movq %define movh movd %define movnta movntq %assign %%i 0 %rep 8 CAT_XDEFINE m, %%i, mm %+ %%i CAT_XDEFINE nmm, %%i, %%i %assign %%i %%i+1 %endrep %rep 8 CAT_UNDEF m, %%i CAT_UNDEF nmm, %%i %assign %%i %%i+1 %endrep INIT_CPUFLAGS %1 %endmacro %macro INIT_XMM 0-1+ %assign avx_enabled 0 %define RESET_MM_PERMUTATION INIT_XMM %1 %define mmsize 16 %define num_mmregs 8 %if ARCH_X86_64 %define num_mmregs 16 %endif %define mova movdqa %define movu movdqu %define movh movq %define movnta movntdq %assign %%i 0 %rep num_mmregs CAT_XDEFINE m, %%i, xmm %+ %%i CAT_XDEFINE nxmm, %%i, %%i %assign %%i %%i+1 %endrep INIT_CPUFLAGS %1 %endmacro %macro INIT_YMM 0-1+ %assign avx_enabled 1 %define RESET_MM_PERMUTATION INIT_YMM %1 %define mmsize 32 %define num_mmregs 8 %if ARCH_X86_64 %define num_mmregs 16 %endif %define mova movdqa %define movu movdqu %undef movh %define movnta movntdq %assign %%i 0 %rep num_mmregs CAT_XDEFINE m, %%i, ymm %+ %%i CAT_XDEFINE nymm, %%i, %%i %assign %%i %%i+1 %endrep INIT_CPUFLAGS %1 %endmacro INIT_XMM %macro DECLARE_MMCAST 1 %define mmmm%1 mm%1 %define mmxmm%1 mm%1 %define mmymm%1 mm%1 %define xmmmm%1 mm%1 %define xmmxmm%1 xmm%1 %define xmmymm%1 xmm%1 %define ymmmm%1 mm%1 %define ymmxmm%1 xmm%1 %define ymmymm%1 ymm%1 %define xm%1 xmm %+ m%1 %define ym%1 ymm %+ m%1 %endmacro %assign i 0 %rep 16 DECLARE_MMCAST i %assign i i+1 %endrep ; I often want to use macros that permute their arguments. e.g. there's no ; efficient way to implement butterfly or transpose or dct without swapping some ; arguments. ; ; I would like to not have to manually keep track of the permutations: ; If I insert a permutation in the middle of a function, it should automatically ; change everything that follows. For more complex macros I may also have multiple ; implementations, e.g. the SSE2 and SSSE3 versions may have different permutations. ; ; Hence these macros. Insert a PERMUTE or some SWAPs at the end of a macro that ; permutes its arguments. It's equivalent to exchanging the contents of the ; registers, except that this way you exchange the register names instead, so it ; doesn't cost any cycles. %macro PERMUTE 2-* ; takes a list of pairs to swap %rep %0/2 %xdefine %%tmp%2 m%2 %rotate 2 %endrep %rep %0/2 %xdefine m%1 %%tmp%2 CAT_XDEFINE n, m%1, %1 %rotate 2 %endrep %endmacro %macro SWAP 2+ ; swaps a single chain (sometimes more concise than pairs) %ifnum %1 ; SWAP 0, 1, ... SWAP_INTERNAL_NUM %1, %2 %else ; SWAP m0, m1, ... SWAP_INTERNAL_NAME %1, %2 %endif %endmacro %macro SWAP_INTERNAL_NUM 2-* %rep %0-1 %xdefine %%tmp m%1 %xdefine m%1 m%2 %xdefine m%2 %%tmp CAT_XDEFINE n, m%1, %1 CAT_XDEFINE n, m%2, %2 %rotate 1 %endrep %endmacro %macro SWAP_INTERNAL_NAME 2-* %xdefine %%args n %+ %1 %rep %0-1 %xdefine %%args %%args, n %+ %2 %rotate 1 %endrep SWAP_INTERNAL_NUM %%args %endmacro ; If SAVE_MM_PERMUTATION is placed at the end of a function, then any later ; calls to that function will automatically load the permutation, so values can ; be returned in mmregs. %macro SAVE_MM_PERMUTATION 0-1 %if %0 %xdefine %%f %1_m %else %xdefine %%f current_function %+ _m %endif %assign %%i 0 %rep num_mmregs CAT_XDEFINE %%f, %%i, m %+ %%i %assign %%i %%i+1 %endrep %endmacro %macro LOAD_MM_PERMUTATION 1 ; name to load from %ifdef %1_m0 %assign %%i 0 %rep num_mmregs CAT_XDEFINE m, %%i, %1_m %+ %%i CAT_XDEFINE n, m %+ %%i, %%i %assign %%i %%i+1 %endrep %endif %endmacro ; Append cpuflags to the callee's name iff the appended name is known and the plain name isn't %macro call 1 call_internal %1, %1 %+ SUFFIX %endmacro %macro call_internal 2 %xdefine %%i %1 %ifndef cglobaled_%1 %ifdef cglobaled_%2 %xdefine %%i %2 %endif %endif call %%i LOAD_MM_PERMUTATION %%i %endmacro ; Substitutions that reduce instruction size but are functionally equivalent %macro add 2 %ifnum %2 %if %2==128 sub %1, -128 %else add %1, %2 %endif %else add %1, %2 %endif %endmacro %macro sub 2 %ifnum %2 %if %2==128 add %1, -128 %else sub %1, %2 %endif %else sub %1, %2 %endif %endmacro ;============================================================================= ; AVX abstraction layer ;============================================================================= %assign i 0 %rep 16 %if i < 8 CAT_XDEFINE sizeofmm, i, 8 %endif CAT_XDEFINE sizeofxmm, i, 16 CAT_XDEFINE sizeofymm, i, 32 %assign i i+1 %endrep %undef i %macro CHECK_AVX_INSTR_EMU 3-* %xdefine %%opcode %1 %xdefine %%dst %2 %rep %0-2 %ifidn %%dst, %3 %error non-avx emulation of ``%%opcode'' is not supported %endif %rotate 1 %endrep %endmacro ;%1 == instruction ;%2 == 1 if float, 0 if int ;%3 == 1 if non-destructive or 4-operand (xmm, xmm, xmm, imm), 0 otherwise ;%4 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not ;%5+: operands %macro RUN_AVX_INSTR 5-8+ %ifnum sizeof%6 %assign %%sizeofreg sizeof%6 %elifnum sizeof%5 %assign %%sizeofreg sizeof%5 %else %assign %%sizeofreg mmsize %endif %assign %%emulate_avx 0 %if avx_enabled && %%sizeofreg >= 16 %xdefine %%instr v%1 %else %xdefine %%instr %1 %if %0 >= 7+%3 %assign %%emulate_avx 1 %endif %endif %if %%emulate_avx %xdefine %%src1 %6 %xdefine %%src2 %7 %ifnidn %5, %6 %if %0 >= 8 CHECK_AVX_INSTR_EMU {%1 %5, %6, %7, %8}, %5, %7, %8 %else CHECK_AVX_INSTR_EMU {%1 %5, %6, %7}, %5, %7 %endif %if %4 && %3 == 0 %ifnid %7 ; 3-operand AVX instructions with a memory arg can only have it in src2, ; whereas SSE emulation prefers to have it in src1 (i.e. the mov). ; So, if the instruction is commutative with a memory arg, swap them. %xdefine %%src1 %7 %xdefine %%src2 %6 %endif %endif %if %%sizeofreg == 8 MOVQ %5, %%src1 %elif %2 MOVAPS %5, %%src1 %else MOVDQA %5, %%src1 %endif %endif %if %0 >= 8 %1 %5, %%src2, %8 %else %1 %5, %%src2 %endif %elif %0 >= 8 %%instr %5, %6, %7, %8 %elif %0 == 7 %%instr %5, %6, %7 %elif %0 == 6 %%instr %5, %6 %else %%instr %5 %endif %endmacro ;%1 == instruction ;%2 == 1 if float, 0 if int ;%3 == 1 if non-destructive or 4-operand (xmm, xmm, xmm, imm), 0 otherwise ;%4 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not %macro AVX_INSTR 1-4 0, 1, 0 %macro %1 1-9 fnord, fnord, fnord, fnord, %1, %2, %3, %4 %ifidn %2, fnord RUN_AVX_INSTR %6, %7, %8, %9, %1 %elifidn %3, fnord RUN_AVX_INSTR %6, %7, %8, %9, %1, %2 %elifidn %4, fnord RUN_AVX_INSTR %6, %7, %8, %9, %1, %2, %3 %elifidn %5, fnord RUN_AVX_INSTR %6, %7, %8, %9, %1, %2, %3, %4 %else RUN_AVX_INSTR %6, %7, %8, %9, %1, %2, %3, %4, %5 %endif %endmacro %endmacro ; Instructions with both VEX and non-VEX encodings ; Non-destructive instructions are written without parameters AVX_INSTR addpd, 1, 0, 1 AVX_INSTR addps, 1, 0, 1 AVX_INSTR addsd, 1, 0, 1 AVX_INSTR addss, 1, 0, 1 AVX_INSTR addsubpd, 1, 0, 0 AVX_INSTR addsubps, 1, 0, 0 AVX_INSTR aesdec, 0, 0, 0 AVX_INSTR aesdeclast, 0, 0, 0 AVX_INSTR aesenc, 0, 0, 0 AVX_INSTR aesenclast, 0, 0, 0 AVX_INSTR aesimc AVX_INSTR aeskeygenassist AVX_INSTR andnpd, 1, 0, 0 AVX_INSTR andnps, 1, 0, 0 AVX_INSTR andpd, 1, 0, 1 AVX_INSTR andps, 1, 0, 1 AVX_INSTR blendpd, 1, 0, 0 AVX_INSTR blendps, 1, 0, 0 AVX_INSTR blendvpd, 1, 0, 0 AVX_INSTR blendvps, 1, 0, 0 AVX_INSTR cmppd, 1, 1, 0 AVX_INSTR cmpps, 1, 1, 0 AVX_INSTR cmpsd, 1, 1, 0 AVX_INSTR cmpss, 1, 1, 0 AVX_INSTR comisd AVX_INSTR comiss AVX_INSTR cvtdq2pd AVX_INSTR cvtdq2ps AVX_INSTR cvtpd2dq AVX_INSTR cvtpd2ps AVX_INSTR cvtps2dq AVX_INSTR cvtps2pd AVX_INSTR cvtsd2si AVX_INSTR cvtsd2ss AVX_INSTR cvtsi2sd AVX_INSTR cvtsi2ss AVX_INSTR cvtss2sd AVX_INSTR cvtss2si AVX_INSTR cvttpd2dq AVX_INSTR cvttps2dq AVX_INSTR cvttsd2si AVX_INSTR cvttss2si AVX_INSTR divpd, 1, 0, 0 AVX_INSTR divps, 1, 0, 0 AVX_INSTR divsd, 1, 0, 0 AVX_INSTR divss, 1, 0, 0 AVX_INSTR dppd, 1, 1, 0 AVX_INSTR dpps, 1, 1, 0 AVX_INSTR extractps AVX_INSTR haddpd, 1, 0, 0 AVX_INSTR haddps, 1, 0, 0 AVX_INSTR hsubpd, 1, 0, 0 AVX_INSTR hsubps, 1, 0, 0 AVX_INSTR insertps, 1, 1, 0 AVX_INSTR lddqu AVX_INSTR ldmxcsr AVX_INSTR maskmovdqu AVX_INSTR maxpd, 1, 0, 1 AVX_INSTR maxps, 1, 0, 1 AVX_INSTR maxsd, 1, 0, 1 AVX_INSTR maxss, 1, 0, 1 AVX_INSTR minpd, 1, 0, 1 AVX_INSTR minps, 1, 0, 1 AVX_INSTR minsd, 1, 0, 1 AVX_INSTR minss, 1, 0, 1 AVX_INSTR movapd AVX_INSTR movaps AVX_INSTR movd AVX_INSTR movddup AVX_INSTR movdqa AVX_INSTR movdqu AVX_INSTR movhlps, 1, 0, 0 AVX_INSTR movhpd, 1, 0, 0 AVX_INSTR movhps, 1, 0, 0 AVX_INSTR movlhps, 1, 0, 0 AVX_INSTR movlpd, 1, 0, 0 AVX_INSTR movlps, 1, 0, 0 AVX_INSTR movmskpd AVX_INSTR movmskps AVX_INSTR movntdq AVX_INSTR movntdqa AVX_INSTR movntpd AVX_INSTR movntps AVX_INSTR movq AVX_INSTR movsd, 1, 0, 0 AVX_INSTR movshdup AVX_INSTR movsldup AVX_INSTR movss, 1, 0, 0 AVX_INSTR movupd AVX_INSTR movups AVX_INSTR mpsadbw, 0, 1, 0 AVX_INSTR mulpd, 1, 0, 1 AVX_INSTR mulps, 1, 0, 1 AVX_INSTR mulsd, 1, 0, 1 AVX_INSTR mulss, 1, 0, 1 AVX_INSTR orpd, 1, 0, 1 AVX_INSTR orps, 1, 0, 1 AVX_INSTR pabsb AVX_INSTR pabsd AVX_INSTR pabsw AVX_INSTR packsswb, 0, 0, 0 AVX_INSTR packssdw, 0, 0, 0 AVX_INSTR packuswb, 0, 0, 0 AVX_INSTR packusdw, 0, 0, 0 AVX_INSTR paddb, 0, 0, 1 AVX_INSTR paddw, 0, 0, 1 AVX_INSTR paddd, 0, 0, 1 AVX_INSTR paddq, 0, 0, 1 AVX_INSTR paddsb, 0, 0, 1 AVX_INSTR paddsw, 0, 0, 1 AVX_INSTR paddusb, 0, 0, 1 AVX_INSTR paddusw, 0, 0, 1 AVX_INSTR palignr, 0, 1, 0 AVX_INSTR pand, 0, 0, 1 AVX_INSTR pandn, 0, 0, 0 AVX_INSTR pavgb, 0, 0, 1 AVX_INSTR pavgw, 0, 0, 1 AVX_INSTR pblendvb, 0, 0, 0 AVX_INSTR pblendw, 0, 1, 0 AVX_INSTR pclmulqdq, 0, 1, 0 AVX_INSTR pcmpestri AVX_INSTR pcmpestrm AVX_INSTR pcmpistri AVX_INSTR pcmpistrm AVX_INSTR pcmpeqb, 0, 0, 1 AVX_INSTR pcmpeqw, 0, 0, 1 AVX_INSTR pcmpeqd, 0, 0, 1 AVX_INSTR pcmpeqq, 0, 0, 1 AVX_INSTR pcmpgtb, 0, 0, 0 AVX_INSTR pcmpgtw, 0, 0, 0 AVX_INSTR pcmpgtd, 0, 0, 0 AVX_INSTR pcmpgtq, 0, 0, 0 AVX_INSTR pextrb AVX_INSTR pextrd AVX_INSTR pextrq AVX_INSTR pextrw AVX_INSTR phaddw, 0, 0, 0 AVX_INSTR phaddd, 0, 0, 0 AVX_INSTR phaddsw, 0, 0, 0 AVX_INSTR phminposuw AVX_INSTR phsubw, 0, 0, 0 AVX_INSTR phsubd, 0, 0, 0 AVX_INSTR phsubsw, 0, 0, 0 AVX_INSTR pinsrb, 0, 1, 0 AVX_INSTR pinsrd, 0, 1, 0 AVX_INSTR pinsrq, 0, 1, 0 AVX_INSTR pinsrw, 0, 1, 0 AVX_INSTR pmaddwd, 0, 0, 1 AVX_INSTR pmaddubsw, 0, 0, 0 AVX_INSTR pmaxsb, 0, 0, 1 AVX_INSTR pmaxsw, 0, 0, 1 AVX_INSTR pmaxsd, 0, 0, 1 AVX_INSTR pmaxub, 0, 0, 1 AVX_INSTR pmaxuw, 0, 0, 1 AVX_INSTR pmaxud, 0, 0, 1 AVX_INSTR pminsb, 0, 0, 1 AVX_INSTR pminsw, 0, 0, 1 AVX_INSTR pminsd, 0, 0, 1 AVX_INSTR pminub, 0, 0, 1 AVX_INSTR pminuw, 0, 0, 1 AVX_INSTR pminud, 0, 0, 1 AVX_INSTR pmovmskb AVX_INSTR pmovsxbw AVX_INSTR pmovsxbd AVX_INSTR pmovsxbq AVX_INSTR pmovsxwd AVX_INSTR pmovsxwq AVX_INSTR pmovsxdq AVX_INSTR pmovzxbw AVX_INSTR pmovzxbd AVX_INSTR pmovzxbq AVX_INSTR pmovzxwd AVX_INSTR pmovzxwq AVX_INSTR pmovzxdq AVX_INSTR pmuldq, 0, 0, 1 AVX_INSTR pmulhrsw, 0, 0, 1 AVX_INSTR pmulhuw, 0, 0, 1 AVX_INSTR pmulhw, 0, 0, 1 AVX_INSTR pmullw, 0, 0, 1 AVX_INSTR pmulld, 0, 0, 1 AVX_INSTR pmuludq, 0, 0, 1 AVX_INSTR por, 0, 0, 1 AVX_INSTR psadbw, 0, 0, 1 AVX_INSTR pshufb, 0, 0, 0 AVX_INSTR pshufd AVX_INSTR pshufhw AVX_INSTR pshuflw AVX_INSTR psignb, 0, 0, 0 AVX_INSTR psignw, 0, 0, 0 AVX_INSTR psignd, 0, 0, 0 AVX_INSTR psllw, 0, 0, 0 AVX_INSTR pslld, 0, 0, 0 AVX_INSTR psllq, 0, 0, 0 AVX_INSTR pslldq, 0, 0, 0 AVX_INSTR psraw, 0, 0, 0 AVX_INSTR psrad, 0, 0, 0 AVX_INSTR psrlw, 0, 0, 0 AVX_INSTR psrld, 0, 0, 0 AVX_INSTR psrlq, 0, 0, 0 AVX_INSTR psrldq, 0, 0, 0 AVX_INSTR psubb, 0, 0, 0 AVX_INSTR psubw, 0, 0, 0 AVX_INSTR psubd, 0, 0, 0 AVX_INSTR psubq, 0, 0, 0 AVX_INSTR psubsb, 0, 0, 0 AVX_INSTR psubsw, 0, 0, 0 AVX_INSTR psubusb, 0, 0, 0 AVX_INSTR psubusw, 0, 0, 0 AVX_INSTR ptest AVX_INSTR punpckhbw, 0, 0, 0 AVX_INSTR punpckhwd, 0, 0, 0 AVX_INSTR punpckhdq, 0, 0, 0 AVX_INSTR punpckhqdq, 0, 0, 0 AVX_INSTR punpcklbw, 0, 0, 0 AVX_INSTR punpcklwd, 0, 0, 0 AVX_INSTR punpckldq, 0, 0, 0 AVX_INSTR punpcklqdq, 0, 0, 0 AVX_INSTR pxor, 0, 0, 1 AVX_INSTR rcpps, 1, 0, 0 AVX_INSTR rcpss, 1, 0, 0 AVX_INSTR roundpd AVX_INSTR roundps AVX_INSTR roundsd AVX_INSTR roundss AVX_INSTR rsqrtps, 1, 0, 0 AVX_INSTR rsqrtss, 1, 0, 0 AVX_INSTR shufpd, 1, 1, 0 AVX_INSTR shufps, 1, 1, 0 AVX_INSTR sqrtpd, 1, 0, 0 AVX_INSTR sqrtps, 1, 0, 0 AVX_INSTR sqrtsd, 1, 0, 0 AVX_INSTR sqrtss, 1, 0, 0 AVX_INSTR stmxcsr AVX_INSTR subpd, 1, 0, 0 AVX_INSTR subps, 1, 0, 0 AVX_INSTR subsd, 1, 0, 0 AVX_INSTR subss, 1, 0, 0 AVX_INSTR ucomisd AVX_INSTR ucomiss AVX_INSTR unpckhpd, 1, 0, 0 AVX_INSTR unpckhps, 1, 0, 0 AVX_INSTR unpcklpd, 1, 0, 0 AVX_INSTR unpcklps, 1, 0, 0 AVX_INSTR xorpd, 1, 0, 1 AVX_INSTR xorps, 1, 0, 1 ; 3DNow instructions, for sharing code between AVX, SSE and 3DN AVX_INSTR pfadd, 1, 0, 1 AVX_INSTR pfsub, 1, 0, 0 AVX_INSTR pfmul, 1, 0, 1 ; base-4 constants for shuffles %assign i 0 %rep 256 %assign j ((i>>6)&3)*1000 + ((i>>4)&3)*100 + ((i>>2)&3)*10 + (i&3) %if j < 10 CAT_XDEFINE q000, j, i %elif j < 100 CAT_XDEFINE q00, j, i %elif j < 1000 CAT_XDEFINE q0, j, i %else CAT_XDEFINE q, j, i %endif %assign i i+1 %endrep %undef i %undef j %macro FMA_INSTR 3 %macro %1 4-7 %1, %2, %3 %if cpuflag(xop) v%5 %1, %2, %3, %4 %else %6 %1, %2, %3 %7 %1, %4 %endif %endmacro %endmacro FMA_INSTR pmacsdd, pmulld, paddd FMA_INSTR pmacsww, pmullw, paddw FMA_INSTR pmadcswd, pmaddwd, paddd ; convert FMA4 to FMA3 if possible %macro FMA4_INSTR 4 %macro %1 4-8 %1, %2, %3, %4 %if cpuflag(fma4) v%5 %1, %2, %3, %4 %elifidn %1, %2 v%6 %1, %4, %3 ; %1 = %1 * %3 + %4 %elifidn %1, %3 v%7 %1, %2, %4 ; %1 = %2 * %1 + %4 %elifidn %1, %4 v%8 %1, %2, %3 ; %1 = %2 * %3 + %1 %else %error fma3 emulation of ``%5 %1, %2, %3, %4'' is not supported %endif %endmacro %endmacro FMA4_INSTR fmaddpd, fmadd132pd, fmadd213pd, fmadd231pd FMA4_INSTR fmaddps, fmadd132ps, fmadd213ps, fmadd231ps FMA4_INSTR fmaddsd, fmadd132sd, fmadd213sd, fmadd231sd FMA4_INSTR fmaddss, fmadd132ss, fmadd213ss, fmadd231ss FMA4_INSTR fmaddsubpd, fmaddsub132pd, fmaddsub213pd, fmaddsub231pd FMA4_INSTR fmaddsubps, fmaddsub132ps, fmaddsub213ps, fmaddsub231ps FMA4_INSTR fmsubaddpd, fmsubadd132pd, fmsubadd213pd, fmsubadd231pd FMA4_INSTR fmsubaddps, fmsubadd132ps, fmsubadd213ps, fmsubadd231ps FMA4_INSTR fmsubpd, fmsub132pd, fmsub213pd, fmsub231pd FMA4_INSTR fmsubps, fmsub132ps, fmsub213ps, fmsub231ps FMA4_INSTR fmsubsd, fmsub132sd, fmsub213sd, fmsub231sd FMA4_INSTR fmsubss, fmsub132ss, fmsub213ss, fmsub231ss FMA4_INSTR fnmaddpd, fnmadd132pd, fnmadd213pd, fnmadd231pd FMA4_INSTR fnmaddps, fnmadd132ps, fnmadd213ps, fnmadd231ps FMA4_INSTR fnmaddsd, fnmadd132sd, fnmadd213sd, fnmadd231sd FMA4_INSTR fnmaddss, fnmadd132ss, fnmadd213ss, fnmadd231ss FMA4_INSTR fnmsubpd, fnmsub132pd, fnmsub213pd, fnmsub231pd FMA4_INSTR fnmsubps, fnmsub132ps, fnmsub213ps, fnmsub231ps FMA4_INSTR fnmsubsd, fnmsub132sd, fnmsub213sd, fnmsub231sd FMA4_INSTR fnmsubss, fnmsub132ss, fnmsub213ss, fnmsub231ss ; workaround: vpbroadcastq is broken in x86_32 due to a yasm bug %if ARCH_X86_64 == 0 %macro vpbroadcastq 2 %if sizeof%1 == 16 movddup %1, %2 %else vbroadcastsd %1, %2 %endif %endmacro %endif
; float lgamma(float x) SECTION code_clib SECTION code_fp_math48 PUBLIC cm48_sdcciy_lgamma EXTERN cm48_sdcciy_lgamma_fastcall cm48_sdcciy_lgamma: pop af pop hl pop de push de push hl push af jp cm48_sdcciy_lgamma_fastcall
; A011877: [ n(n-1)/24 ]. ; 0,0,0,0,0,0,1,1,2,3,3,4,5,6,7,8,10,11,12,14,15,17,19,21,23,25,27,29,31,33,36,38,41,44,46,49,52,55,58,61,65,68,71,75,78,82,86,90,94,98,102,106,110,114,119,123,128,133,137,142,147,152,157,162,168,173,178,184,189 bin $0,2 div $0,12
.include "defaults_mod.asm" table_file_jp equ "exe5-utf8.tbl" table_file_en equ "bn5-utf8.tbl" game_code_len equ 3 game_code equ 0x4252424A // BRBJ game_code_2 equ 0x42524245 // BRBE game_code_3 equ 0x42524250 // BRBP card_type equ 1 card_id equ 78 card_no equ "078" card_sub equ "Mod Card 078" card_sub_x equ 64 card_desc_len equ 2 card_desc_1 equ "Drixol" card_desc_2 equ "17MB" card_desc_3 equ "" card_name_jp_full equ "ドリクロール" card_name_jp_game equ "ドリクロール" card_name_en_full equ "Drixol" card_name_en_game equ "Drixol" card_address equ "" card_address_id equ 0 card_bug equ 0 card_wrote_en equ "" card_wrote_jp equ ""
; A021953: Decimal expansion of 1/949. ; Submitted by Jamie Morken(s4.) ; 0,0,1,0,5,3,7,4,0,7,7,9,7,6,8,1,7,7,0,2,8,4,5,1,0,0,1,0,5,3,7,4,0,7,7,9,7,6,8,1,7,7,0,2,8,4,5,1,0,0,1,0,5,3,7,4,0,7,7,9,7,6,8,1,7,7,0,2,8,4,5,1,0,0,1,0,5,3,7,4,0,7,7,9,7,6,8,1,7,7,0,2,8,4,5,1,0,0,1 add $0,1 mov $2,10 pow $2,$0 div $2,949 mov $0,$2 mod $0,10
/** * GLOBALS["default.engine.frame"] = number; //default 100. * GLOBALS["default.net.open"] = bool; //default false. * GLOBALS["default.net.service"] = bool; //default false. * GLOBALS["default.net.service_ip"] = string; //default "". * GLOBALS["default.net.service_port"] = number; //default 0. * GLOBALS["default.net.conn_max"] = number; //default NET_CONNECTION_MAX. * GLOBALS["default.script.open"] = bool; //default false. * GLOBALS["default.script.rootpath"] = string; //default SCRIPT_ROOT_PATH. * GLOBALS["default.script.workpath"] = string; //default SCRIPT_WORK_PATH. * GLOBALS["default.script.bootstrap"] = string; //default "bootstrap.lua". * GLOBALS["default.script.type"] = number; //default pf_script::kTypeLua. * GLOBALS["default.cache.open"] = bool; //default fasle. * GLOBALS["default.cache.service"] = bool; //default fasle. * GLOBALS["default.cache.conf"] = string; //default "". * GLOBALS["default.cache.key_map"] = number; //default ID_INVALID. * GLOBALS["default.cache.recycle_map"] = number; //default ID_INVALID. * GLOBALS["default.cache.query_map"] = number; //default ID_INVALID. * GLOBALS["default.db.open"] = bool; //default fasle. * GLOBALS["default.db.type"] = number; //default kDBConnectorTypeODBC. * GLOBALS["default.db.server"] = string; //default "". * GLOBALS["default.db.user"] = string; //default "". * GLOBALS["default.db.password"] = string; //default "". **/ #include "main.h" #include "net.h" #include "packet/sayhello.h" #include "passgen.h" //The script reload function. void reload() { if (is_null(ENGINE_POINTER)) return; auto env = ENGINE_POINTER->get_script(); if (is_null(env)) return; auto task_queue = env->task_queue(); task_queue->enqueue([env] { env->reload("preload.lua"); }); } //The test engine main loop event 1. int32_t times = 0; void main_loop(pf_engine::Kernel &engine) { using namespace pf_cache; /** auto cache = ENGINE_POINTER->get_cache(); if (cache) { auto db = dynamic_cast<DBStore *>(cache->get_db_dirver()->store()); auto key_map = db->get_keymap(); for (size_t i = 0; i < 10; ++i) { std::string key{"t_user#"}; key += i; key_map->set(key.c_str(), "100000000"); } for (size_t i = 0; i < 10; ++i) { std::string key{"t_user#"}; key += i; key_map->remove(key.c_str()); } } **/ std::cout << "main_loop ..." << std::endl; ++times; if (times > 10) std::cout << "main_loop exited by 10 times" << std::endl; else engine.enqueue([&engine](){ main_loop(engine); }); } //The test engine main loop event 2. void main_loop1(pf_engine::Kernel &engine) { std::cout << "main_loop1 ..." << std::endl; ++times; if (times > 20) std::cout << "main_loop1 exited by 20 times" << std::endl; else engine.enqueue([&engine](){ main_loop1(engine); }); } //Net test. pf_net::connection::Basic *connector{nullptr}; void main_nconnect(pf_engine::Kernel &engine, pf_net::connection::manager::Connector &mconnector) { mconnector.tick(); if (is_null(connector)) { connector = mconnector.connect( "127.0.0.1", GLOBALS["default.net.service_port"].get<uint16_t>()); } else { static uint32_t last_time = 0; auto tickcount = TIME_MANAGER_POINTER->get_tickcount(); if (tickcount - last_time > 5000) { SayHello packet; packet.set_str("hello ..."); connector->send(&packet); last_time = tickcount; } } engine.enqueue([&engine, &mconnector](){ main_nconnect(engine, mconnector); }); } //DB test. void db_test(pf_engine::Kernel &engine) { auto db = engine.get_db(); if (is_null(db)) return; if (db->isready()) { pf_db::Query query; if (!query.init(db)) return; query.set_tablename("t_test"); query.select("*"); query.from(); query.limit(1); db_lock(db, db_auto_lock); if (query.query()) { pf_basic::io_cwarn("------------------------db---------------------------"); db_fetch_array_t fectch_array; query.fetcharray(fectch_array); pf_basic::io_cdebug("db_test keys: "); for (pf_basic::type::variable_t &key : fectch_array.keys) std::cout << key.c_str() << std::endl; pf_basic::io_cdebug("db_test values: "); for (pf_basic::type::variable_t &val : fectch_array.values) std::cout << val.c_str() << std::endl; pf_basic::io_cwarn("------------------------db---------------------------"); } } else { engine.enqueue([&engine](){ db_test(engine); }); } } int32_t main(int32_t argc, char * argv[]) { /* Base config. */ GLOBALS["app.debug"] = true; GLOBALS["app.name"] = "simple"; //Net. GLOBALS["default.net.open"] = true; GLOBALS["default.net.service"] = true; GLOBALS["default.net.service_port"] = 12306; //DB. GLOBALS["default.db.open"] = true; GLOBALS["default.db.server"] = "pf_test"; GLOBALS["default.db.user"] = "root"; GLOBALS["default.db.password"] = "mysql"; //Script. GLOBALS["default.script.open"] = true; GLOBALS["default.script.heartbeat"] = "heartbeat"; //Cache. GLOBALS["default.cache.open"] = true; GLOBALS["default.cache.key_map"] = 10001; GLOBALS["default.cache.recycle_map"] = 10002; GLOBALS["default.cache.query_map"] = 10003; GLOBALS["default.cache.service"] = true; GLOBALS["default.cache.conf"] = "config/cache.tab"; GLOBALS["default.cache.clear"] = true; /* engine. */ pf_engine::Kernel engine; pf_engine::Application app(&engine); /* command handler. */ app.register_commandhandler("--reload", "lua script reload.", reload); /* engine event. */ engine.enqueue([](){ std::cout << "main loop function1" << std::endl; }); engine.enqueue([&engine](){ main_loop(engine); }); engine.enqueue([&engine](){ main_loop1(engine); }); engine.enqueue([&engine](){ db_test(engine); }); /* net init. */ pf_net::connection::manager::Connector mconnector; init_net_packets(); mconnector.init(1); engine.enqueue([&engine, &mconnector](){ main_nconnect(engine, mconnector); }); char pass[1024]{0}; SimplyDecryptPassword(pass, "_eHJKA_UKMEMeNvR__ZOCLQjYUQjWQPE"); pf_basic::io_cdebug("pass: %s", pass); /* run */ app.run(argc, argv); return 0; }
# Copyright (C) 2001 Free Software Foundation, Inc. # Written By Nick Clifton # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2, or (at your option) any # later version. # # In addition to the permissions in the GNU General Public License, the # Free Software Foundation gives you unlimited permission to link the # compiled version of this file with other programs, and to distribute # those programs without any restriction coming from the use of this # file. (The General Public License restrictions do apply in other # respects; for example, they cover modification of the file, and # distribution when not linked into another program.) # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; see the file COPYING. If not, write to # the Free Software Foundation, 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # As a special exception, if you link this library with files # compiled with GCC to produce an executable, this does not cause # the resulting executable to be covered by the GNU General Public License. # This exception does not however invalidate any other reasons why # the executable file might be covered by the GNU General Public License. # # This file just makes sure that the .fini and .init sections do in # fact return. Users may put any desired instructions in those sections. # This file is the last thing linked into any executable. # Note - this macro is complimented by the FUNC_START macro # in crti.asm. If you change this macro you must also change # that macro match. # # Note - we do not try any fancy optimisations of the return # sequences here, it is just not worth it. Instead keep things # simple. Restore all the save resgisters, including the link # register and then perform the correct function return instruction. .macro FUNC_END #ifdef __thumb__ .thumb pop {r4, r5, r6, r7} pop {r3} mov lr, r3 #else .arm ldmdb fp, {r4, r5, r6, r7, r8, r9, sl, fp, sp, lr} #endif #if defined __THUMB_INTERWORK__ || defined __thumb__ bx lr #else #ifdef __APCS_26__ movs pc, lr #else mov pc, lr #endif #endif .endm .file "crtn.asm" .section ".init" ;; FUNC_END .section ".fini" ;; FUNC_END # end of crtn.asm
// Boost.Units - A C++ library for zero-overhead dimensional analysis and // unit/quantity manipulation and conversion // // Copyright (C) 2003-2008 Matthias Christian Schabel // Copyright (C) 2008 Steven Watanabe // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_UNITS_MEASUREMENT_HPP #define BOOST_UNITS_MEASUREMENT_HPP #include <cmath> #include <cstdlib> #include <iomanip> #include <iostream> #include <boost/io/ios_state.hpp> #include <boost/units/static_rational.hpp> namespace boost { namespace units { namespace sqr_namespace /**/ { template<class Y> Y sqr(Y val) { return val*val; } } // namespace using sqr_namespace::sqr; template<class Y> class measurement { public: typedef measurement<Y> this_type; typedef Y value_type; measurement(const value_type& val = value_type(), const value_type& err = value_type()) : value_(val), uncertainty_(std::abs(err)) { } measurement(const this_type& source) : value_(source.value_), uncertainty_(source.uncertainty_) { } //~measurement() { } this_type& operator=(const this_type& source) { if (this == &source) return *this; value_ = source.value_; uncertainty_ = source.uncertainty_; return *this; } operator value_type() const { return value_; } value_type value() const { return value_; } value_type uncertainty() const { return uncertainty_; } value_type lower_bound() const { return value_-uncertainty_; } value_type upper_bound() const { return value_+uncertainty_; } this_type& operator+=(const value_type& val) { value_ += val; return *this; } this_type& operator-=(const value_type& val) { value_ -= val; return *this; } this_type& operator*=(const value_type& val) { value_ *= val; uncertainty_ *= val; return *this; } this_type& operator/=(const value_type& val) { value_ /= val; uncertainty_ /= val; return *this; } this_type& operator+=(const this_type& /*source*/); this_type& operator-=(const this_type& /*source*/); this_type& operator*=(const this_type& /*source*/); this_type& operator/=(const this_type& /*source*/); private: value_type value_, uncertainty_; }; } } #if BOOST_UNITS_HAS_BOOST_TYPEOF BOOST_TYPEOF_REGISTER_TEMPLATE(boost::units::measurement, 1) #endif namespace boost { namespace units { template<class Y> inline measurement<Y>& measurement<Y>::operator+=(const this_type& source) { uncertainty_ = std::sqrt(sqr(uncertainty_)+sqr(source.uncertainty_)); value_ += source.value_; return *this; } template<class Y> inline measurement<Y>& measurement<Y>::operator-=(const this_type& source) { uncertainty_ = std::sqrt(sqr(uncertainty_)+sqr(source.uncertainty_)); value_ -= source.value_; return *this; } template<class Y> inline measurement<Y>& measurement<Y>::operator*=(const this_type& source) { uncertainty_ = (value_*source.value_)* std::sqrt(sqr(uncertainty_/value_)+ sqr(source.uncertainty_/source.value_)); value_ *= source.value_; return *this; } template<class Y> inline measurement<Y>& measurement<Y>::operator/=(const this_type& source) { uncertainty_ = (value_/source.value_)* std::sqrt(sqr(uncertainty_/value_)+ sqr(source.uncertainty_/source.value_)); value_ /= source.value_; return *this; } // value_type op measurement template<class Y> inline measurement<Y> operator+(Y lhs,const measurement<Y>& rhs) { return (measurement<Y>(lhs,Y(0))+=rhs); } template<class Y> inline measurement<Y> operator-(Y lhs,const measurement<Y>& rhs) { return (measurement<Y>(lhs,Y(0))-=rhs); } template<class Y> inline measurement<Y> operator*(Y lhs,const measurement<Y>& rhs) { return (measurement<Y>(lhs,Y(0))*=rhs); } template<class Y> inline measurement<Y> operator/(Y lhs,const measurement<Y>& rhs) { return (measurement<Y>(lhs,Y(0))/=rhs); } // measurement op value_type template<class Y> inline measurement<Y> operator+(const measurement<Y>& lhs,Y rhs) { return (measurement<Y>(lhs)+=measurement<Y>(rhs,Y(0))); } template<class Y> inline measurement<Y> operator-(const measurement<Y>& lhs,Y rhs) { return (measurement<Y>(lhs)-=measurement<Y>(rhs,Y(0))); } template<class Y> inline measurement<Y> operator*(const measurement<Y>& lhs,Y rhs) { return (measurement<Y>(lhs)*=measurement<Y>(rhs,Y(0))); } template<class Y> inline measurement<Y> operator/(const measurement<Y>& lhs,Y rhs) { return (measurement<Y>(lhs)/=measurement<Y>(rhs,Y(0))); } // measurement op measurement template<class Y> inline measurement<Y> operator+(const measurement<Y>& lhs,const measurement<Y>& rhs) { return (measurement<Y>(lhs)+=rhs); } template<class Y> inline measurement<Y> operator-(const measurement<Y>& lhs,const measurement<Y>& rhs) { return (measurement<Y>(lhs)-=rhs); } template<class Y> inline measurement<Y> operator*(const measurement<Y>& lhs,const measurement<Y>& rhs) { return (measurement<Y>(lhs)*=rhs); } template<class Y> inline measurement<Y> operator/(const measurement<Y>& lhs,const measurement<Y>& rhs) { return (measurement<Y>(lhs)/=rhs); } /// specialize power typeof helper template<class Y,long N,long D> struct power_typeof_helper<measurement<Y>,static_rational<N,D> > { typedef measurement< typename power_typeof_helper<Y,static_rational<N,D> >::type > type; static type value(const measurement<Y>& x) { const static_rational<N,D> rat; const Y m = Y(rat.numerator())/Y(rat.denominator()), newval = std::pow(x.value(),m), err = newval*std::sqrt(std::pow(m*x.uncertainty()/x.value(),2)); return type(newval,err); } }; /// specialize root typeof helper template<class Y,long N,long D> struct root_typeof_helper<measurement<Y>,static_rational<N,D> > { typedef measurement< typename root_typeof_helper<Y,static_rational<N,D> >::type > type; static type value(const measurement<Y>& x) { const static_rational<N,D> rat; const Y m = Y(rat.denominator())/Y(rat.numerator()), newval = std::pow(x.value(),m), err = newval*std::sqrt(std::pow(m*x.uncertainty()/x.value(),2)); return type(newval,err); } }; // stream output template<class Y> inline std::ostream& operator<<(std::ostream& os,const measurement<Y>& val) { boost::io::ios_precision_saver precision_saver(os); boost::io::ios_flags_saver flags_saver(os); os << val.value() << "(+/-" << val.uncertainty() << ")"; return os; } } // namespace units } // namespace boost #endif // BOOST_UNITS_MEASUREMENT_HPP
SafariZoneWest_Script: jp EnableAutoTextBoxDrawing SafariZoneWest_TextPointers: dw PickUpItemText dw PickUpItemText dw PickUpItemText dw PickUpItemText dw SafariZoneWestText5 dw SafariZoneWestText6 dw SafariZoneWestText7 dw SafariZoneWestText8 SafariZoneWestText5: text_far _SafariZoneWestText5 text_end SafariZoneWestText6: text_far _SafariZoneWestText6 text_end SafariZoneWestText7: text_far _SafariZoneWestText7 text_end SafariZoneWestText8: text_far _SafariZoneWestText8 text_end
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r9 push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x4a5e, %rsi lea addresses_D_ht+0x75ec, %rdi nop nop nop nop nop inc %rdx mov $2, %rcx rep movsq nop nop nop sub $58742, %r9 lea addresses_WT_ht+0x2f9e, %rsi lea addresses_UC_ht+0x1ca5e, %rdi cmp $62011, %r14 mov $99, %rcx rep movsq nop inc %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %r9 pop %r14 ret .global s_faulty_load s_faulty_load: push %r12 push %r15 push %r9 push %rbp push %rbx push %rdi push %rsi // Store lea addresses_normal+0x19a5e, %rbp nop nop nop nop xor $62941, %rsi mov $0x5152535455565758, %r9 movq %r9, %xmm1 movups %xmm1, (%rbp) nop nop nop nop xor $16400, %r12 // Store lea addresses_A+0xd0de, %rdi nop nop dec %r15 mov $0x5152535455565758, %rsi movq %rsi, (%rdi) nop nop nop cmp $2258, %r15 // Store lea addresses_UC+0x7a55, %rdi clflush (%rdi) add $48254, %r15 mov $0x5152535455565758, %rsi movq %rsi, %xmm0 movups %xmm0, (%rdi) nop nop nop dec %r9 // Faulty Load lea addresses_US+0x2a5e, %rbp clflush (%rbp) nop nop nop nop add $61668, %rbx movb (%rbp), %r12b lea oracles, %rbx and $0xff, %r12 shlq $12, %r12 mov (%rbx,%r12,1), %r12 pop %rsi pop %rdi pop %rbx pop %rbp pop %r9 pop %r15 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 10}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_A', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_US', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 10}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 1}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 0}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 10}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
;-----------------------------; ; FIBONACCI GENERATOR FOR PIC ; ; ; ; Por: Prof. Carlo Requiao ; ; 31/Jul/2020 ; ;-----------------------------; list p = 16f877a org 0x00 goto INICIO INICIO: movlw 0x05 ; cnt = 5 movwf 0x23 clrf 0x20 ; x0 = 0 clrf 0x21 ; x1 = 0 incf 0x21 ; x1 = 1 LOOP: movf 0x20,0 ; W = x0 addwf 0x21,0 ; W = W + x1 movwf 0x22 ; x2 = W movf 0x21,0 movwf 0x20 ; x0 = x1 movf 0x22,0 movwf 0x21 ; x1 = x2 decfsz 0x23 goto LOOP END
; A157444: a(n) = 1331*n - 209. ; 1122,2453,3784,5115,6446,7777,9108,10439,11770,13101,14432,15763,17094,18425,19756,21087,22418,23749,25080,26411,27742,29073,30404,31735,33066,34397,35728,37059,38390,39721,41052,42383,43714,45045,46376,47707,49038,50369,51700,53031,54362,55693,57024,58355,59686,61017,62348,63679,65010,66341,67672,69003,70334,71665,72996,74327,75658,76989,78320,79651,80982,82313,83644,84975,86306,87637,88968,90299,91630,92961,94292,95623,96954,98285,99616,100947,102278,103609,104940,106271,107602,108933,110264,111595,112926,114257,115588,116919,118250,119581,120912,122243,123574,124905,126236,127567,128898,130229,131560,132891 mul $0,1331 add $0,1122
// File doc/quickbook/oglplus/quickref/enums/framebuffer_target.hpp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/framebuffer_target.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2015 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // //[oglplus_enums_framebuffer_target namespace oglplus { enum class FramebufferTarget : GLenum { Draw = GL_DRAW_FRAMEBUFFER, Read = GL_READ_FRAMEBUFFER }; template <> __Range<FramebufferTarget> __EnumValueRange<FramebufferTarget>(void); __StrCRef __EnumValueName(FramebufferTarget); } // namespace oglplus //]
; A132720: Sequence is identical to its second differences in absolute values. ; 1,2,4,8,8,16,32,32,64,128,128,256,512,512,1024,2048,2048,4096,8192,8192,16384,32768,32768,65536,131072,131072,262144,524288,524288,1048576,2097152,2097152,4194304,8388608,8388608,16777216,33554432,33554432,67108864,134217728,134217728,268435456,536870912,536870912 mul $0,2 mov $1,1 mov $2,1 lpb $0,1 sub $0,$2 trn $0,1 mul $1,2 mov $2,2 lpe
%include "../UltimaPatcher.asm" %include "include/uw1.asm" %include "include/uw1-eop.asm" [bits 16] startPatch EXE_LENGTH, \ call eop enqueueGridCoords to flip drawing of geometry behind player %macro callEopEnqueueGridCoordsAt 2 startBlockAt %1, %2 callFromLoadModule byCallSiteEopDispatcher endBlockOfLength 5 %endmacro ; 16 calls to enqueueGridCoords in enqueueDrawBlock callEopEnqueueGridCoordsAt 19, 0x0F7E callEopEnqueueGridCoordsAt 19, 0x0F9F callEopEnqueueGridCoordsAt 19, 0x0FBE callEopEnqueueGridCoordsAt 19, 0x0FDA callEopEnqueueGridCoordsAt 19, 0x101C callEopEnqueueGridCoordsAt 19, 0x1033 callEopEnqueueGridCoordsAt 19, 0x104C callEopEnqueueGridCoordsAt 19, 0x1063 callEopEnqueueGridCoordsAt 19, 0x1218 callEopEnqueueGridCoordsAt 19, 0x1235 callEopEnqueueGridCoordsAt 19, 0x125E callEopEnqueueGridCoordsAt 19, 0x1286 callEopEnqueueGridCoordsAt 19, 0x1344 callEopEnqueueGridCoordsAt 19, 0x1362 callEopEnqueueGridCoordsAt 19, 0x1382 callEopEnqueueGridCoordsAt 19, 0x13A1 endPatch
@localsize 16, 1, 1 @buf 16 ; g[0] @invocationid(r0.x) ; r0.xyz @branchstack 1 cmps.u.gt p0.x, r0.x, 0 mov.u32u32 r1.x, 0x87654321 (rpt5)nop br !p0.x, #endif mov.u32u32 r1.x, 0x12345678 endif: (jp)(rpt5)nop stib.b.untyped.1d.u32.1.imm r1.x, r0.x, 0 end nop
// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -fsyntax-only -verify %s // The object declared in an exception-declaration or, if the // exception-declaration does not specify a name, a temporary (12.2) // is copy-initialized (8.5) from the exception object. // template<typename T> class X { T* ptr; public: X(const X<T> &) { int *ip = 0; ptr = ip; // expected-error{{assigning to 'float *' from incompatible type 'int *'}} } ~X() { float *fp = 0; ptr = fp; // expected-error{{assigning to 'int *' from incompatible type 'float *'}} } }; void f() { try { } catch (X<float>) { // expected-note{{instantiation}} // copy constructor } catch (X<int> xi) { // expected-note{{instantiation}} // destructor } } struct Abstract { virtual void f() = 0; // expected-note{{pure virtual}} }; void g() { try { } catch (Abstract) { // expected-error{{variable type 'Abstract' is an abstract class}} } }
BikeShop_h: db CLUB ; tileset db BIKE_SHOP_HEIGHT, BIKE_SHOP_WIDTH ; dimensions (y, x) dw BikeShopBlocks, BikeShopTextPointers, BikeShopScript ; blocks, texts, scripts db $00 ; connections dw BikeShopObject ; objects
; A054554: a(n) = 4n^2 - 10n + 7. ; 1,3,13,31,57,91,133,183,241,307,381,463,553,651,757,871,993,1123,1261,1407,1561,1723,1893,2071,2257,2451,2653,2863,3081,3307,3541,3783,4033,4291,4557,4831,5113,5403,5701,6007,6321,6643,6973,7311,7657,8011,8373,8743,9121,9507,9901,10303,10713,11131,11557,11991,12433,12883,13341,13807,14281,14763,15253,15751,16257,16771,17293,17823,18361,18907,19461,20023,20593,21171,21757,22351,22953,23563,24181,24807,25441,26083,26733,27391,28057,28731,29413,30103,30801,31507,32221,32943,33673,34411,35157,35911 mul $0,2 bin $0,2 mul $0,2 add $0,1
; CRT0 for the Mattel Aquarius ; ; Stefano Bodrato Dec. 2000 ; ; If an error occurs eg break we just drop back to BASIC ; ; $Id: aquarius_crt0.asm,v 1.8 2009/06/22 21:20:05 dom Exp $ ; MODULE aquarius_crt0 ;-------- ; Include zcc_opt.def to find out some info ;-------- INCLUDE "zcc_opt.def" ;-------- ; Some scope definitions ;-------- XREF _main ;main() is always external to crt0 code XDEF cleanup ;jp'd to by exit() XDEF l_dcal ;jp(hl) XDEF _std_seed ;Integer rand() seed XDEF _vfprintf ;jp to the printf() core XDEF exitsp ;atexit() variables XDEF exitcount XDEF __sgoioblk ;stdio info block XDEF heaplast ;Near malloc heap variables XDEF heapblocks XDEF base_graphics ;Graphical variables XDEF coords ;Current xy position XDEF snd_tick ;Sound variable ;;org 14768 ; Mattel relocating loader org 14712 ; Simpler loader start: ld (start1+1),sp ;Save entry stack ld hl,-64 add hl,sp ld sp,hl ld (exitsp),sp IF !DEFINED_nostreams IF DEFINED_ANSIstdio ; Set up the std* stuff so we can be called again ld hl,__sgoioblk+2 ld (hl),19 ;stdin ld hl,__sgoioblk+6 ld (hl),21 ;stdout ld hl,__sgoioblk+10 ld (hl),21 ;stderr ENDIF ENDIF call _main ;Call user program cleanup: ; ; Deallocate memory which has been allocated here! ; IF !DEFINED_nostreams IF DEFINED_ANSIstdio LIB closeall call closeall ENDIF ENDIF start1: ld sp,0 ;Restore stack to entry value ret l_dcal: jp (hl) ;Used for function pointer calls ;----------- ; Define the stdin/out/err area. For the z88 we have two models - the ; classic (kludgey) one and "ANSI" model ;----------- __sgoioblk: IF DEFINED_ANSIstdio INCLUDE "stdio_fp.asm" ELSE defw -11,-12,-10 ENDIF ;--------------------------------- ; Select which printf core we want ;--------------------------------- _vfprintf: IF DEFINED_floatstdio LIB vfprintf_fp jp vfprintf_fp ELSE IF DEFINED_complexstdio LIB vfprintf_comp jp vfprintf_comp ELSE IF DEFINED_ministdio LIB vfprintf_mini jp vfprintf_mini ENDIF ENDIF ENDIF ;----------- ; Now some variables ;----------- coords: defw 0 ; Current graphics xy coordinates base_graphics: defw $3028 ; Address of the Graphics map ; (text area-second line) _std_seed: defw 0 ; Seed for integer rand() routines exitsp: defw 0 ; Address of where the atexit() stack is exitcount: defb 0 ; How many routines on the atexit() stack heaplast: defw 0 ; Address of last block on heap heapblocks: defw 0 ; Number of blocks IF DEFINED_NEED1bitsound snd_tick: defb 0 ; Sound variable ENDIF defm "Small C+ Aquarius" ;Unnecessary file signature defb 0 ;----------------------- ; Floating point support ;----------------------- IF NEED_floatpack INCLUDE "float.asm" fp_seed: defb $80,$80,0,0,0,0 ;FP seed (unused ATM) extra: defs 6 ;FP register fa: defs 6 ;FP Accumulator fasign: defb 0 ;FP register ENDIF
; void SMS_loadPSGaidencompressedTiles(void *src, unsigned int tilefrom) SECTION code_clib SECTION code_SMSlib PUBLIC SMS_loadPSGaidencompressedTiles EXTERN SMS_loadPSGaidencompressedTiles_callee_0 SMS_loadPSGaidencompressedTiles: pop af pop hl pop de push de push hl push af jp SMS_loadPSGaidencompressedTiles_callee_0
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>vfork() -> str Invokes the syscall vfork. See 'man 2 vfork' for more information. Arguments: Returns: pid_t </%docstring> <%page args=""/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = [] can_pushstr_array = [] argument_names = [] argument_values = [] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_vfork']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* vfork(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
// Copyright 2017 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 "gin/gin_features.h" #include "base/metrics/field_trial_params.h" namespace features { // Enables optimization of JavaScript in V8. const base::Feature kV8OptimizeJavascript{"V8OptimizeJavascript", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables flushing of JS bytecode in V8. const base::Feature kV8FlushBytecode{"V8FlushBytecode", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables flushing of baseline code in V8. const base::Feature kV8FlushBaselineCode{"V8FlushBaselineCode", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables finalizing streaming JS compilations on a background thread. const base::Feature kV8OffThreadFinalization{"V8OffThreadFinalization", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables lazy feedback allocation in V8. const base::Feature kV8LazyFeedbackAllocation{"V8LazyFeedbackAllocation", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables concurrent inlining in TurboFan. const base::Feature kV8ConcurrentInlining{"V8ConcurrentInlining", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables per-context marking worklists in V8 GC. const base::Feature kV8PerContextMarkingWorklist{ "V8PerContextMarkingWorklist", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables flushing of the instruction cache for the embedded blob. const base::Feature kV8FlushEmbeddedBlobICache{ "V8FlushEmbeddedBlobICache", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables reduced number of concurrent marking tasks. const base::Feature kV8ReduceConcurrentMarkingTasks{ "V8ReduceConcurrentMarkingTasks", base::FEATURE_DISABLED_BY_DEFAULT}; // Disables reclaiming of unmodified wrappers objects. const base::Feature kV8NoReclaimUnmodifiedWrappers{ "V8NoReclaimUnmodifiedWrappers", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables W^X code memory protection in V8. // This is enabled in V8 by default. To test the performance impact, we are // going to disable this feature in a finch experiment. const base::Feature kV8CodeMemoryWriteProtection{ "V8CodeMemoryWriteProtection", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables fallback to a breadth-first regexp engine on excessive backtracking. const base::Feature kV8ExperimentalRegexpEngine{ "V8ExperimentalRegexpEngine", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables experimental Turboprop compiler. const base::Feature kV8Turboprop{"V8Turboprop", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables Sparkplug compiler. Note that this only sets the V8 flag when // manually overridden; otherwise it defers to whatever the V8 default is. const base::Feature kV8Sparkplug{"V8Sparkplug", base::FEATURE_ENABLED_BY_DEFAULT}; // Makes sure the experimental Sparkplug compiler is only enabled if short // builtin calls are enabled too. const base::Feature kV8SparkplugNeedsShortBuiltinCalls{ "V8SparkplugNeedsShortBuiltinCalls", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables short builtin calls feature. const base::Feature kV8ShortBuiltinCalls{"V8ShortBuiltinCalls", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables fast API calls in TurboFan. const base::Feature kV8TurboFastApiCalls{"V8TurboFastApiCalls", base::FEATURE_DISABLED_BY_DEFAULT}; // Artificially delays script execution. const base::Feature kV8ScriptAblation{"V8ScriptAblation", base::FEATURE_DISABLED_BY_DEFAULT}; const base::FeatureParam<int> kV8ScriptDelayOnceMs{&kV8ScriptAblation, "V8ScriptDelayOnceMs", 0}; const base::FeatureParam<int> kV8ScriptDelayMs{&kV8ScriptAblation, "V8ScriptDelayMs", 0}; const base::FeatureParam<double> kV8ScriptDelayFraction{ &kV8ScriptAblation, "V8ScriptDelayFraction", 0.0}; // Enables slow histograms that provide detailed information at increased // runtime overheads. const base::Feature kV8SlowHistograms{"V8SlowHistograms", base::FEATURE_DISABLED_BY_DEFAULT}; // Multiple finch experiments might use slow-histograms. We introduce // separate feature flags to circumvent finch limitations. const base::Feature kV8SlowHistogramsCodeMemoryWriteProtection{ "V8SlowHistogramsCodeMemoryWriteProtection", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kV8SlowHistogramsSparkplug{ "V8SlowHistogramsSparkplug", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kV8SlowHistogramsSparkplugAndroid{ "V8SlowHistogramsSparkplugAndroid", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kV8SlowHistogramsScriptAblation{ "V8SlowHistogramsScriptAblation", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables the V8 virtual memory cage. const base::Feature kV8VirtualMemoryCage { "V8VirtualMemoryCage", #if defined(V8_HEAP_SANDBOX) // The cage is required for the V8 Heap Sandbox. base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; } // namespace features
; A170377: Number of reduced words of length n in Coxeter group on 32 generators S_i with relations (S_i)^2 = (S_i S_j)^43 = I. ; 1,32,992,30752,953312,29552672,916132832,28400117792,880403651552,27292513198112,846067909141472,26228105183385632,813071260684954592,25205209081233592352,781361481518241362912,24222205927065482250272 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,31 lpe mov $0,$2 div $0,31
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r14 push %r8 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x432b, %r10 nop nop cmp $44460, %rbp and $0xffffffffffffffc0, %r10 vmovntdqa (%r10), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $0, %xmm3, %r8 nop nop nop nop nop sub $27647, %rbp lea addresses_D_ht+0x1218b, %r12 nop cmp $27515, %rbx mov $0x6162636465666768, %r10 movq %r10, %xmm4 movups %xmm4, (%r12) nop nop nop nop add %r10, %r10 lea addresses_WC_ht+0x6b8b, %r14 nop nop nop and %r10, %r10 mov $0x6162636465666768, %r8 movq %r8, %xmm3 movups %xmm3, (%r14) nop xor %rbx, %rbx lea addresses_normal_ht+0xb80b, %rsi lea addresses_WT_ht+0x1352b, %rdi nop nop nop nop xor %r8, %r8 mov $28, %rcx rep movsq inc %r10 lea addresses_WT_ht+0xf205, %rbp nop nop nop inc %r10 movups (%rbp), %xmm2 vpextrq $1, %xmm2, %r8 nop nop add $38274, %r12 lea addresses_A_ht+0x17b, %rsi lea addresses_UC_ht+0x1536b, %rdi nop nop nop nop nop add $44219, %r10 mov $38, %rcx rep movsq nop nop nop nop nop cmp $59206, %r14 lea addresses_normal_ht+0x15d1a, %rsi nop and %rbp, %rbp mov $0x6162636465666768, %r12 movq %r12, (%rsi) nop and %r12, %r12 lea addresses_normal_ht+0x7d0b, %rsi nop nop nop nop nop cmp %r12, %r12 movups (%rsi), %xmm2 vpextrq $1, %xmm2, %rbp nop nop nop nop add %r12, %r12 lea addresses_D_ht+0x1a2bb, %rsi lea addresses_normal_ht+0x13add, %rdi nop nop nop inc %r10 mov $74, %rcx rep movsb nop nop add $20469, %rbp pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r8 pop %r14 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r15 push %r9 push %rax push %rbp push %rdi // Store lea addresses_WC+0x1ee0b, %r14 nop nop inc %rbp mov $0x5152535455565758, %rdi movq %rdi, %xmm0 vmovups %ymm0, (%r14) nop nop nop nop nop add %rdi, %rdi // Store lea addresses_WC+0x11b1b, %rdi nop nop nop nop nop dec %r10 movw $0x5152, (%rdi) nop sub $52262, %r14 // Faulty Load mov $0x27edc000000098b, %rdi nop cmp $36928, %r15 mov (%rdi), %r10 lea oracles, %r9 and $0xff, %r10 shlq $12, %r10 mov (%r9,%r10,1), %r10 pop %rdi pop %rbp pop %rax pop %r9 pop %r15 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': True, 'same': False, 'congruent': 0, 'type': 'addresses_NC', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_WC', 'AVXalign': False, 'size': 32}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_WC', 'AVXalign': False, 'size': 2}} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_NC', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'NT': True, 'same': False, 'congruent': 4, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16}} {'src': {'same': False, 'congruent': 6, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_UC_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8}} {'src': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 4, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 0, 'type': 'addresses_normal_ht'}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
.text getMin: pushq %rbp movq %rsp, %rbp movq %rdi, -24(%rbp) movl %esi, -28(%rbp) movl $0, -4(%rbp) movss .FL0(%rip), %xmm0 movss %xmm0, -84(%rbp) movl $999999, -8(%rbp) jmp .L2 .L3: movl -4(%rbp), %eax movl -8(%rbp), %eax cmpl %eax, -8(%rbp) jge .L4 movl -4(%rbp), %eax cltq leaq 0(,%rax,4), %rdx movq -24(%rbp), %rax addq %rdx, %rax movl (%rax), %eax subl $1, %eax movl %eax, -8(%rbp) .L4: addl $1, -4(%rbp) .L2: movl -4(%rbp), %eax cmpl -28(%rbp), %eax jl .L3 movl -8(%rbp), %eax popq %rbp ret .globl main .type main, @function main: pushq %rbp movq %rsp, %rbp pushq %r15 pushq %r14 pushq %r13 pushq %r12 pushq %rbx subq $40, %rsp movq %rsp, %rax movq %rax, %rbx movl $3, -52(%rbp) movl $0, -80(%rbp) leaq -80(%rbp), %rax movq %rax, %rsi movl $.LC0, %edi movl $0, %eax call __isoc99_scanf movl -52(%rbp), %eax movslq %eax, %rdx subq $1, %rdx movq %rdx, -64(%rbp) movslq %eax, %rdx movq %rdx, %r14 movl $0, %r15d movslq %eax, %rdx movq %rdx, %r12 movl $0, %r13d cltq leaq 0(,%rax,4), %rdx movl $16, %eax subq $1, %rax addq %rdx, %rax movl $16, %ecx movl $0, %edx divq %rcx imulq $16, %rax, %rax subq %rax, %rsp movq %rsp, %rax addq $3, %rax shrq $2, %rax salq $2, %rax movq %rax, -72(%rbp) movq -72(%rbp), %rax movl $2, (%rax) movq -72(%rbp), %rax movl $0, 4(%rax) movq -72(%rbp), %rax movl $3, 8(%rax) movq -72(%rbp), %rax movl -52(%rbp), %edx movl %edx, %esi movq %rax, %rdi call getMin movl %eax, -76(%rbp) movl -76(%rbp), %eax movl %eax, %esi movl $.LC1, %edi movl $0, %eax call printf movl -80(%rbp), %eax movl %eax, %esi movl $.LC2, %edi movl $0, %eax call printf nop movq %rbx, %rsp leaq -40(%rbp), %rsp popq %rbx popq %r12 popq %r13 popq %r14 popq %r15 popq %rbp ret .LC0: .string "%d" .LC1: .string "%d\n" .LC2: .string "%d\n" .FL0: .long 1067030938
; A052794: E.g.f.: -x^5*log(1-x). ; 0,0,0,0,0,0,720,2520,13440,90720,725760,6652800,68428800,778377600,9686476800,130767436800,1902071808000,29640619008000,492490285056000,8688935743488000,162193467211776000,3193183885731840000,66117689869271040000,1436223152160276480000,32655179038591549440000,775560502166549299200000,19204355291743125504000000,494948611382652370944000000,13256014983117993934848000000,368406749739154248105984000000,10610114392487642345452339200000,316263025160689339143290880000000 mov $1,$0 seq $0,142 ; Factorial numbers: n! = 1*2*3*4*...*n (order of symmetric group S_n, number of permutations of n letters). sub $1,5 gcd $1,$0 mul $1,5 div $0,$1 div $0,24 mul $0,120
song364restored_pri equ 100 song364restored_rev equ 0 song364restored_mvl equ 127 song364restored_key equ 0 song364restored_tbs equ 1 song364restored_exg equ 0 song364restored_cmp equ 1 .align 4 ;**************** Track 1 (Midi-Chn.7) ****************; @song364restored_1: .byte KEYSH , song364restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 13 .byte PAN , c_v+45 .byte VOL , 94*song364restored_mvl/mxv .byte PAN , c_v+45 .byte VOL , 94*song364restored_mvl/mxv .byte 94*song364restored_mvl/mxv .byte PAN , c_v+45 .byte c_v+45 .byte VOL , 94*song364restored_mvl/mxv .byte 94*song364restored_mvl/mxv .byte PAN , c_v+45 .byte c_v+45 .byte VOL , 94*song364restored_mvl/mxv .byte BEND , c_v-1 .byte W14 .byte c_v-1 .byte N01 , As4 , v100 .byte W02 .byte BEND , c_v-1 .byte N01 , An4 .byte W03 .byte BEND , c_v-1 .byte N01 , Gn4 .byte W02 .byte BEND , c_v-1 .byte N01 , Fs4 .byte W02 .byte VOL , 82*song364restored_mvl/mxv .byte PAN , c_v+52 .byte W01 .byte BEND , c_v-1 .byte N01 , Fn4 .byte W02 .byte En4 .byte W02 .byte Dn4 .byte W03 .byte Cs4 .byte W02 .byte Bn3 .byte W02 .byte VOL , 100*song364restored_mvl/mxv .byte PAN , c_v+49 .byte W01 .byte BEND , c_v-1 .byte N01 , Cn5 .byte W02 .byte Bn4 .byte W02 .byte An4 .byte W03 .byte BEND , c_v-1 .byte N01 , Gn4 .byte W02 .byte BEND , c_v-1 .byte N01 , Fs4 .byte W02 .byte VOL , 63*song364restored_mvl/mxv .byte PAN , c_v+63 .byte W01 .byte N01 , Gs4 .byte W02 .byte BEND , c_v-1 .byte N01 , Gn4 .byte W02 .byte BEND , c_v-1 .byte N01 , Fs4 .byte W03 .byte BEND , c_v-1 .byte N01 , En4 .byte W01 .byte VOL , 85*song364restored_mvl/mxv .byte PAN , c_v+51 .byte W01 .byte N01 , Ds4 .byte W03 .byte Dn4 .byte W02 .byte Cs4 .byte W02 .byte Bn3 .byte W03 .byte BEND , c_v-1 .byte N01 , An3 .byte W02 .byte BEND , c_v-1 .byte N01 , As4 .byte W03 .byte BEND , c_v-1 .byte N01 , An4 .byte W02 .byte BEND , c_v-1 .byte N01 , Gn4 .byte W02 .byte BEND , c_v-1 .byte N01 , Fs4 .byte W02 .byte VOL , 82*song364restored_mvl/mxv .byte PAN , c_v+52 .byte W01 .byte BEND , c_v-1 .byte N01 , Fn4 .byte W02 .byte En4 .byte W03 .byte Dn4 .byte W02 .byte Cs4 .byte W02 .byte Bn3 .byte W02 .byte VOL , 100*song364restored_mvl/mxv .byte PAN , c_v+49 .byte W01 .byte BEND , c_v-1 .byte N01 , Cn5 .byte W02 .byte Bn4 .byte W03 ; 001 ---------------------------------------- .byte An4 .byte W02 .byte BEND , c_v-1 .byte N01 , Gn4 .byte W02 .byte BEND , c_v-1 .byte N01 , Fs4 .byte W02 .byte VOL , 63*song364restored_mvl/mxv .byte PAN , c_v+63 .byte W01 .byte N01 , Gs4 .byte W02 .byte BEND , c_v-1 .byte N01 , Gn4 .byte W03 .byte BEND , c_v-1 .byte N01 , Fs4 .byte W02 .byte BEND , c_v-1 .byte N01 , En4 .byte W02 .byte VOL , 85*song364restored_mvl/mxv .byte PAN , c_v+51 .byte N01 , Ds4 .byte W03 .byte Dn4 .byte W02 .byte Cs4 .byte W03 .byte Bn3 .byte W02 .byte BEND , c_v-1 .byte N01 , An3 .byte W02 .byte VOL , 92*song364restored_mvl/mxv .byte PAN , c_v+46 .byte W66 .byte W01 .byte VOL , 94*song364restored_mvl/mxv .byte PAN , c_v+45 .byte W01 ; 002 ---------------------------------------- .byte VOICE , 13 .byte PAN , c_v+46 .byte VOL , 92*song364restored_mvl/mxv .byte PAN , c_v+46 .byte VOL , 92*song364restored_mvl/mxv .byte BEND , c_v-1 .byte FINE ;**************** Track 2 (Midi-Chn.8) ****************; @song364restored_2: .byte KEYSH , song364restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 13 .byte PAN , c_v-20 .byte VOL , 95*song364restored_mvl/mxv .byte PAN , c_v-20 .byte VOL , 95*song364restored_mvl/mxv .byte 95*song364restored_mvl/mxv .byte PAN , c_v-20 .byte c_v-20 .byte VOL , 95*song364restored_mvl/mxv .byte 95*song364restored_mvl/mxv .byte PAN , c_v-20 .byte c_v-20 .byte VOL , 95*song364restored_mvl/mxv .byte BEND , c_v+0 .byte N01 , An4 , v100 .byte W02 .byte Gs4 .byte W02 .byte Fs4 .byte W03 .byte Fn4 .byte W01 .byte VOL , 85*song364restored_mvl/mxv .byte PAN , c_v-25 .byte W01 .byte N01 , En4 .byte W03 .byte Ds4 .byte W02 .byte Cs4 .byte W02 .byte Cn4 .byte W03 .byte As3 .byte W01 .byte VOL , 104*song364restored_mvl/mxv .byte PAN , c_v-20 .byte W01 .byte N01 , Bn4 .byte W03 .byte As4 .byte W02 .byte Gs4 .byte W02 .byte Fs4 .byte W03 .byte Fn4 .byte W01 .byte VOL , 73*song364restored_mvl/mxv .byte PAN , c_v-21 .byte W01 .byte N01 , Gn4 .byte W03 .byte Fs4 .byte W02 .byte Fn4 .byte W02 .byte Ds4 .byte W02 .byte VOL , 90*song364restored_mvl/mxv .byte W01 .byte N01 , Dn4 .byte W02 .byte Cs4 .byte W03 .byte Cn4 .byte W02 .byte As3 .byte W02 .byte Gs3 .byte W03 .byte An4 .byte W02 .byte Gs4 .byte W03 .byte Fs4 .byte W02 .byte Fn4 .byte W02 .byte VOL , 85*song364restored_mvl/mxv .byte PAN , c_v-25 .byte N01 , En4 .byte W03 .byte Ds4 .byte W02 .byte Cs4 .byte W03 .byte Cn4 .byte W02 .byte As3 .byte W02 .byte VOL , 104*song364restored_mvl/mxv .byte PAN , c_v-20 .byte N01 , Bn4 .byte W03 .byte As4 .byte W02 .byte Gs4 .byte W03 .byte Fs4 .byte W02 .byte Fn4 .byte W02 .byte VOL , 73*song364restored_mvl/mxv .byte PAN , c_v-21 .byte N01 , Gn4 .byte W03 .byte Fs4 .byte W02 .byte Fn4 .byte W03 ; 001 ---------------------------------------- .byte Ds4 .byte W01 .byte VOL , 90*song364restored_mvl/mxv .byte W01 .byte N01 , Dn4 .byte W02 .byte Cs4 .byte W03 .byte Cn4 .byte W02 .byte As3 .byte W03 .byte Gs3 .byte W01 .byte VOL , 92*song364restored_mvl/mxv .byte PAN , c_v-44 .byte W80 .byte W02 .byte VOL , 95*song364restored_mvl/mxv .byte PAN , c_v-20 .byte BEND , c_v+0 .byte W01 ; 002 ---------------------------------------- .byte VOICE , 13 .byte PAN , c_v-44 .byte VOL , 92*song364restored_mvl/mxv .byte PAN , c_v-44 .byte VOL , 92*song364restored_mvl/mxv .byte BEND , c_v+0 .byte FINE ;******************************************************; .align 4 song364restored: .byte 2 ; NumTrks .byte 0 ; NumBlks .byte song364restored_pri ; Priority .byte song364restored_rev ; Reverb. //emit_clean_voicegroup_offset_for_song 364 .word 0x81071B4 //Voice Table .word @song364restored_1 .word @song364restored_2
aLine 0 nNew newNodePtr, {0:D} gNewVPtr temp gMoveNext temp, Root nMoveAbs newNodePtr, 1380, 435.455 aLine 1 gBne temp, null, 4 aLine 2 gMove Rear, newNodePtr Jmp 3 aLine 5 pSetPrev temp, newNodePtr aLine 7 pSetNext newNodePtr, temp aLine 8 pSetNext Root, newNodePtr aLine 9 pSetPrev newNodePtr, Root aLine 10 aStd gDelete newNodePtr gDelete temp Halt
BITS 64 pre_test: dec edi jnz near pre_test ; translates to a DWORD ; -- Test finished at this point -- rdtsc mov [rsi + 8], eax ; __TEST_SETTINGS.ts2_l mov [rsi + 12], edx ; __TEST_SETTINGS.ts2_h ret
; ============================================================================= ; BareMetal -- a 64-bit OS written in Assembly for x86-64 systems ; Copyright (C) 2008-2016 Return Infinity -- see LICENSE.TXT ; ; Initialization Includes ; ============================================================================= %include "init/64.asm" %include "init/hdd.asm" %include "init/net.asm" %include "init/pci.asm" ; ============================================================================= ; EOF
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2018-2020, The Regents of the University of California // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #include <cstdlib> #include <cmath> #include <cfloat> #include <iostream> #include "fft.h" #define REPLACE_FFT_PI 3.141592653589793238462L namespace gpl { FFT::FFT() : binDensity_(nullptr), electroPhi_(nullptr), electroForceX_(nullptr), electroForceY_(nullptr), binCntX_(0), binCntY_(0), binSizeX_(0), binSizeY_(0) {} FFT::FFT(int binCntX, int binCntY, int binSizeX, int binSizeY) : binCntX_(binCntX), binCntY_(binCntY), binSizeX_(binSizeX), binSizeY_(binSizeY) { init(); } FFT::~FFT() { using std::vector; for(int i=0; i<binCntX_; i++) { delete[] binDensity_[i]; delete[] electroPhi_[i]; delete[] electroForceX_[i]; delete[] electroForceY_[i]; } delete[] binDensity_; delete[] electroPhi_; delete[] electroForceX_; delete[] electroForceY_; csTable_.clear(); wx_.clear(); wxSquare_.clear(); wy_.clear(); wySquare_.clear(); workArea_.clear(); } void FFT::init() { binDensity_ = new float*[binCntX_]; electroPhi_ = new float*[binCntX_]; electroForceX_ = new float*[binCntX_]; electroForceY_ = new float*[binCntX_]; for(int i=0; i<binCntX_; i++) { binDensity_[i] = new float[binCntY_]; electroPhi_[i] = new float[binCntY_]; electroForceX_[i] = new float[binCntY_]; electroForceY_[i] = new float[binCntY_]; for(int j=0; j<binCntY_; j++) { binDensity_[i][j] = electroPhi_[i][j] = electroForceX_[i][j] = electroForceY_[i][j] = 0.0f; } } csTable_.resize( std::max(binCntX_, binCntY_) * 3 / 2, 0 ); wx_.resize( binCntX_, 0 ); wxSquare_.resize( binCntX_, 0); wy_.resize( binCntY_, 0 ); wySquare_.resize( binCntY_, 0 ); workArea_.resize( round(sqrt(std::max(binCntX_, binCntY_))) + 2, 0 ); for(int i=0; i<binCntX_; i++) { wx_[i] = REPLACE_FFT_PI * static_cast<float>(i) / static_cast<float>(binCntX_); wxSquare_[i] = wx_[i] * wx_[i]; } for(int i=0; i<binCntY_; i++) { wy_[i] = REPLACE_FFT_PI * static_cast<float>(i) / static_cast<float>(binCntY_) * static_cast<float>(binSizeY_) / static_cast<float>(binSizeX_); wySquare_[i] = wy_[i] * wy_[i]; } } void FFT::updateDensity(int x, int y, float density) { binDensity_[x][y] = density; } std::pair<float, float> FFT::getElectroForce(int x, int y) const { return std::make_pair( electroForceX_[x][y], electroForceY_[x][y]); } float FFT::getElectroPhi(int x, int y) const { return electroPhi_[x][y]; } using namespace std; void FFT::doFFT() { ddct2d(binCntX_, binCntY_, -1, binDensity_, NULL, (int*) &workArea_[0], (float*)&csTable_[0]); for(int i = 0; i < binCntX_; i++) { binDensity_[i][0] *= 0.5; } for(int i = 0; i < binCntY_; i++) { binDensity_[0][i] *= 0.5; } for(int i = 0; i < binCntX_; i++) { for(int j = 0; j < binCntY_; j++) { binDensity_[i][j] *= 4.0 / binCntX_ / binCntY_; } } for(int i = 0; i < binCntX_; i++) { float wx = wx_[i]; float wx2 = wxSquare_[i]; for(int j = 0; j < binCntY_; j++) { float wy = wy_[j]; float wy2 = wySquare_[j]; float density = binDensity_[i][j]; float phi = 0; float electroX = 0, electroY = 0; if(i == 0 && j == 0) { phi = electroX = electroY = 0.0f; } else { //////////// lutong // denom = // wx2 / 4.0 + // wy2 / 4.0 ; // a_phi = a_den / denom ; ////b_phi = 0 ; // -1.0 * b / denom ; ////a_ex = 0 ; // b_phi * wx ; // a_ex = a_phi * wx / 2.0 ; ////a_ey = 0 ; // b_phi * wy ; // a_ey = a_phi * wy / 2.0 ; /////////// phi = density / (wx2 + wy2); electroX = phi * wx; electroY = phi * wy; } electroPhi_[i][j] = phi; electroForceX_[i][j] = electroX; electroForceY_[i][j] = electroY; } } // Inverse DCT ddct2d(binCntX_, binCntY_, 1, electroPhi_, NULL, (int*) &workArea_[0], (float*) &csTable_[0]); ddsct2d(binCntX_, binCntY_, 1, electroForceX_, NULL, (int*) &workArea_[0], (float*) &csTable_[0]); ddcst2d(binCntX_, binCntY_, 1, electroForceY_, NULL, (int*) &workArea_[0], (float*) &csTable_[0]); } }
; ; ; Z88 Maths Routines ; ; C Interface for Small C+ Compiler ; ; 7/12/98 djm ;double sqrt(double) ;Number in FA.. INCLUDE "fpp.def" PUBLIC sqrt EXTERN fsetup EXTERN stkequ2 .sqrt call fsetup fpp(FP_SQR) jp stkequ2
; A238768: Number of n X 1 0..3 arrays with no element equal to the sum modulo 4 of elements to its left or elements above it. ; Submitted by Jamie Morken(s1) ; 3,6,14,32,72,164,372,844,1916,4348,9868,22396,50828,115356,261804,594172,1348492,3060444,6945772,15763644,35776076,81194908,184274348,418216316,949154828,2154136156,4888878444,11095460412,25181489612,57150167324,129704067372,294367381244,668075850636,1516218747868,3441105211628,7809694408636,17724342327628,40225941568156,91294015040684,207194582832252,470234496049932,1067211691795804,2422069849560172,5496962225251644,12475525307963596,28313589457587228,64258564524017708,145836794055119356 mov $3,1 mov $4,1 lpb $0 sub $0,1 mov $2,$1 add $1,$4 add $2,3 mov $4,$3 mul $4,2 add $1,$4 mov $3,$2 lpe mov $0,$1 add $0,3
AREA SBCS, CODE, READONLY ENTRY LDR R0,=0X40000000 LDR R10,=0X40000050 LDR R4, #32 LDR R5, [R0], #04 ; N (no. of numbers) LDR R2, [R0], #04 SUB R5, R5, #01 ; counter OUTER START MOVS R3, R2, LSL #01 BCC FINE BCS BREAK SUBS R4, R4, #01 BNE START FINE ADDS R0, R0, #01 CMP R3, #00 BNE START BEQ UP BREAK STR R0, [R10], #04 UP B UP END
; ; ; ; This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. ; ; Copyright 2007-2019 Broadcom Inc. All rights reserved. ; ; ; This is the default program for Greyhound SKUs: ; BCM53422 ; ; To start it, use the following commands from BCM: ; ; led load gh_cascade.hex ; led auto on ; led start ; ; Assume 1 LED per port for Link. And 2 bits stream per LED. ; Link-Down = Off (b'00) ; Link-Up = On (b'01) ; ; Totally 10 ports/LEDs will be outputed. ; ; Link up/down info cannot be derived from LINKEN or LINKUP, as the LED ; processor does not always have access to link status. This program ; assumes link status is kept current in bit 0 of RAM byte (0xA0 + portnum). ; Generally, a program running on the main CPU must update these ; locations on link change; see linkscan callback in ; $SDK/src/appl/diag/ledproc.c. ; ; ; Constants ; NUM_PORTS equ 10 MIN_PORT_0 equ 18 MAX_PORT_0 equ 26 MIN_PORT_1 equ 28 MAX_PORT_1 equ 28 ; ; LED process ; start: ld a, MIN_PORT_0 iter_sec0: cmp a, MAX_PORT_0+1 jnc iter_sec1 cmp a, MIN_PORT_0 jz iter_sec0_init jc iter_sec0_init jmp iter_sec0_start iter_sec0_init: ld a, MIN_PORT_0 ld b, MAX_PORT_0 ld (SEC_MAX), b iter_sec0_start: jmp iter_common iter_sec1: cmp a, MAX_PORT_1+1 jnc end cmp a, MIN_PORT_1 jz iter_sec1_init jc iter_sec1_init jmp iter_sec1_start iter_sec1_init: ld a, MIN_PORT_1 ld b, MAX_PORT_1 ld (SEC_MAX), b iter_sec1_start: jmp iter_common iter_common: port a ld (PORT_NUM), a call get_link ld a, (PORT_NUM) inc a ld b, (SEC_MAX) inc b cmp a, b jz iter_sec0 jmp iter_common end: send 2*NUM_PORTS ; ; get_link ; ; This routine finds the link status LED for a port. ; Link info is in bit 0 of the byte read from PORTDATA[port] ; Inputs: (PORT_NUM) ; Outputs: Carry flag set if link is up, clear if link is down. ; Destroys: a, b get_link: ld b, PORTDATA add b, (PORT_NUM) ld a, (b) tst a, 0 jc led_green jmp led_black ; ; led_green ; ; Outputs: Bits to the LED stream indicating ON ; led_green: push 0 pack push 1 pack ret ; ; led_black ; ; Outputs: Bits to the LED stream indicating OFF ; led_black: push 0 pack push 0 pack ret ; Variables (SDK software initializes LED memory from 0xA0-0xff to 0) PORTDATA equ 0xA0 PORT_NUM equ 0xE0 SEC_MAX equ 0xE1 ; Symbolic names for the bits of the port status fields RX equ 0x0 ; received packet TX equ 0x1 ; transmitted packet COLL equ 0x2 ; collision indicator SPEED_C equ 0x3 ; 100 Mbps SPEED_M equ 0x4 ; 1000 Mbps DUPLEX equ 0x5 ; half/full duplex FLOW equ 0x6 ; flow control capable LINKUP equ 0x7 ; link down/up status LINKEN equ 0x8 ; link disabled/enabled status ZERO equ 0xE ; always 0 ONE equ 0xF ; always 1
; A118649: Row sums for A106597. ; 1,2,5,12,30,74,184,456,1132,2808,6968,17288,42896,106432,264080,655232,1625760,4033824,10008704,24833536,61616832,152883328,379333248,941199488,2335298816,5794330112,14376858880,35671780352,88508618240 add $0,1 seq $0,52987 ; Expansion of (1-2x^2)/(1-2x-2x^2+2x^3). div $0,2
; A284403: Binary representation of the x-axis, from the left edge to the origin, of the n-th stage of growth of the two-dimensional cellular automaton defined by "Rule 913", based on the 5-celled von Neumann neighborhood. ; 1,0,101,1110,11111,111111,1111111,11111111,111111111,1111111111,11111111111,111111111111,1111111111111,11111111111111,111111111111111,1111111111111111,11111111111111111,111111111111111111,1111111111111111111,11111111111111111111,111111111111111111111,1111111111111111111111,11111111111111111111111,111111111111111111111111,1111111111111111111111111,11111111111111111111111111,111111111111111111111111111,1111111111111111111111111111,11111111111111111111111111111,111111111111111111111111111111 seq $0,283523 ; Decimal representation of the x-axis, from the left edge to the origin, of the n-th stage of growth of the two-dimensional cellular automaton defined by "Rule 913", based on the 5-celled von Neumann neighborhood. seq $0,7088 ; The binary numbers (or binary words, or binary vectors, or binary expansion of n): numbers written in base 2.
global test_case extern std.outdln section .text test_case: mov rax, 2 ; value call std.outdln ; print value ret
;; Copyright (c) Microsoft Corporation. All rights reserved. ;; Licensed under the MIT License. include ksamd64.inc extern __oe_dispatch_ocall:proc ;;============================================================================== ;; ;; void oe_enter_sim( ;; [IN] void* tcs, ;; [IN] void (*aep)(), ;; [IN] uint64_t arg1, ;; [IN] uint64_t arg2, ;; [OUT] uint64_t* arg3, ;; [OUT] uint64_t* arg4, ;; [OUT] oe_enclave_t* enclave); ;; ;; Registers: ;; RCX - tcs: thread control structure (extended) ;; RDX - aep: asynchronous execution procedure ;; R8 - arg1 ;; R9 - arg2 ;; [RBP+48] - arg3 ;; [RBP+56] - arg4 ;; ;; These registers may be destroyed across function calls: ;; RAX, RCX, RDX, R8, R9, R10, R11 ;; ;; These registers must be preserved across function calls: ;; RBX, RBP, RDI, RSI, RSP, R12, R13, R14, and R15 ;; ;;============================================================================== PARAMS_SPACE EQU 128 TCS EQU [rbp-8] AEP EQU [rbp-16] ARG1 EQU [rbp-24] ARG2 EQU [rbp-32] ARG3 EQU [rbp-40] ARG4 EQU [rbp-48] ENCLAVE EQU [rbp-56] ARG1OUT EQU [rbp-64] ARG2OUT EQU [rbp-72] CSSA EQU [rbp-80] STACKPTR EQU [rbp-88] TCS_u_main EQU 72 NESTED_ENTRY oe_enter_sim, _TEXT$00 END_PROLOGUE ;; Setup stack frame: push rbp mov rbp, rsp ;; Save parameters on stack for later reference: ;; TCS := [RBP-8] <- RCX ;; AEP := [RBP-16] <- RDX ;; ARG1 := [RBP-24] <- R8 ;; ARG2 := [RBP-32] <- R9 ;; ARG3 := [RBP-40] <- [RBP+48] ;; ARG4 := [RBP-48] <- [RBP+56] ;; ENCLAVE := [RBP-56] <- [RBP+64] ;; sub rsp, PARAMS_SPACE mov TCS, rcx mov AEP, rdx mov ARG1, r8 mov ARG2, r9 mov rax, [rbp+48] mov ARG3, rax mov rax, [rbp+56] mov ARG4, rax mov rax, [rbp+64] mov ENCLAVE, rax ;; Load CSSA with zero initially: mov rax, 0 mov CSSA, rax ;; Save registers: push rbx push rdi push rsi push r12 push r13 push r14 push r15 call_start: ;; Save the stack pointer so enclave can use the stack. mov STACKPTR, rsp ;; Call start(RAX=CSSA, RBX=TCS, RCX=RETADDR, RDI=ARG1, RSI=ARG2) in enclave mov rax, CSSA mov rbx, TCS lea rcx, retaddr mov rdi, ARG1 mov rsi, ARG2 jmp qword ptr [rbx+TCS_u_main] retaddr: mov ARG1OUT, rdi mov ARG2OUT, rsi dispatch_ocall_sim: ;; RAX = __oe_dispatch_ocall( ;; RCX=arg1 ;; RDX=arg2 ;; R8=arg1_out ;; R9=arg2_out ;; [RSP+32]=TCS, ;; [RSP+40]=ENCLAVE); sub rsp, 56 mov rcx, ARG1OUT mov rdx, ARG2OUT lea r8, qword ptr ARG1OUT lea r9, qword ptr ARG2OUT mov rax, qword ptr TCS mov qword ptr [rsp+32], rax mov rax, qword ptr ENCLAVE mov qword ptr [rsp+40], rax call __oe_dispatch_ocall ;; RAX contains return value add rsp, 56 ;; Restore the stack pointer: mov rsp, STACKPTR ;; If this was not an OCALL, then return from ECALL. cmp rax, 0 jne return_from_ecall_sim ;; Prepare to reenter the enclave, calling start() mov rax, ARG1OUT mov ARG1, rax mov rax, ARG2OUT mov ARG2, rax jmp call_start return_from_ecall_sim: ;; Set ARG3 (out) mov rbx, ARG1OUT mov rax, qword ptr [rbp+48] mov qword ptr [rax], rbx ;; Set ARG4 (out) mov rbx, ARG2OUT mov rax, qword ptr [rbp+56] mov qword ptr [rax], rbx ;; Restore registers: pop r15 pop r14 pop r13 pop r12 pop rsi pop rdi pop rbx ;; Return parameters space: add rsp, PARAMS_SPACE ;; Restore stack frame: pop rbp BEGIN_EPILOGUE ret forever: jmp forever NESTED_END oe_enter_sim, _TEXT$00 END
;============================================================== ; WLA-DX banking setup ;============================================================== .memorymap defaultslot 0 slotsize $8000 slot 0 $0000 .endme .rombankmap bankstotal 1 banksize $8000 banks 1 .endro ;============================================================== ; SMS defines ;============================================================== .define VDPControl $bf .define VDPData $be .define VRAMWrite $4000 .define CRAMWrite $c000 ;============================================================== ; SDSC tag and SMS rom header ;============================================================== .sdsctag 1.2,"Hello World!","SMS programming tutorial program - enhanced version","Maxim" .bank 0 slot 0 .org $0000 ;============================================================== ; Boot section ;============================================================== di ; disable interrupts im 1 ; Interrupt mode 1 jp main ; jump to main program .org $0066 ;============================================================== ; Pause button handler ;============================================================== ; Do nothing retn ;============================================================== ; Main program ;============================================================== main: ld sp, $dff0 ;============================================================== ; Set up VDP registers ;============================================================== ld hl,VDPInitData ld b,VDPInitDataEnd-VDPInitData ld c,VDPControl otir ;============================================================== ; Clear VRAM ;============================================================== ; 1. Set VRAM write address to $0000 ld hl,$0000 | VRAMWrite call SetVDPAddress ; 2. Output 16KB of zeroes ld bc,$4000 ; Counter for 16KB of VRAM -: xor a out (VDPData),a ; Output to VRAM address, which is auto-incremented after each write dec bc ld a,b or c jr nz,- ;============================================================== ; Load palette ;============================================================== ; 1. Set VRAM write address to CRAM (palette) address 0 ld hl,$0000 | CRAMWrite call SetVDPAddress ; 2. Output colour data ld hl,PaletteData ld bc,PaletteDataEnd-PaletteData call CopyToVDP ;============================================================== ; Load tiles (font) ;============================================================== ; 1. Set VRAM write address to tile index 0 ld hl,$0000 | VRAMWrite call SetVDPAddress ; 2. Output tile data ld hl,FontData ; Location of tile data ld bc,FontDataSize ; Counter for number of bytes to write call CopyToVDP ;============================================================== ; Write text to name table ;============================================================== ; 1. Set VRAM write address to tilemap index 0 ld hl,$3800 | VRAMWrite call SetVDPAddress ; 2. Output tilemap data ld hl,Message -: ld a,(hl) cp $ff jr z,+ out (VDPData),a xor a out (VDPData),a inc hl jr - +: ; Turn screen on ld a,%01000000 ; ||||||`- Zoomed sprites -> 16x16 pixels ; |||||`-- Doubled sprites -> 2 tiles per sprite, 8x16 ; ||||`--- Mega Drive mode 5 enable ; |||`---- 30 row/240 line mode ; ||`----- 28 row/224 line mode ; |`------ VBlank interrupts ; `------- Enable display out (VDPControl),a ld a,$81 out (VDPControl),a ;============================================================== ; Plays the video ;============================================================== ; Infinite loop to stop program -: jr - ;============================================================== ; Helper functions ;============================================================== SetVDPAddress: ; Sets the VDP address ; Parameters: hl = address push af ld a,l out (VDPControl),a ld a,h out (VDPControl),a pop af ret CopyToVDP: ; Copies data to the VDP ; Parameters: hl = data address, bc = data length ; Affects: a, hl, bc -: ld a,(hl) ; Get data byte out (VDPData),a inc hl ; Point to next letter dec bc ld a,b or c jr nz,- ret ;============================================================== ; Data ;============================================================== .asciitable map " " to "~" = 0 .enda Message: .asc "Hello world!" .db $ff PaletteData: .db $00,$3f ; Black, white PaletteDataEnd: ; VDP initialisation data VDPInitData: .db $04,$80,$00,$81,$ff,$82,$ff,$85,$ff,$86,$ff,$87,$00,$88,$00,$89,$ff,$8a VDPInitDataEnd: FontData: .incbin "font.bin" fsize FontDataSize VideoData: .incbin "intro.bin"
SECTION code_fp_math32 PUBLIC l_f32_lt EXTERN m32_compare_callee .l_f32_lt call m32_compare_callee ret C dec hl ret
%ifdef CONFIG { "RegData": { "MM7": ["0x8000000000000000", "0x3FFE"] }, "MemoryRegions": { "0x100000000": "4096" } } %endif mov rdx, 0xe0000000 mov rax, 0x3ff0000000000000 ; 1.0 mov [rdx + 8 * 0], rax mov eax, 2 mov [rdx + 8 * 1], eax fld qword [rdx + 8 * 0] fidiv dword [rdx + 8 * 1] hlt
; A085478: Triangle read by rows: T(n, k) = binomial(n + k, 2*k). ; Submitted by Jamie Morken(s2) ; 1,1,1,1,3,1,1,6,5,1,1,10,15,7,1,1,15,35,28,9,1,1,21,70,84,45,11,1,1,28,126,210,165,66,13,1,1,36,210,462,495,286,91,15,1,1,45,330,924,1287,1001,455,120,17,1,1,55,495,1716,3003,3003,1820,680,153,19,1,1,66,715,3003,6435,8008,6188,3060,969,190,21,1,1,78,1001,5005,12870,19448,18564,11628,4845,1330,231,23,1,1,91,1365,8008,24310,43758,50388,38760,20349 lpb $0 mov $1,$0 add $2,1 sub $0,$2 lpe mul $0,2 bin $1,$0 mov $0,$1
org $15C72D ; Routine to hack ; First canal row skip 9 ; Skip to $15C736 CMP #$A4 ; Check if map is on row A4 skip 2 ; Skip to $15C73A LDA #$1A ; Load 1A (middle right sea coast) STA $7F5CD6,x ; Store new tile into 7F:65A4 LDA #$16 ; Load 16 (grass field) STA $7F5CD7,x ; Store new tile into 7F:65A4 LDA #$18 ; Load 18 (middle left sea coast) STA $7F5CD8,x ; Store new tile into 7F:65A4 nop #4 ; Delete code until $15C750 ; Second canal row skip 1 ; Skip to $15C751 CMP #$A5 ; Check if map is on row A4 skip 2 ; Skip to $15C755 LDA #$2A ; Load 1A (bottom right sea coast) STA $7F5CD6,x ; Store new tile into 7F:65A4 LDA #$16 ; Load 16 (grass field) STA $7F5CD7,x ; Store new tile into 7F:65A4 LDA #$18 ; Load 18 (middle left sea coast) STA $7F5CD8,x ; Store new tile into 7F:65A4 nop #8 ; Delete code until $15C769 skip 1 ; Skip to $15C770 nop #26 ; Delete code until $15C78B
#pragma once // Define VTUNE_PATH to use vtune for profiling // #define VTUNE_PATH "/opt/intel/oneapi/vtune/2021.2.0/bin64/vtune"
/* * * Copyright (c) 2021 Project CHIP 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. */ // THIS FILE IS GENERATED BY ZAP #include <cinttypes> #include <cstdint> #include "app/common/gen/af-structs.h" #include "app/common/gen/callback.h" #include "app/common/gen/ids/Clusters.h" #include "app/common/gen/ids/Commands.h" #include "app/util/util.h" #include <app/InteractionModelEngine.h> // Currently we need some work to keep compatible with ember lib. #include <app/util/ember-compatibility-functions.h> namespace chip { namespace app { namespace { void ReportCommandUnsupported(Command * aCommandObj, EndpointId aEndpointId, ClusterId aClusterId, CommandId aCommandId) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId aClusterId, aCommandId, (CommandPathFlags::kEndpointIdValid) }; aCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kNotFound, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::UnsupportedCommand); ChipLogError(Zcl, "Unknown command " ChipLogFormatMEI " for cluster " ChipLogFormatMEI, ChipLogValueMEI(aCommandId), ChipLogValueMEI(aClusterId)); } } // anonymous namespace // Cluster specific command parsing namespace clusters { namespace AdministratorCommissioning { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::AdministratorCommissioning::Commands::Ids::OpenBasicCommissioningWindow: { expectArgumentCount = 1; uint16_t CommissioningTimeout; bool argExists[1]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 1) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(CommissioningTimeout); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 1 == validArgumentCount) { wasHandled = emberAfAdministratorCommissioningClusterOpenBasicCommissioningWindowCallback(aEndpointId, apCommandObj, CommissioningTimeout); } break; } case Clusters::AdministratorCommissioning::Commands::Ids::OpenCommissioningWindow: { expectArgumentCount = 6; uint16_t CommissioningTimeout; chip::ByteSpan PAKEVerifier; uint16_t Discriminator; uint32_t Iterations; chip::ByteSpan Salt; uint16_t PasscodeID; bool argExists[6]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 6) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(CommissioningTimeout); break; case 1: TLVUnpackError = aDataTlv.Get(PAKEVerifier); break; case 2: TLVUnpackError = aDataTlv.Get(Discriminator); break; case 3: TLVUnpackError = aDataTlv.Get(Iterations); break; case 4: TLVUnpackError = aDataTlv.Get(Salt); break; case 5: TLVUnpackError = aDataTlv.Get(PasscodeID); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 6 == validArgumentCount) { wasHandled = emberAfAdministratorCommissioningClusterOpenCommissioningWindowCallback( aEndpointId, apCommandObj, CommissioningTimeout, PAKEVerifier, Discriminator, Iterations, Salt, PasscodeID); } break; } case Clusters::AdministratorCommissioning::Commands::Ids::RevokeCommissioning: { wasHandled = emberAfAdministratorCommissioningClusterRevokeCommissioningCallback(aEndpointId, apCommandObj); break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::AdministratorCommissioning::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::AdministratorCommissioning::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace AdministratorCommissioning namespace ColorControl { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::ColorControl::Commands::Ids::ColorLoopSet: { expectArgumentCount = 7; uint8_t updateFlags; uint8_t action; uint8_t direction; uint16_t time; uint16_t startHue; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[7]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 7) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(updateFlags); break; case 1: TLVUnpackError = aDataTlv.Get(action); break; case 2: TLVUnpackError = aDataTlv.Get(direction); break; case 3: TLVUnpackError = aDataTlv.Get(time); break; case 4: TLVUnpackError = aDataTlv.Get(startHue); break; case 5: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 6: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 7 == validArgumentCount) { wasHandled = emberAfColorControlClusterColorLoopSetCallback( aEndpointId, apCommandObj, updateFlags, action, direction, time, startHue, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::EnhancedMoveHue: { expectArgumentCount = 4; uint8_t moveMode; uint16_t rate; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(moveMode); break; case 1: TLVUnpackError = aDataTlv.Get(rate); break; case 2: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 3: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfColorControlClusterEnhancedMoveHueCallback(aEndpointId, apCommandObj, moveMode, rate, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::EnhancedMoveToHue: { expectArgumentCount = 5; uint16_t enhancedHue; uint8_t direction; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(enhancedHue); break; case 1: TLVUnpackError = aDataTlv.Get(direction); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterEnhancedMoveToHueCallback(aEndpointId, apCommandObj, enhancedHue, direction, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::EnhancedMoveToHueAndSaturation: { expectArgumentCount = 5; uint16_t enhancedHue; uint8_t saturation; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(enhancedHue); break; case 1: TLVUnpackError = aDataTlv.Get(saturation); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterEnhancedMoveToHueAndSaturationCallback( aEndpointId, apCommandObj, enhancedHue, saturation, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::EnhancedStepHue: { expectArgumentCount = 5; uint8_t stepMode; uint16_t stepSize; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(stepMode); break; case 1: TLVUnpackError = aDataTlv.Get(stepSize); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterEnhancedStepHueCallback(aEndpointId, apCommandObj, stepMode, stepSize, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveColor: { expectArgumentCount = 4; int16_t rateX; int16_t rateY; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(rateX); break; case 1: TLVUnpackError = aDataTlv.Get(rateY); break; case 2: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 3: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveColorCallback(aEndpointId, apCommandObj, rateX, rateY, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveColorTemperature: { expectArgumentCount = 6; uint8_t moveMode; uint16_t rate; uint16_t colorTemperatureMinimum; uint16_t colorTemperatureMaximum; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[6]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 6) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(moveMode); break; case 1: TLVUnpackError = aDataTlv.Get(rate); break; case 2: TLVUnpackError = aDataTlv.Get(colorTemperatureMinimum); break; case 3: TLVUnpackError = aDataTlv.Get(colorTemperatureMaximum); break; case 4: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 5: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 6 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveColorTemperatureCallback( aEndpointId, apCommandObj, moveMode, rate, colorTemperatureMinimum, colorTemperatureMaximum, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveHue: { expectArgumentCount = 4; uint8_t moveMode; uint8_t rate; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(moveMode); break; case 1: TLVUnpackError = aDataTlv.Get(rate); break; case 2: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 3: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveHueCallback(aEndpointId, apCommandObj, moveMode, rate, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveSaturation: { expectArgumentCount = 4; uint8_t moveMode; uint8_t rate; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(moveMode); break; case 1: TLVUnpackError = aDataTlv.Get(rate); break; case 2: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 3: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveSaturationCallback(aEndpointId, apCommandObj, moveMode, rate, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveToColor: { expectArgumentCount = 5; uint16_t colorX; uint16_t colorY; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(colorX); break; case 1: TLVUnpackError = aDataTlv.Get(colorY); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveToColorCallback(aEndpointId, apCommandObj, colorX, colorY, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveToColorTemperature: { expectArgumentCount = 4; uint16_t colorTemperature; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(colorTemperature); break; case 1: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 2: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 3: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveToColorTemperatureCallback(aEndpointId, apCommandObj, colorTemperature, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveToHue: { expectArgumentCount = 5; uint8_t hue; uint8_t direction; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(hue); break; case 1: TLVUnpackError = aDataTlv.Get(direction); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveToHueCallback(aEndpointId, apCommandObj, hue, direction, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveToHueAndSaturation: { expectArgumentCount = 5; uint8_t hue; uint8_t saturation; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(hue); break; case 1: TLVUnpackError = aDataTlv.Get(saturation); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveToHueAndSaturationCallback(aEndpointId, apCommandObj, hue, saturation, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::MoveToSaturation: { expectArgumentCount = 4; uint8_t saturation; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(saturation); break; case 1: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 2: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 3: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfColorControlClusterMoveToSaturationCallback(aEndpointId, apCommandObj, saturation, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::StepColor: { expectArgumentCount = 5; int16_t stepX; int16_t stepY; uint16_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(stepX); break; case 1: TLVUnpackError = aDataTlv.Get(stepY); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterStepColorCallback(aEndpointId, apCommandObj, stepX, stepY, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::StepColorTemperature: { expectArgumentCount = 7; uint8_t stepMode; uint16_t stepSize; uint16_t transitionTime; uint16_t colorTemperatureMinimum; uint16_t colorTemperatureMaximum; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[7]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 7) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(stepMode); break; case 1: TLVUnpackError = aDataTlv.Get(stepSize); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(colorTemperatureMinimum); break; case 4: TLVUnpackError = aDataTlv.Get(colorTemperatureMaximum); break; case 5: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 6: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 7 == validArgumentCount) { wasHandled = emberAfColorControlClusterStepColorTemperatureCallback( aEndpointId, apCommandObj, stepMode, stepSize, transitionTime, colorTemperatureMinimum, colorTemperatureMaximum, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::StepHue: { expectArgumentCount = 5; uint8_t stepMode; uint8_t stepSize; uint8_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(stepMode); break; case 1: TLVUnpackError = aDataTlv.Get(stepSize); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterStepHueCallback(aEndpointId, apCommandObj, stepMode, stepSize, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::StepSaturation: { expectArgumentCount = 5; uint8_t stepMode; uint8_t stepSize; uint8_t transitionTime; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(stepMode); break; case 1: TLVUnpackError = aDataTlv.Get(stepSize); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfColorControlClusterStepSaturationCallback(aEndpointId, apCommandObj, stepMode, stepSize, transitionTime, optionsMask, optionsOverride); } break; } case Clusters::ColorControl::Commands::Ids::StopMoveStep: { expectArgumentCount = 2; uint8_t optionsMask; uint8_t optionsOverride; bool argExists[2]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 2) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(optionsMask); break; case 1: TLVUnpackError = aDataTlv.Get(optionsOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 2 == validArgumentCount) { wasHandled = emberAfColorControlClusterStopMoveStepCallback(aEndpointId, apCommandObj, optionsMask, optionsOverride); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::ColorControl::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::ColorControl::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace ColorControl namespace DiagnosticLogs { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::DiagnosticLogs::Commands::Ids::RetrieveLogsRequest: { expectArgumentCount = 3; uint8_t intent; uint8_t requestedProtocol; chip::ByteSpan transferFileDesignator; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(intent); break; case 1: TLVUnpackError = aDataTlv.Get(requestedProtocol); break; case 2: TLVUnpackError = aDataTlv.Get(transferFileDesignator); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfDiagnosticLogsClusterRetrieveLogsRequestCallback(aEndpointId, apCommandObj, intent, requestedProtocol, transferFileDesignator); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::DiagnosticLogs::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::DiagnosticLogs::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace DiagnosticLogs namespace EthernetNetworkDiagnostics { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::EthernetNetworkDiagnostics::Commands::Ids::ResetCounts: { wasHandled = emberAfEthernetNetworkDiagnosticsClusterResetCountsCallback(aEndpointId, apCommandObj); break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::EthernetNetworkDiagnostics::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::EthernetNetworkDiagnostics::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace EthernetNetworkDiagnostics namespace GeneralCommissioning { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::GeneralCommissioning::Commands::Ids::ArmFailSafe: { expectArgumentCount = 3; uint16_t expiryLengthSeconds; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(expiryLengthSeconds); break; case 1: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 2: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfGeneralCommissioningClusterArmFailSafeCallback(aEndpointId, apCommandObj, expiryLengthSeconds, breadcrumb, timeoutMs); } break; } case Clusters::GeneralCommissioning::Commands::Ids::CommissioningComplete: { wasHandled = emberAfGeneralCommissioningClusterCommissioningCompleteCallback(aEndpointId, apCommandObj); break; } case Clusters::GeneralCommissioning::Commands::Ids::SetRegulatoryConfig: { expectArgumentCount = 4; uint8_t location; const uint8_t * countryCode; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(location); break; case 1: // TODO(#5542): The cluster handlers should accept a ByteSpan for all string types. TLVUnpackError = aDataTlv.GetDataPtr(countryCode); break; case 2: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 3: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfGeneralCommissioningClusterSetRegulatoryConfigCallback( aEndpointId, apCommandObj, location, const_cast<uint8_t *>(countryCode), breadcrumb, timeoutMs); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::GeneralCommissioning::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::GeneralCommissioning::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace GeneralCommissioning namespace LevelControl { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::LevelControl::Commands::Ids::Move: { expectArgumentCount = 4; uint8_t moveMode; uint8_t rate; uint8_t optionMask; uint8_t optionOverride; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(moveMode); break; case 1: TLVUnpackError = aDataTlv.Get(rate); break; case 2: TLVUnpackError = aDataTlv.Get(optionMask); break; case 3: TLVUnpackError = aDataTlv.Get(optionOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfLevelControlClusterMoveCallback(aEndpointId, apCommandObj, moveMode, rate, optionMask, optionOverride); } break; } case Clusters::LevelControl::Commands::Ids::MoveToLevel: { expectArgumentCount = 4; uint8_t level; uint16_t transitionTime; uint8_t optionMask; uint8_t optionOverride; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(level); break; case 1: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 2: TLVUnpackError = aDataTlv.Get(optionMask); break; case 3: TLVUnpackError = aDataTlv.Get(optionOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfLevelControlClusterMoveToLevelCallback(aEndpointId, apCommandObj, level, transitionTime, optionMask, optionOverride); } break; } case Clusters::LevelControl::Commands::Ids::MoveToLevelWithOnOff: { expectArgumentCount = 2; uint8_t level; uint16_t transitionTime; bool argExists[2]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 2) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(level); break; case 1: TLVUnpackError = aDataTlv.Get(transitionTime); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 2 == validArgumentCount) { wasHandled = emberAfLevelControlClusterMoveToLevelWithOnOffCallback(aEndpointId, apCommandObj, level, transitionTime); } break; } case Clusters::LevelControl::Commands::Ids::MoveWithOnOff: { expectArgumentCount = 2; uint8_t moveMode; uint8_t rate; bool argExists[2]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 2) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(moveMode); break; case 1: TLVUnpackError = aDataTlv.Get(rate); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 2 == validArgumentCount) { wasHandled = emberAfLevelControlClusterMoveWithOnOffCallback(aEndpointId, apCommandObj, moveMode, rate); } break; } case Clusters::LevelControl::Commands::Ids::Step: { expectArgumentCount = 5; uint8_t stepMode; uint8_t stepSize; uint16_t transitionTime; uint8_t optionMask; uint8_t optionOverride; bool argExists[5]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 5) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(stepMode); break; case 1: TLVUnpackError = aDataTlv.Get(stepSize); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; case 3: TLVUnpackError = aDataTlv.Get(optionMask); break; case 4: TLVUnpackError = aDataTlv.Get(optionOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 5 == validArgumentCount) { wasHandled = emberAfLevelControlClusterStepCallback(aEndpointId, apCommandObj, stepMode, stepSize, transitionTime, optionMask, optionOverride); } break; } case Clusters::LevelControl::Commands::Ids::StepWithOnOff: { expectArgumentCount = 3; uint8_t stepMode; uint8_t stepSize; uint16_t transitionTime; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(stepMode); break; case 1: TLVUnpackError = aDataTlv.Get(stepSize); break; case 2: TLVUnpackError = aDataTlv.Get(transitionTime); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfLevelControlClusterStepWithOnOffCallback(aEndpointId, apCommandObj, stepMode, stepSize, transitionTime); } break; } case Clusters::LevelControl::Commands::Ids::Stop: { expectArgumentCount = 2; uint8_t optionMask; uint8_t optionOverride; bool argExists[2]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 2) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(optionMask); break; case 1: TLVUnpackError = aDataTlv.Get(optionOverride); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 2 == validArgumentCount) { wasHandled = emberAfLevelControlClusterStopCallback(aEndpointId, apCommandObj, optionMask, optionOverride); } break; } case Clusters::LevelControl::Commands::Ids::StopWithOnOff: { wasHandled = emberAfLevelControlClusterStopWithOnOffCallback(aEndpointId, apCommandObj); break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::LevelControl::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::LevelControl::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace LevelControl namespace NetworkCommissioning { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::NetworkCommissioning::Commands::Ids::AddThreadNetwork: { expectArgumentCount = 3; chip::ByteSpan operationalDataset; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(operationalDataset); break; case 1: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 2: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterAddThreadNetworkCallback(aEndpointId, apCommandObj, operationalDataset, breadcrumb, timeoutMs); } break; } case Clusters::NetworkCommissioning::Commands::Ids::AddWiFiNetwork: { expectArgumentCount = 4; chip::ByteSpan ssid; chip::ByteSpan credentials; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(ssid); break; case 1: TLVUnpackError = aDataTlv.Get(credentials); break; case 2: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 3: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterAddWiFiNetworkCallback(aEndpointId, apCommandObj, ssid, credentials, breadcrumb, timeoutMs); } break; } case Clusters::NetworkCommissioning::Commands::Ids::DisableNetwork: { expectArgumentCount = 3; chip::ByteSpan networkID; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(networkID); break; case 1: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 2: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterDisableNetworkCallback(aEndpointId, apCommandObj, networkID, breadcrumb, timeoutMs); } break; } case Clusters::NetworkCommissioning::Commands::Ids::EnableNetwork: { expectArgumentCount = 3; chip::ByteSpan networkID; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(networkID); break; case 1: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 2: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterEnableNetworkCallback(aEndpointId, apCommandObj, networkID, breadcrumb, timeoutMs); } break; } case Clusters::NetworkCommissioning::Commands::Ids::GetLastNetworkCommissioningResult: { expectArgumentCount = 1; uint32_t timeoutMs; bool argExists[1]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 1) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 1 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterGetLastNetworkCommissioningResultCallback(aEndpointId, apCommandObj, timeoutMs); } break; } case Clusters::NetworkCommissioning::Commands::Ids::RemoveNetwork: { expectArgumentCount = 3; chip::ByteSpan NetworkID; uint64_t Breadcrumb; uint32_t TimeoutMs; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(NetworkID); break; case 1: TLVUnpackError = aDataTlv.Get(Breadcrumb); break; case 2: TLVUnpackError = aDataTlv.Get(TimeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterRemoveNetworkCallback(aEndpointId, apCommandObj, NetworkID, Breadcrumb, TimeoutMs); } break; } case Clusters::NetworkCommissioning::Commands::Ids::ScanNetworks: { expectArgumentCount = 3; chip::ByteSpan ssid; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(ssid); break; case 1: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 2: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterScanNetworksCallback(aEndpointId, apCommandObj, ssid, breadcrumb, timeoutMs); } break; } case Clusters::NetworkCommissioning::Commands::Ids::UpdateThreadNetwork: { expectArgumentCount = 3; chip::ByteSpan operationalDataset; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(operationalDataset); break; case 1: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 2: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterUpdateThreadNetworkCallback( aEndpointId, apCommandObj, operationalDataset, breadcrumb, timeoutMs); } break; } case Clusters::NetworkCommissioning::Commands::Ids::UpdateWiFiNetwork: { expectArgumentCount = 4; chip::ByteSpan ssid; chip::ByteSpan credentials; uint64_t breadcrumb; uint32_t timeoutMs; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(ssid); break; case 1: TLVUnpackError = aDataTlv.Get(credentials); break; case 2: TLVUnpackError = aDataTlv.Get(breadcrumb); break; case 3: TLVUnpackError = aDataTlv.Get(timeoutMs); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfNetworkCommissioningClusterUpdateWiFiNetworkCallback(aEndpointId, apCommandObj, ssid, credentials, breadcrumb, timeoutMs); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::NetworkCommissioning::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::NetworkCommissioning::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace NetworkCommissioning namespace OnOff { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::OnOff::Commands::Ids::Off: { wasHandled = emberAfOnOffClusterOffCallback(aEndpointId, apCommandObj); break; } case Clusters::OnOff::Commands::Ids::On: { wasHandled = emberAfOnOffClusterOnCallback(aEndpointId, apCommandObj); break; } case Clusters::OnOff::Commands::Ids::Toggle: { wasHandled = emberAfOnOffClusterToggleCallback(aEndpointId, apCommandObj); break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::OnOff::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::OnOff::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace OnOff namespace OperationalCredentials { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::OperationalCredentials::Commands::Ids::AddNOC: { expectArgumentCount = 4; chip::ByteSpan NOCArray; chip::ByteSpan IPKValue; chip::NodeId CaseAdminNode; uint16_t AdminVendorId; bool argExists[4]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 4) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(NOCArray); break; case 1: TLVUnpackError = aDataTlv.Get(IPKValue); break; case 2: TLVUnpackError = aDataTlv.Get(CaseAdminNode); break; case 3: TLVUnpackError = aDataTlv.Get(AdminVendorId); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 4 == validArgumentCount) { wasHandled = emberAfOperationalCredentialsClusterAddNOCCallback(aEndpointId, apCommandObj, NOCArray, IPKValue, CaseAdminNode, AdminVendorId); } break; } case Clusters::OperationalCredentials::Commands::Ids::AddTrustedRootCertificate: { expectArgumentCount = 1; chip::ByteSpan RootCertificate; bool argExists[1]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 1) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(RootCertificate); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 1 == validArgumentCount) { wasHandled = emberAfOperationalCredentialsClusterAddTrustedRootCertificateCallback(aEndpointId, apCommandObj, RootCertificate); } break; } case Clusters::OperationalCredentials::Commands::Ids::OpCSRRequest: { expectArgumentCount = 1; chip::ByteSpan CSRNonce; bool argExists[1]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 1) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(CSRNonce); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 1 == validArgumentCount) { wasHandled = emberAfOperationalCredentialsClusterOpCSRRequestCallback(aEndpointId, apCommandObj, CSRNonce); } break; } case Clusters::OperationalCredentials::Commands::Ids::RemoveAllFabrics: { wasHandled = emberAfOperationalCredentialsClusterRemoveAllFabricsCallback(aEndpointId, apCommandObj); break; } case Clusters::OperationalCredentials::Commands::Ids::RemoveFabric: { expectArgumentCount = 3; chip::FabricId FabricId; chip::NodeId NodeId; uint16_t VendorId; bool argExists[3]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 3) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(FabricId); break; case 1: TLVUnpackError = aDataTlv.Get(NodeId); break; case 2: TLVUnpackError = aDataTlv.Get(VendorId); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 3 == validArgumentCount) { wasHandled = emberAfOperationalCredentialsClusterRemoveFabricCallback(aEndpointId, apCommandObj, FabricId, NodeId, VendorId); } break; } case Clusters::OperationalCredentials::Commands::Ids::RemoveTrustedRootCertificate: { expectArgumentCount = 1; chip::ByteSpan TrustedRootIdentifier; bool argExists[1]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 1) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(TrustedRootIdentifier); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 1 == validArgumentCount) { wasHandled = emberAfOperationalCredentialsClusterRemoveTrustedRootCertificateCallback(aEndpointId, apCommandObj, TrustedRootIdentifier); } break; } case Clusters::OperationalCredentials::Commands::Ids::SetFabric: { expectArgumentCount = 1; uint16_t VendorId; bool argExists[1]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 1) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: TLVUnpackError = aDataTlv.Get(VendorId); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 1 == validArgumentCount) { wasHandled = emberAfOperationalCredentialsClusterSetFabricCallback(aEndpointId, apCommandObj, VendorId); } break; } case Clusters::OperationalCredentials::Commands::Ids::UpdateFabricLabel: { expectArgumentCount = 1; const uint8_t * Label; bool argExists[1]; memset(argExists, 0, sizeof argExists); while ((TLVError = aDataTlv.Next()) == CHIP_NO_ERROR) { // Since call to aDataTlv.Next() is CHIP_NO_ERROR, the read head always points to an element. // Skip this element if it is not a ContextTag, not consider it as an error if other values are valid. if (!TLV::IsContextTag(aDataTlv.GetTag())) { continue; } currentDecodeTagId = TLV::TagNumFromTag(aDataTlv.GetTag()); if (currentDecodeTagId < 1) { if (argExists[currentDecodeTagId]) { ChipLogProgress(Zcl, "Duplicate TLV tag %" PRIx32, TLV::TagNumFromTag(aDataTlv.GetTag())); TLVUnpackError = CHIP_ERROR_IM_MALFORMED_COMMAND_DATA_ELEMENT; break; } else { argExists[currentDecodeTagId] = true; validArgumentCount++; } } switch (currentDecodeTagId) { case 0: // TODO(#5542): The cluster handlers should accept a ByteSpan for all string types. TLVUnpackError = aDataTlv.GetDataPtr(Label); break; default: // Unsupported tag, ignore it. ChipLogProgress(Zcl, "Unknown TLV tag during processing."); break; } if (CHIP_NO_ERROR != TLVUnpackError) { break; } } if (CHIP_END_OF_TLV == TLVError) { // CHIP_END_OF_TLV means we have iterated all items in the structure, which is not a real error. TLVError = CHIP_NO_ERROR; } if (CHIP_NO_ERROR == TLVError && CHIP_NO_ERROR == TLVUnpackError && 1 == validArgumentCount) { wasHandled = emberAfOperationalCredentialsClusterUpdateFabricLabelCallback(aEndpointId, apCommandObj, const_cast<uint8_t *>(Label)); } break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::OperationalCredentials::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::OperationalCredentials::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace OperationalCredentials namespace SoftwareDiagnostics { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::SoftwareDiagnostics::Commands::Ids::ResetWatermarks: { wasHandled = emberAfSoftwareDiagnosticsClusterResetWatermarksCallback(aEndpointId, apCommandObj); break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::SoftwareDiagnostics::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::SoftwareDiagnostics::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace SoftwareDiagnostics namespace ThreadNetworkDiagnostics { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::ThreadNetworkDiagnostics::Commands::Ids::ResetCounts: { wasHandled = emberAfThreadNetworkDiagnosticsClusterResetCountsCallback(aEndpointId, apCommandObj); break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::ThreadNetworkDiagnostics::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::ThreadNetworkDiagnostics::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace ThreadNetworkDiagnostics namespace WiFiNetworkDiagnostics { void DispatchServerCommand(app::CommandHandler * apCommandObj, CommandId aCommandId, EndpointId aEndpointId, TLV::TLVReader & aDataTlv) { // We are using TLVUnpackError and TLVError here since both of them can be CHIP_END_OF_TLV // When TLVError is CHIP_END_OF_TLV, it means we have iterated all of the items, which is not a real error. // Any error value TLVUnpackError means we have received an illegal value. // The following variables are used for all commands to save code size. CHIP_ERROR TLVError = CHIP_NO_ERROR; CHIP_ERROR TLVUnpackError = CHIP_NO_ERROR; uint32_t validArgumentCount = 0; uint32_t expectArgumentCount = 0; uint32_t currentDecodeTagId = 0; bool wasHandled = false; { switch (aCommandId) { case Clusters::WiFiNetworkDiagnostics::Commands::Ids::ResetCounts: { wasHandled = emberAfWiFiNetworkDiagnosticsClusterResetCountsCallback(aEndpointId, apCommandObj); break; } default: { // Unrecognized command ID, error status will apply. ReportCommandUnsupported(apCommandObj, aEndpointId, Clusters::WiFiNetworkDiagnostics::Id, aCommandId); return; } } } if (CHIP_NO_ERROR != TLVError || CHIP_NO_ERROR != TLVUnpackError || expectArgumentCount != validArgumentCount || !wasHandled) { chip::app::CommandPathParams returnStatusParam = { aEndpointId, 0, // GroupId Clusters::WiFiNetworkDiagnostics::Id, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kBadRequest, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogProgress(Zcl, "Failed to dispatch command, %" PRIu32 "/%" PRIu32 " arguments parsed, TLVError=%" CHIP_ERROR_FORMAT ", UnpackError=%" CHIP_ERROR_FORMAT " (last decoded tag = %" PRIu32, validArgumentCount, expectArgumentCount, TLVError.Format(), TLVUnpackError.Format(), currentDecodeTagId); // A command with no arguments would never write currentDecodeTagId. If // progress logging is also disabled, it would look unused. Silence that // warning. UNUSED_VAR(currentDecodeTagId); } } } // namespace WiFiNetworkDiagnostics } // namespace clusters void DispatchSingleClusterCommand(chip::ClusterId aClusterId, chip::CommandId aCommandId, chip::EndpointId aEndPointId, chip::TLV::TLVReader & aReader, CommandHandler * apCommandObj) { ChipLogDetail(Zcl, "Received Cluster Command: Cluster=" ChipLogFormatMEI " Command=" ChipLogFormatMEI " Endpoint=%" PRIx16, ChipLogValueMEI(aClusterId), ChipLogValueMEI(aCommandId), aEndPointId); Compatibility::SetupEmberAfObjects(apCommandObj, aClusterId, aCommandId, aEndPointId); TLV::TLVType dataTlvType; SuccessOrExit(aReader.EnterContainer(dataTlvType)); switch (aClusterId) { case Clusters::AdministratorCommissioning::Id: clusters::AdministratorCommissioning::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::ColorControl::Id: clusters::ColorControl::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::DiagnosticLogs::Id: clusters::DiagnosticLogs::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::EthernetNetworkDiagnostics::Id: clusters::EthernetNetworkDiagnostics::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::GeneralCommissioning::Id: clusters::GeneralCommissioning::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::LevelControl::Id: clusters::LevelControl::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::NetworkCommissioning::Id: clusters::NetworkCommissioning::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::OnOff::Id: clusters::OnOff::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::OperationalCredentials::Id: clusters::OperationalCredentials::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::SoftwareDiagnostics::Id: clusters::SoftwareDiagnostics::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::ThreadNetworkDiagnostics::Id: clusters::ThreadNetworkDiagnostics::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; case Clusters::WiFiNetworkDiagnostics::Id: clusters::WiFiNetworkDiagnostics::DispatchServerCommand(apCommandObj, aCommandId, aEndPointId, aReader); break; default: // Unrecognized cluster ID, error status will apply. chip::app::CommandPathParams returnStatusParam = { aEndPointId, 0, // GroupId aClusterId, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kNotFound, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogError(Zcl, "Unknown cluster %" PRIx32, aClusterId); break; } exit: Compatibility::ResetEmberAfObjects(); aReader.ExitContainer(dataTlvType); } void DispatchSingleClusterResponseCommand(chip::ClusterId aClusterId, chip::CommandId aCommandId, chip::EndpointId aEndPointId, chip::TLV::TLVReader & aReader, CommandSender * apCommandObj) { ChipLogDetail(Zcl, "Received Cluster Command: Cluster=%" PRIx32 " Command=%" PRIx32 " Endpoint=%" PRIx16, aClusterId, aCommandId, aEndPointId); Compatibility::SetupEmberAfObjects(apCommandObj, aClusterId, aCommandId, aEndPointId); TLV::TLVType dataTlvType; SuccessOrExit(aReader.EnterContainer(dataTlvType)); switch (aClusterId) { default: // Unrecognized cluster ID, error status will apply. chip::app::CommandPathParams returnStatusParam = { aEndPointId, 0, // GroupId aClusterId, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid) }; apCommandObj->AddStatusCode(returnStatusParam, Protocols::SecureChannel::GeneralStatusCode::kNotFound, Protocols::SecureChannel::Id, Protocols::InteractionModel::ProtocolCode::InvalidCommand); ChipLogError(Zcl, "Unknown cluster " ChipLogFormatMEI, ChipLogValueMEI(aClusterId)); break; } exit: Compatibility::ResetEmberAfObjects(); aReader.ExitContainer(dataTlvType); } } // namespace app } // namespace chip
global _main default rel section .text _main: call print_question call read_input call print_answer call exit print_question: ; print question message mov rax, syscall_write ; write mov rdi, stdout ; stdout mov rsi, m_question ; msg text mov rdx, m_question.len ; msg length syscall ret print_answer: ; print response mensage mov rax, syscall_write ; write mov rdi, stdout ; stdout mov rsi, m_answer ; msg text mov rdx, m_answer.len ; msg length syscall ; print user input mov rax, syscall_write ; write mov rdi, stdout ; stdout mov rsi, num ; msg text mov rdx, 0xff ; msg length syscall ret read_input: ; read user input mov rax, syscall_read ; read mov rdi, stdin ; stdin mov rsi, num ; input bytes mov rdx, 0xff ; bytes to read syscall ret exit: ; exit program mov rax, syscall_exit ; exit mov rdi, 0 ; code 0 syscall section .data syscall_write equ 0x2000004 syscall_read equ 0x2000003 syscall_exit equ 0x2000001 stdout equ 1 stdin equ 0 m_question: db "What's your name? " .len equ $-m_question m_answer: db 0x0A, "Thank you for answering, " .len equ $-m_answer section .bss num resb 0xff
00000000 00000001 10100000 00000000 11010000 00000001 10100000 00000001 11010000 00000010 10110000 00000010 11010000 00000000 01010000 00000001 11010000 00000010 10110000 00000000 11010000 00000001 10000000 00011101 00100000 00000000 11100000 00001010 00000000 11101001 11100000 00011100
; A134142: List of quadruples: 2*(-4)^n, -3*(-4)^n, 2*(-4^n), 2*(-4)^n, n >= 0. ; 2,-3,2,2,-8,12,-8,-8,32,-48,32,32,-128,192,-128,-128,512,-768,512,512,-2048,3072,-2048,-2048,8192,-12288,8192,8192,-32768,49152,-32768,-32768,131072,-196608,131072,131072,-524288,786432,-524288,-524288,2097152,-3145728,2097152,2097152,-8388608 mov $1,4 mov $2,$0 mov $4,4 lpb $2,1 add $4,$1 add $1,1 mov $3,2 add $3,$1 sub $1,$1 sub $1,$4 mul $1,2 sub $2,1 add $3,7 mov $4,$3 lpe sub $1,4 div $1,20 mul $1,5 add $1,2
; CRT0 for the ZX80 ; ; Stefano Bodrato Dec. 2012 ; ; If an error occurs (eg. out if screen) we just drop back to BASIC ; ; ZX80 works in FAST mode only, thus the screen is visible only ; during a PAUSE or waiting for a keypress. ; ; ; - - - - - - - ; ; $Id: zx80_crt0.asm,v 1.15 2016-07-15 21:03:25 dom Exp $ ; ; - - - - - - - MODULE zx80_crt0 ;------- ; Include zcc_opt.def to find out information about us ;------- defc crt0 = 1 INCLUDE "zcc_opt.def" ;------- ; Some general scope declarations ;------- EXTERN _main ;main() is always external to crt0 code PUBLIC cleanup ;jp'd to by exit() PUBLIC l_dcal ;jp(hl) PUBLIC save81 ;Save ZX81 critical registers PUBLIC restore81 ;Restore ZX81 critical registers PUBLIC zx_fast PUBLIC zx_slow PUBLIC _zx_fast PUBLIC _zx_slow ;; PUBLIC frames ;Frame counter for time() PUBLIC _FRAMES defc _FRAMES = 16414 ; Timer EXTERN filltxt ; used by custom CLS IF !DEFINED_CRT_ORG_CODE defc CRT_ORG_CODE = 16525 ENDIF defc CONSOLE_ROWS = 24 defc CONSOLE_COLUMNS = 32 defc TAR__clib_exit_stack_size = 0 defc TAR__register_sp = -1 defc CRT_KEY_DEL = 12 defc __CPU_CLOCK = 3250000 INCLUDE "crt/classic/crt_rules.inc" org CRT_ORG_CODE start: ld l,0 call filltxt LD (IY+$12),24 ; set DF-SZ to 24 lines. ;call zx80_cls ;call 1863 ; CLS ;call $6e0 ;; N/L-LINE (PRPOS) ;ld a,0 ;call $720 ;call 1474 ; CL-EOD - clear to end of display ; (zx81) this would be after 'hrg_on', sometimes ; the stack will be moved to make room ; for high-resolution graphics. ld (start1+1),sp ;Save entry stack INCLUDE "crt/classic/crt_init_sp.asm" INCLUDE "crt/classic/crt_init_atexit.asm" call crt0_init_bss ld (exitsp),sp ; Optional definition for auto MALLOC init ; it assumes we have free space between the end of ; the compiled program and the stack pointer IF DEFINED_USING_amalloc INCLUDE "crt/classic/crt_init_amalloc.asm" ENDIF call _main ;Call user program cleanup: ; ; Deallocate memory which has been allocated here! ; push hl ; keep return code IF CRT_ENABLE_STDIO = 1 EXTERN closeall call closeall ENDIF ; ld iy,16384 ; no ix/iy swap here ;LD (IY+$12),2 ; set DF-SZ to 24 lines. ;call 1863 pop hl ; return code (for BASIC) start1: ld sp,0 ;Restore stack to entry value ;jp $283 ;ret ; oddly EightyOne gets unstable without this 'ret' !! ;jp restore81 restore81: ; ex af,af ; ld a,(a1save) ; ex af,af ld iy,16384 ; no ix/iy swap here save81: zx_fast: zx_slow: _zx_fast: _zx_slow: ret l_dcal: jp (hl) ;Used for function pointer calls ; defm "Small C+ ZX80" ;Unnecessary file signature ; defb 0 ;zx80_cls: ; LD HL,($400A) ; fetch E-LINE ; INC HL ; address the next location. ; LD (HL),$76 ; insert a newline. ; INC HL ; address the next location. ; LD ($400C),HL ; set D-FILE to start of dynamic display file. ; LD (IY+$12),$02 ; set DF-SZ to 2 lines. ;zx80_cls2: ; call $6e0 ;; N/L-LINE (PRPOS) ; ld a,0 ; call $720 ; ld a,($4025) ; S_POSN_Y ; dec a ; jr nz,zx80_cls2 ; jp $747 ; CLS INCLUDE "crt/classic/crt_runtime_selection.asm" INCLUDE "crt/classic/crt_section.asm"
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(int argc, const char * argv[]) { int N, K, l; vector<int> v; int sum; //初期化 sum = 0; //入力 cin >> N >> K; for (int i = 0; i < N; i++) { cin >> l; v.push_back(l); } //最大値計算 //昇順ソート sort(v.begin(), v.end()); //反転 reverse(v.begin(), v.end()); for (int i = 0; i < K; i++) { sum += v[i]; } //出力 cout << sum << endl; return 0; }
83_Header: sHeaderInit ; Z80 offset is $CD96 sHeaderPatch 83_Patches sHeaderTick $01 sHeaderCh $01 sHeaderSFX $80, $05, 83_FM5, $15, $05 83_FM5: sPatFM $00 ssModZ80 $01, $01, $20, $85 dc.b nD0, $03, nB0, $1E sStop 83_Patches: ; Patch $00 ; $35 ; $02, $FD, $01, $F6, $0F, $16, $14, $11 ; $06, $04, $0F, $08, $02, $03, $03, $04 ; $7F, $6F, $3F, $2F, $31, $28, $0E, $80 spAlgorithm $05 spFeedback $06 spDetune $00, $00, $0F, $0F spMultiple $02, $01, $0D, $06 spRateScale $00, $00, $00, $00 spAttackRt $0F, $14, $16, $11 spAmpMod $00, $00, $00, $00 spSustainRt $06, $0F, $04, $08 spSustainLv $07, $03, $06, $02 spDecayRt $02, $03, $03, $04 spReleaseRt $0F, $0F, $0F, $0F spTotalLv $31, $0E, $28, $00
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid VintageTimePieceCoin address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
; void *bsearch(const void *key, const void *base, ; size_t nmemb, size_t size, ; int (*compar)(const void *, const void *)) SECTION code_clib SECTION code_stdlib PUBLIC bsearch EXTERN asm_bsearch bsearch: pop af pop ix pop de pop hl pop bc exx pop bc push bc push bc push hl push de push hl push af push bc pop af exx jp asm_bsearch
; ; Copyright (c) 2022 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, January 2022 ; ;------------------------------------------------------------------------- ; asm_am9511_popf - am9511 APU pop float ;------------------------------------------------------------------------- ; ; Load IEEE-754 float from Am9511 APU stack ; ;------------------------------------------------------------------------- SECTION code_clib SECTION code_fp_am9511 INCLUDE "../../_DEVELOPMENT/target/am9511/config_am9511_private.inc" PUBLIC asm_am9511_popf .am9511_popf_wait ex (sp),hl ex (sp),hl .asm_am9511_popf ; float primitive ; pop a IEEE-754 floating point from the Am9511 stack. ; ; Convert from am9511_float to IEEE_float. ; ; enter : stack = ret0 ; ; exit : dehl = IEEE_float ; ; uses : af, bc, de, hl in a,(__IO_APU_STATUS) ; read the APU status register rlca ; busy? and __IO_APU_STATUS_BUSY jp C,am9511_popf_wait in a,(__IO_APU_DATA) ; load MSW from APU ld d,a in a,(__IO_APU_DATA) ld e,a in a,(__IO_APU_DATA) ; load LSW from APU ld h,a in a,(__IO_APU_DATA) ld l,a in a,(__IO_APU_STATUS) ; read the APU status register and 03eh ; errors from status register jp NZ,errors ld a,d ; get sign and exponent rla ; remove sign rlca ; adjust twos complement exponent rra ; with sign extention rra add 127-1 ; bias including shift binary point rl de ; get sign to carry, remove 1 leading mantissa rra ; reposition sign and exponent ld d,a ; restore exponent and carry ld a,e rra ; resposition exponent and mantissa ld e,a ret .errors rrca ; relocate status bits rrca jp C,infinity ; overflow rrca rrca jp C,nan ; negative sqr or log rrca jp C,nan ; division by zero .zero ld de,0 ld hl,de ret .nan ld a,d ; get sign or 07fh ld d,a ; nan exponent ld hl,0ffffh ; nan mantissa ld e,h ret .infinity ld a,d ; get sign or 07fh ld d,a ; nan exponent ld hl,0 ; nan mantissa ld e,080h ret
; A174112: After correction, duplicate of A111490. ; 1,2,4,5,9,9,15,16,21,23,33,29,41,45,51,52,68,65,83,81,91,99,121,109,128,138,152,152,180,168,198,199,217,231,253,234,270,286,308,298,338,326,368 mov $2,$0 lpb $0,1 add $1,1 mov $3,$0 sub $0,1 sub $1,1 add $4,1 mod $3,$4 add $1,$3 lpe add $1,1 add $1,$2
; Program 4.4 ; Array - MASM (64-bit) ; Copyright (c) 2020 Hall & Slonka extrn ExitProcess : proc .data array QWORD 1, 2, 3, 4 .code _main PROC ; Load using byte offsets lea rsi, array mov rax, QWORD PTR [rsi] mov rbx, QWORD PTR [rsi + 8] ; Save using indices mov rdx, 2 mov QWORD PTR [rsi+rdx*8], 10 mov rdx, 3 mov QWORD PTR [rsi+rdx*8], 20 xor rcx, rcx call ExitProcess _main ENDP END
; A249852: a(n) is the total number of pentagons on the left or the right of the vertical symmetry axis of a pentagon expansion (vertex to vertex) after n iterations. ; 0,2,7,14,23,35,50,67,86,108,133,160,189,221,256,293,332,374,419,466,515,567,622,679,738,800,865,932,1001,1073,1148,1225,1304,1386,1471,1558,1647,1739,1834,1931,2030,2132,2237,2344,2453,2565,2680,2797,2916,3038,3163,3290,3419 mov $1,$0 add $0,1 pow $0,2 mul $0,2 sub $1,2 bin $1,2 div $1,2 mul $1,2 add $1,$0 sub $1,4 div $1,2
Function f0 -closures 1 PushNull PushString "Test" Require StoreClosure 0 PushFunction f1 Store 0 Grab 0 CallFunctionNoReturn 0 Function f1 -closures 1 PushNull PushFunction f2 StoreClosure 0 PushString "Recursive Fibonacci" PushString "begin" LoadClosure 1 LoadElement CallFunctionNoReturn 1 PushUnsignedInteger 35 LoadClosure 0 CallFunction 1 Store 0 Grab 0 PushString "end" LoadClosure 1 LoadElement CallFunctionNoReturn 1 Function f2 -parameters 1 Grab 0 PushUnsignedInteger 1 LessThanOrEquals JumpIfFalse l1 Grab 0 Return .l1 Grab 0 PushUnsignedInteger 1 Subtract LoadClosure 0 CallFunction 1 Grab 1 PushUnsignedInteger 2 Subtract LoadClosure 0 CallFunction 1 Add Return
SECTION "Undocumented Registers", ROMX UndocumentedRegistersTest:: ; Test register $FF72 ldh a, [$FF72] and a jr z, .validInitFF72 ld de, strInvalidInit ld b, "2" jr ReturnFailString .validInitFF72 dec a ldh [$FF72], a ldh a, [$FF72] cp $FF jr z, .validWriteFF72 ld de, strFailWrite ld b, "2" jr ReturnFailString .validWriteFF72 ; Test register $FF73 ldh a, [$FF73] and a jr z, .validInitFF73 ld de, strInvalidInit ld b, "3" jr ReturnFailString .validInitFF73 dec a ldh [$FF73], a ldh a, [$FF73] cp $FF jr z, .validWriteFF73 ld de, strFailWrite ld b, "3" jr ReturnFailString .validWriteFF73 ; Test register $FF74 ldh a, [$FF74] and a jr z, .validInitFF74 ld de, strInvalidInit ld b, "4" jr ReturnFailString .validInitFF74 dec a ldh [$FF74], a ldh a, [$FF74] cp $FF jr z, .validWriteFF74 ld de, strFailWrite ld b, "4" jr ReturnFailString .validWriteFF74 ; Test register $FF75 ldh a, [$FF75] cp %10001111 jr z, .validInitFF75 ld de, strInvalidInit ld b, "5" jr ReturnFailString .validInitFF75 ld a, $FF ldh [$FF75], a ldh a, [$FF75] cp $FF jr z, .didWriteFF75 ld de, strFailWrite ld b, "5" jr ReturnFailString .didWriteFF75 ld a, %01110000 ldh [$FF75], a ldh a, [$FF75] cp $FF jr z, .validWriteFF75 ld de, strFailBitsFF75 ret .validWriteFF75 ld de, $0000 ret ;------------------------------------------------------------------------ ; Generates a fail string in WRAM and returns a pointer to the ; testing framework. ; Parameters: ; * DE - Base Pointer to error string ; * B - Character to be appended to the error string ;------------------------------------------------------------------------ ReturnFailString:: ld hl, _RAM call Strcpy dec hl ld a, b ld [hli], a xor a ld [hl], a ld de, _RAM ret strInvalidInit: db "Invalid initial $FF7", 0 strFailWrite: db "Read-only $FF7", 0 strFailBitsFF75: db "Incorrect writeable bits on $FF75", 0
#include "Platform.inc" #include "TailCalls.inc" #include "Lcd/Isr.inc" #include "PowerManagement/Isr.inc" #include "Clock.inc" #include "Motor/Isr.inc" #include "InitialisationChain.inc" radix decimal extern INITIALISE_AFTER_ISR MOTOR_ADC_CHANNEL equ b'00011100' MOTOR_LOAD_FLAGS_MASK equ (1 << MOTOR_FLAG_NOLOAD) | (1 << MOTOR_FLAG_NOMINALLOAD) | (1 << MOTOR_FLAG_OVERLOAD) ADRESH_90MA equ 23 udata_shr contextSavingW res 1 contextSavingStatus res 1 contextSavingPclath res 1 lcdContrastAccumulator res 1 Isr code 0x0004 global isr global initialiseIsr ; TODO: BUG (HERE ?) - LCD CONTRAST GOES FROM ABOUT 1.24V TO 2.38V ; SEEMINGLY RANDOMLY, TURNING OFF THE LCD. VOLTAGE IS ROCK SOLID UNTIL ; IT HAPPENS, AND THERE IS NO CONSISTENT TIME UNTIL IT HAPPENS... ; ; *** UPDATE: I THINK THIS IS BECAUSE UNDER CERTAIN (UNKNOWN) CONDITIONS, ; THE ADC IS TURNED OFF - PORTC5=1, TRISC=0x88, PSTRCON=0x11, CCPR1L=0xff, ; ADCON=0x1f, ADCON1=0x20, motorState=0x05. NOTICED DURING RAISING OF THE ; DOOR DURING SIMULATION. isr: movwf contextSavingW swapf contextSavingW swapf STATUS, W movwf contextSavingStatus movf PCLATH, W movwf contextSavingPclath clrf PCLATH preventSleepForSinglePollLoopIteration: .setBankFor powerManagementFlags bsf powerManagementFlags, POWER_FLAG_PREVENTSLEEP adcSampled: .safelySetBankFor PIR1 btfss PIR1, ADIF goto endOfAdcBlock bcf PIR1, ADIF disableMotorOutputsIfNotMonitoringCurrent: .setBankFor ADCON0 bsf ADCON0, GO movlw b'00111100' andwf ADCON0, W xorlw MOTOR_ADC_CHANNEL btfss STATUS, Z goto disableMotorOutputs motorCurrentMonitoring: .setBankFor PSTRCON movlw MOTOR_PSTRCON_OUTPUT_MASK andwf PSTRCON, W btfsc STATUS, Z goto endOfMotorCurrentMonitoring setMotorFlags: .setBankFor ADRESH movlw ADRESH_90MA subwf ADRESH, W movlw ~MOTOR_LOAD_FLAGS_MASK | (1 << MOTOR_FLAG_NOLOAD) btfsc STATUS, C movlw ~MOTOR_LOAD_FLAGS_MASK | (1 << MOTOR_FLAG_NOMINALLOAD) btfsc ADRESH, 7 movlw ~MOTOR_LOAD_FLAGS_MASK | (1 << MOTOR_FLAG_OVERLOAD) .setBankFor motorFlags andwf motorFlags andlw MOTOR_LOAD_FLAGS_MASK iorwf motorFlags disableMotorOutputsIfFlagsMasked: swapf motorFlags, W andlw MOTOR_LOAD_FLAGS_MASK andwf motorFlags, W btfsc STATUS, Z goto endOfMotorCurrentMonitoring disableMotorOutputs: .safelySetBankFor MOTOR_PORT bcf MOTOR_PORT, MOTOR_PWMA_PIN bcf MOTOR_PORT, MOTOR_PWMB_PIN .setBankFor PSTRCON movlw ~MOTOR_PSTRCON_OUTPUT_MASK andwf PSTRCON endOfMotorCurrentMonitoring: lcdDeltaSigmaContrastControl: .safelySetBankFor lcdFlags btfss lcdFlags, LCD_FLAG_ENABLED goto endOfContrastControl movf lcdContrast, W addwf lcdContrastAccumulator .setBankFor LCD_CONTRAST_PORT btfss STATUS, C bcf LCD_CONTRAST_PORT, LCD_CONTRAST_PIN btfsc STATUS, C bsf LCD_CONTRAST_PORT, LCD_CONTRAST_PIN endOfContrastControl: endOfAdcBlock: clockTicked: .safelySetBankFor PIR1 btfss PIR1, TMR1IF goto endOfClockTicked bcf PIR1, TMR1IF .setBankFor clockFlags bsf clockFlags, CLOCK_FLAG_TICKED endOfClockTicked: clearButtonFlagIfJustWokenUp: .safelySetBankFor powerManagementFlags btfss powerManagementFlags, POWER_FLAG_SLEEPING goto endOfIsr .setBankFor INTCON bcf INTCON, RABIF endOfIsr: movf contextSavingPclath, W movwf PCLATH swapf contextSavingStatus, W movwf STATUS swapf contextSavingW, W retfie initialiseIsr: clrf lcdContrastAccumulator tcall INITIALISE_AFTER_ISR end
// // VoxelTree.cpp // libraries/voxels/src // // Created by Stephen Birarda on 3/13/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <algorithm> #include <QDebug> #include <QImage> #include <QRgb> #include "VoxelTree.h" #include "Tags.h" // Voxel Specific operations.... VoxelTree::VoxelTree(bool shouldReaverage) : Octree(shouldReaverage) { _rootElement = createNewElement(); } VoxelTreeElement* VoxelTree::createNewElement(unsigned char * octalCode) { VoxelSystem* voxelSystem = NULL; if (_rootElement) { voxelSystem = (static_cast<VoxelTreeElement*>(_rootElement))->getVoxelSystem(); } VoxelTreeElement* newElement = new VoxelTreeElement(octalCode); newElement->setVoxelSystem(voxelSystem); return newElement; } void VoxelTree::deleteVoxelAt(float x, float y, float z, float s) { deleteOctreeElementAt(x, y, z, s); } VoxelTreeElement* VoxelTree::getVoxelAt(float x, float y, float z, float s) const { return static_cast<VoxelTreeElement*>(getOctreeElementAt(x, y, z, s)); } VoxelTreeElement* VoxelTree::getEnclosingVoxelAt(float x, float y, float z, float s) const { return static_cast<VoxelTreeElement*>(getOctreeEnclosingElementAt(x, y, z, s)); } void VoxelTree::createVoxel(float x, float y, float z, float s, unsigned char red, unsigned char green, unsigned char blue, bool destructive) { unsigned char* voxelData = pointToVoxel(x,y,z,s,red,green,blue); lockForWrite(); readCodeColorBufferToTree(voxelData, destructive); unlock(); delete[] voxelData; } class NodeChunkArgs { public: VoxelTree* thisVoxelTree; glm::vec3 nudgeVec; VoxelEditPacketSender* voxelEditSenderPtr; int childOrder[NUMBER_OF_CHILDREN]; }; float findNewLeafSize(const glm::vec3& nudgeAmount, float leafSize) { // we want the smallest non-zero and non-negative new leafSize float newLeafSizeX = fabs(fmod(nudgeAmount.x, leafSize)); float newLeafSizeY = fabs(fmod(nudgeAmount.y, leafSize)); float newLeafSizeZ = fabs(fmod(nudgeAmount.z, leafSize)); float newLeafSize = leafSize; if (newLeafSizeX) { newLeafSize = std::min(newLeafSize, newLeafSizeX); } if (newLeafSizeY) { newLeafSize = std::min(newLeafSize, newLeafSizeY); } if (newLeafSizeZ) { newLeafSize = std::min(newLeafSize, newLeafSizeZ); } return newLeafSize; } void reorderChildrenForNudge(void* extraData) { NodeChunkArgs* args = (NodeChunkArgs*)extraData; glm::vec3 nudgeVec = args->nudgeVec; int lastToNudgeVote[NUMBER_OF_CHILDREN] = { 0 }; const int POSITIVE_X_ORDERING[4] = {0, 1, 2, 3}; const int NEGATIVE_X_ORDERING[4] = {4, 5, 6, 7}; const int POSITIVE_Y_ORDERING[4] = {0, 1, 4, 5}; const int NEGATIVE_Y_ORDERING[4] = {2, 3, 6, 7}; const int POSITIVE_Z_ORDERING[4] = {0, 2, 4, 6}; const int NEGATIVE_Z_ORDERING[4] = {1, 3, 5, 7}; if (nudgeVec.x > 0) { for (int i = 0; i < NUMBER_OF_CHILDREN / 2; i++) { lastToNudgeVote[POSITIVE_X_ORDERING[i]]++; } } else if (nudgeVec.x < 0) { for (int i = 0; i < NUMBER_OF_CHILDREN / 2; i++) { lastToNudgeVote[NEGATIVE_X_ORDERING[i]]++; } } if (nudgeVec.y > 0) { for (int i = 0; i < NUMBER_OF_CHILDREN / 2; i++) { lastToNudgeVote[POSITIVE_Y_ORDERING[i]]++; } } else if (nudgeVec.y < 0) { for (int i = 0; i < NUMBER_OF_CHILDREN / 2; i++) { lastToNudgeVote[NEGATIVE_Y_ORDERING[i]]++; } } if (nudgeVec.z > 0) { for (int i = 0; i < NUMBER_OF_CHILDREN / 2; i++) { lastToNudgeVote[POSITIVE_Z_ORDERING[i]]++; } } else if (nudgeVec.z < 0) { for (int i = 0; i < NUMBER_OF_CHILDREN / 2; i++) { lastToNudgeVote[NEGATIVE_Z_ORDERING[i]]++; } } int nUncountedVotes = NUMBER_OF_CHILDREN; while (nUncountedVotes > 0) { int maxNumVotes = 0; int maxVoteIndex = -1; for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { if (lastToNudgeVote[i] > maxNumVotes) { maxNumVotes = lastToNudgeVote[i]; maxVoteIndex = i; } else if (lastToNudgeVote[i] == maxNumVotes && maxVoteIndex == -1) { maxVoteIndex = i; } } lastToNudgeVote[maxVoteIndex] = -1; args->childOrder[nUncountedVotes - 1] = maxVoteIndex; nUncountedVotes--; } } bool VoxelTree::nudgeCheck(OctreeElement* element, void* extraData) { VoxelTreeElement* voxel = (VoxelTreeElement*)element; if (voxel->isLeaf()) { // we have reached the deepest level of elements/voxels // now there are two scenarios // 1) this element's size is <= the minNudgeAmount // in which case we will simply call nudgeLeaf on this leaf // 2) this element's size is still not <= the minNudgeAmount // in which case we need to break this leaf down until the leaf sizes are <= minNudgeAmount NodeChunkArgs* args = (NodeChunkArgs*)extraData; // get octal code of this element const unsigned char* octalCode = element->getOctalCode(); // get voxel position/size VoxelPositionSize unNudgedDetails; voxelDetailsForCode(octalCode, unNudgedDetails); // find necessary leaf size float newLeafSize = findNewLeafSize(args->nudgeVec, unNudgedDetails.s); // check to see if this unNudged element can be nudged if (unNudgedDetails.s <= newLeafSize) { args->thisVoxelTree->nudgeLeaf(voxel, extraData); return false; } else { // break the current leaf into smaller chunks args->thisVoxelTree->chunkifyLeaf(voxel); } } return true; } void VoxelTree::chunkifyLeaf(VoxelTreeElement* element) { // because this function will continue being called recursively // we only need to worry about breaking this specific leaf down if (!element->isColored()) { return; } for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { element->addChildAtIndex(i); element->getChildAtIndex(i)->setColor(element->getColor()); } } // This function is called to nudge the leaves of a tree, given that the // nudge amount is >= to the leaf scale. void VoxelTree::nudgeLeaf(VoxelTreeElement* element, void* extraData) { NodeChunkArgs* args = (NodeChunkArgs*)extraData; // get octal code of this element const unsigned char* octalCode = element->getOctalCode(); // get voxel position/size VoxelPositionSize unNudgedDetails; voxelDetailsForCode(octalCode, unNudgedDetails); VoxelDetail voxelDetails; voxelDetails.x = unNudgedDetails.x; voxelDetails.y = unNudgedDetails.y; voxelDetails.z = unNudgedDetails.z; voxelDetails.s = unNudgedDetails.s; voxelDetails.red = element->getColor()[RED_INDEX]; voxelDetails.green = element->getColor()[GREEN_INDEX]; voxelDetails.blue = element->getColor()[BLUE_INDEX]; glm::vec3 nudge = args->nudgeVec; // delete the old element args->voxelEditSenderPtr->sendVoxelEditMessage(PacketTypeVoxelErase, voxelDetails); // nudge the old element voxelDetails.x += nudge.x; voxelDetails.y += nudge.y; voxelDetails.z += nudge.z; // create a new voxel in its stead args->voxelEditSenderPtr->sendVoxelEditMessage(PacketTypeVoxelSetDestructive, voxelDetails); } // Recurses voxel element with an operation function void VoxelTree::recurseNodeForNudge(VoxelTreeElement* element, RecurseOctreeOperation operation, void* extraData) { NodeChunkArgs* args = (NodeChunkArgs*)extraData; if (operation(element, extraData)) { for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { // XXXBHG cleanup!! VoxelTreeElement* child = (VoxelTreeElement*)element->getChildAtIndex(args->childOrder[i]); if (child) { recurseNodeForNudge(child, operation, extraData); } } } } void VoxelTree::nudgeSubTree(VoxelTreeElement* elementToNudge, const glm::vec3& nudgeAmount, VoxelEditPacketSender& voxelEditSender) { if (nudgeAmount == glm::vec3(0, 0, 0)) { return; } NodeChunkArgs args; args.thisVoxelTree = this; args.nudgeVec = nudgeAmount; args.voxelEditSenderPtr = &voxelEditSender; reorderChildrenForNudge(&args); recurseNodeForNudge(elementToNudge, nudgeCheck, &args); } bool VoxelTree::readFromSquareARGB32Pixels(const char* filename) { emit importProgress(0); int minAlpha = INT_MAX; QImage pngImage = QImage(filename); for (int i = 0; i < pngImage.width(); ++i) { for (int j = 0; j < pngImage.height(); ++j) { minAlpha = std::min(qAlpha(pngImage.pixel(i, j)) , minAlpha); } } int maxSize = std::max(pngImage.width(), pngImage.height()); int scale = 1; while (maxSize > scale) {scale *= 2;} float size = 1.0f / scale; emit importSize(size * pngImage.width(), 1.0f, size * pngImage.height()); QRgb pixel; int minNeighborhoodAlpha; for (int i = 0; i < pngImage.width(); ++i) { for (int j = 0; j < pngImage.height(); ++j) { emit importProgress((100 * (i * pngImage.height() + j)) / (pngImage.width() * pngImage.height())); pixel = pngImage.pixel(i, j); minNeighborhoodAlpha = qAlpha(pixel) - 1; if (i != 0) { minNeighborhoodAlpha = std::min(minNeighborhoodAlpha, qAlpha(pngImage.pixel(i - 1, j))); } if (j != 0) { minNeighborhoodAlpha = std::min(minNeighborhoodAlpha, qAlpha(pngImage.pixel(i, j - 1))); } if (i < pngImage.width() - 1) { minNeighborhoodAlpha = std::min(minNeighborhoodAlpha, qAlpha(pngImage.pixel(i + 1, j))); } if (j < pngImage.height() - 1) { minNeighborhoodAlpha = std::min(minNeighborhoodAlpha, qAlpha(pngImage.pixel(i, j + 1))); } while (qAlpha(pixel) > minNeighborhoodAlpha) { ++minNeighborhoodAlpha; createVoxel(i * size, (minNeighborhoodAlpha - minAlpha) * size, j * size, size, qRed(pixel), qGreen(pixel), qBlue(pixel), true); } } } emit importProgress(100); return true; } bool VoxelTree::readFromSchematicFile(const char *fileName) { _stopImport = false; emit importProgress(0); std::stringstream ss; int err = retrieveData(std::string(fileName), ss); if (err && ss.get() != TAG_Compound) { qDebug("[ERROR] Invalid schematic file."); return false; } ss.get(); TagCompound schematics(ss); if (!schematics.getBlocksId() || !schematics.getBlocksData()) { qDebug("[ERROR] Invalid schematic data."); return false; } int max = (schematics.getWidth() > schematics.getLength()) ? schematics.getWidth() : schematics.getLength(); max = (max > schematics.getHeight()) ? max : schematics.getHeight(); int scale = 1; while (max > scale) {scale *= 2;} float size = 1.0f / scale; emit importSize(size * schematics.getWidth(), size * schematics.getHeight(), size * schematics.getLength()); int create = 1; int red = 128, green = 128, blue = 128; int count = 0; for (int y = 0; y < schematics.getHeight(); ++y) { for (int z = 0; z < schematics.getLength(); ++z) { emit importProgress((int) 100 * (y * schematics.getLength() + z) / (schematics.getHeight() * schematics.getLength())); for (int x = 0; x < schematics.getWidth(); ++x) { if (_stopImport) { qDebug("Canceled import at %d voxels.", count); _stopImport = false; return true; } int pos = ((y * schematics.getLength()) + z) * schematics.getWidth() + x; int id = schematics.getBlocksId()[pos]; int data = schematics.getBlocksData()[pos]; create = 1; computeBlockColor(id, data, red, green, blue, create); switch (create) { case 1: createVoxel(size * x, size * y, size * z, size, red, green, blue, true); ++count; break; case 2: switch (data) { case 0: createVoxel(size * x + size / 2, size * y + size / 2, size * z , size / 2, red, green, blue, true); createVoxel(size * x + size / 2, size * y + size / 2, size * z + size / 2, size / 2, red, green, blue, true); break; case 1: createVoxel(size * x , size * y + size / 2, size * z , size / 2, red, green, blue, true); createVoxel(size * x , size * y + size / 2, size * z + size / 2, size / 2, red, green, blue, true); break; case 2: createVoxel(size * x , size * y + size / 2, size * z + size / 2, size / 2, red, green, blue, true); createVoxel(size * x + size / 2, size * y + size / 2, size * z + size / 2, size / 2, red, green, blue, true); break; case 3: createVoxel(size * x , size * y + size / 2, size * z , size / 2, red, green, blue, true); createVoxel(size * x + size / 2, size * y + size / 2, size * z , size / 2, red, green, blue, true); break; } count += 2; // There's no break on purpose. case 3: createVoxel(size * x , size * y, size * z , size / 2, red, green, blue, true); createVoxel(size * x + size / 2, size * y, size * z , size / 2, red, green, blue, true); createVoxel(size * x , size * y, size * z + size / 2, size / 2, red, green, blue, true); createVoxel(size * x + size / 2, size * y, size * z + size / 2, size / 2, red, green, blue, true); count += 4; break; } } } } emit importProgress(100); qDebug("Created %d voxels from minecraft import.", count); return true; } class ReadCodeColorBufferToTreeArgs { public: const unsigned char* codeColorBuffer; int lengthOfCode; bool destructive; bool pathChanged; }; void VoxelTree::readCodeColorBufferToTree(const unsigned char* codeColorBuffer, bool destructive) { ReadCodeColorBufferToTreeArgs args; args.codeColorBuffer = codeColorBuffer; args.lengthOfCode = numberOfThreeBitSectionsInCode(codeColorBuffer); args.destructive = destructive; args.pathChanged = false; VoxelTreeElement* node = getRoot(); readCodeColorBufferToTreeRecursion(node, args); } void VoxelTree::readCodeColorBufferToTreeRecursion(VoxelTreeElement* node, ReadCodeColorBufferToTreeArgs& args) { int lengthOfNodeCode = numberOfThreeBitSectionsInCode(node->getOctalCode()); // Since we traverse the tree in code order, we know that if our code // matches, then we've reached our target node. if (lengthOfNodeCode == args.lengthOfCode) { // we've reached our target -- we might have found our node, but that node might have children. // in this case, we only allow you to set the color if you explicitly asked for a destructive // write. if (!node->isLeaf() && args.destructive) { // if it does exist, make sure it has no children for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { node->deleteChildAtIndex(i); } } else { if (!node->isLeaf()) { qDebug("WARNING! operation would require deleting children, add Voxel ignored!"); } } // If we get here, then it means, we either had a true leaf to begin with, or we were in // destructive mode and we deleted all the child trees. So we can color. if (node->isLeaf()) { // give this node its color int octalCodeBytes = bytesRequiredForCodeLength(args.lengthOfCode); nodeColor newColor; memcpy(newColor, args.codeColorBuffer + octalCodeBytes, SIZE_OF_COLOR_DATA); newColor[SIZE_OF_COLOR_DATA] = 1; node->setColor(newColor); // It's possible we just reset the node to it's exact same color, in // which case we don't consider this to be dirty... if (node->isDirty()) { // track our tree dirtiness _isDirty = true; // track that path has changed args.pathChanged = true; } } return; } // Ok, we know we haven't reached our target node yet, so keep looking //printOctalCode(args.codeColorBuffer); int childIndex = branchIndexWithDescendant(node->getOctalCode(), args.codeColorBuffer); VoxelTreeElement* childNode = node->getChildAtIndex(childIndex); // If the branch we need to traverse does not exist, then create it on the way down... if (!childNode) { childNode = node->addChildAtIndex(childIndex); } // recurse... readCodeColorBufferToTreeRecursion(childNode, args); // Unwinding... // If the lower level did some work, then we need to let this node know, so it can // do any bookkeeping it wants to, like color re-averaging, time stamp marking, etc if (args.pathChanged) { node->handleSubtreeChanged(this); } } bool VoxelTree::handlesEditPacketType(PacketType packetType) const { // we handle these types of "edit" packets switch (packetType) { case PacketTypeVoxelSet: case PacketTypeVoxelSetDestructive: case PacketTypeVoxelErase: return true; default: return false; } } const unsigned int REPORT_OVERFLOW_WARNING_INTERVAL = 100; unsigned int overflowWarnings = 0; int VoxelTree::processEditPacketData(PacketType packetType, const unsigned char* packetData, int packetLength, const unsigned char* editData, int maxLength, const SharedNodePointer& node) { // we handle these types of "edit" packets switch (packetType) { case PacketTypeVoxelSet: case PacketTypeVoxelSetDestructive: { bool destructive = (packetType == PacketTypeVoxelSetDestructive); int octets = numberOfThreeBitSectionsInCode(editData, maxLength); if (octets == OVERFLOWED_OCTCODE_BUFFER) { overflowWarnings++; if (overflowWarnings % REPORT_OVERFLOW_WARNING_INTERVAL == 1) { qDebug() << "WARNING! Got voxel edit record that would overflow buffer in numberOfThreeBitSectionsInCode()" " [NOTE: this is warning number" << overflowWarnings << ", the next" << (REPORT_OVERFLOW_WARNING_INTERVAL-1) << "will be suppressed.]"; QDebug debug = qDebug(); debug << "edit data contents:"; outputBufferBits(editData, maxLength, &debug); } return maxLength; } const int COLOR_SIZE_IN_BYTES = 3; int voxelCodeSize = bytesRequiredForCodeLength(octets); int voxelDataSize = voxelCodeSize + COLOR_SIZE_IN_BYTES; if (voxelDataSize > maxLength) { overflowWarnings++; if (overflowWarnings % REPORT_OVERFLOW_WARNING_INTERVAL == 1) { qDebug() << "WARNING! Got voxel edit record that would overflow buffer." " [NOTE: this is warning number" << overflowWarnings << ", the next" << (REPORT_OVERFLOW_WARNING_INTERVAL-1) << "will be suppressed.]"; QDebug debug = qDebug(); debug << "edit data contents:"; outputBufferBits(editData, maxLength, &debug); } return maxLength; } readCodeColorBufferToTree(editData, destructive); return voxelDataSize; } break; case PacketTypeVoxelErase: processRemoveOctreeElementsBitstream((unsigned char*)packetData, packetLength); return maxLength; default: return 0; } } class VoxelTreeDebugOperator : public RecurseOctreeOperator { public: virtual bool preRecursion(OctreeElement* element); virtual bool postRecursion(OctreeElement* element) { return true; } }; bool VoxelTreeDebugOperator::preRecursion(OctreeElement* element) { VoxelTreeElement* treeElement = static_cast<VoxelTreeElement*>(element); qDebug() << "VoxelTreeElement [" << treeElement << ":" << treeElement->getAACube() << "]"; qDebug() << " isLeaf:" << treeElement->isLeaf(); qDebug() << " color:" << treeElement->getColor()[0] << ", " << treeElement->getColor()[1] << ", " << treeElement->getColor()[2]; return true; } void VoxelTree::dumpTree() { // First, look for the existing entity in the tree.. VoxelTreeDebugOperator theOperator; recurseTreeWithOperator(&theOperator); }
; r0: timer 0 owerflov counter ; r1: timer 1 owerflov counter ; r2: error code ; r3: timer high expected value ; r4: timer low expected value ; r5: owerflov counter expected value ajmp start; org 03h ;external interrupt 0 reti; org 0bh ;t/c 0 interrupt inc r0; nop; nop; nop; nop; reti; org 13h ;external interrupt 1 reti; org 1bh ;t/c 1 interrupt inc r1; nop; nop; nop; nop; reti; org 23h ;serial interface interrupt reti; test0: mov a, th0 ; subb a, r3 ; jnz error ; inc r2 ; mov a,tl0 ; subb a, r4 ; jnz error ; inc r2 ; mov a, r0 ; subb a, r5 ; jnz error ; ret; test1: mov a, th1 ; subb a, r3 ; jnz error ; inc r2 ; mov a,tl1 ; subb a, r4 ; jnz error ; inc r2 ; mov a, r1 ; subb a, r5 ; jnz error ; ret; error: mov p0, r2; nop; ajmp error; wait: dec a ; 1 nop ; 1 nop ; 1 nop ; 1 nop ; 1 nop ; 1 nop ; 1 nop ; 1 jnz wait ; 4 ret ; 4 start: clr a; mov r0, a; mov r1, a; mov ie, #08ah ;enable interrupts clr c; ; ; timer 0 test ; ; mode 0 ; mov tmod, #000h ;t/c 0 and t/c 1 in timer mode 0 mov th0, #000h ;load timer 0 mov tl0, #000h ; mov tcon, #010h ;start timer 0; mov a, #03h ; 1 acall wait ; 3 nop; nop; nop; clr tcon.4 ;stop timer 0 mov r2, #010h ; mov r3, #000h ; mov r4, #004h ; mov r5, #000h ; acall test0 ; mov tl0, #01ch ; load timer 0 setb tcon.4 ;start timer 0; mov a, #04h ; 1 acall wait ; 2 nop; nop; nop; clr tcon.4 ;stop timer 0; mov r2, #020h ; mov r3, #001h ; mov r4, #001h ; mov r5, #000h ; acall test0 ; mov tl0, #01ch ; mov th0, #0ffh ; setb tcon.4 ;start timer 0 mov a, #05h ; acall wait ; nop; nop; nop; clr tcon.4 ;stop timer 0 mov r2, #030h ; mov r3, #000h ; mov r4, #003h ; mov r5, #001h ; acall test0 ; ; ; mode 1 ; mov tmod, #001h ; t/c 0 in mode 1 mov th0, #000h ;load timer 0 mov tl0, #000h ; setb tcon.4 ;start timer 0; mov a, #03h ; acall wait ; nop; nop; nop; clr tcon.4 ;stop timer 0 mov r2, #040h ; mov r3, #000h ; mov r4, #004h ; mov r5, #001h ; acall test0 ; mov tl0, #0fch ; load timer 0 setb tcon.4 ;start timer 0; mov a, #04h ; acall wait ; nop; nop; nop; clr tcon.4 ;stop timer 0; mov r2, #050h ; mov r3, #001h ; mov r4, #001h ; mov r5, #001h ; acall test0 ; mov tl0, #0fch ; mov th0, #0ffh ; setb tcon.4 ;start timer 0 mov a, #05h ; acall wait ; nop; nop; nop; clr tcon.4 ;stop timer 0 mov r2, #060h ; mov r3, #000h ; mov r4, #003h ; mov r5, #002h ; acall test0 ; ; ; mode 2 ; mov tmod, #002h ; t/c 0 in mode 2 mov th0, #000h ;load timer 0 mov tl0, #005h ; setb tcon.4 ;start timer 0; mov a, #03h ; acall wait ; nop; nop; nop; clr tcon.4 ;stop timer 0 mov r2, #070h ; mov r3, #000h ; mov r4, #009h ; mov r5, #002h ; acall test0 ; mov tl0, #0fch ; load timer 0 mov th0, #050h ; setb tcon.4 ;start timer 0; mov a, #05h ; acall wait ; nop; nop; nop; clr tcon.4 ;stop timer 0; mov r2, #080h ; mov r3, #050h ; mov r4, #053h ; mov r5, #003h ; acall test0 ; ; ; mode 3 ; mov tmod, #003h ; t/c 0 in mode 3 mov th0, #000h ;load timer 0 mov tl0, #000h ; setb tcon.4 ;start timer 0; mov a, #03h ; acall wait ; nop; nop; nop; clr tcon.4 ;stop timer 0 mov r2, #090h ; mov r3, #000h ; mov r4, #004h ; mov r5, #003h ; acall test0 ; mov tl0, #0fch ; load timer 0 mov th0, #000h ; setb tcon.4 ;start timer 0 mov a, #05h ; acall wait ; nop; nop; nop; clr tcon.4 ;stop timer 0 mov r2, #0a0h ; mov r3, #000h ; mov r4, #003h ; mov r5, #004h ; acall test0 ; mov tl0, #000h ; load timer 0 mov th0, #000h ; setb tcon.6 ; start timer 1 mov a, #03h ; acall wait ; nop; nop; nop; clr tcon.6 ; stop timer 1 mov r2, #0b0h ; mov r3, #004h ; mov r4, #000h ; mov r5, #004h ; acall test0 ; mov tl0, #000h ; load timer 0 mov th0, #0fch ; setb tcon.6 ;start timer 1 mov a, #05h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #0c0h ; mov r3, #003h ; mov r4, #000h ; mov r5, #001h ; mov r0, 01h ; acall test0 ; mov p0, #001h ; test timer 0 done! mov r1, #000h ; ; ; timer 1 test ; ; mode 0 ; mov tmod, #000h ;t/c 0 and t/c 1 in timer mode 0 mov th1, #000h ;load timer 1 mov tl1, #000h ; mov tcon, #040h ;start timer 1; mov a, #03h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #018h ; mov r3, #000h ; mov r4, #004h ; mov r5, #000h ; acall test1 ; mov tl1, #01ch ; load timer 1 setb tcon.6 ;start timer 1 mov a, #04h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #028h ; mov r3, #001h ; mov r4, #001h ; mov r5, #000h ; acall test1 ; mov tl1, #01ch ; mov th1, #0ffh ; setb tcon.6 ;start timer 1 mov a, #05h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #038h ; mov r3, #000h ; mov r4, #003h ; mov r5, #001h ; acall test1 ; ; ; mode 1 ; mov tmod, #010h ; t/c 1 in mode 1 mov th1, #000h ;load timer 1 mov tl1, #000h ; setb tcon.6 ;start timer 1 mov a, #03h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #048h ; mov r3, #000h ; mov r4, #004h ; mov r5, #001h ; acall test1 ; mov tl1, #0fch ; load timer 1 setb tcon.6 ; start timer 1 mov a, #04h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #058h ; mov r3, #001h ; mov r4, #001h ; mov r5, #001h ; acall test1 ; mov tl1, #0fch ; mov th1, #0ffh ; setb tcon.6 ;start timer 1 mov a, #05h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #068h ; mov r3, #000h ; mov r4, #004h ; mov r5, #002h ; acall test1 ; ; ; mode 2 ; mov tmod, #020h ; t/c 1 in mode 2 mov th1, #000h ;load timer 1 mov tl1, #005h ; setb tcon.6 ;start timer 1 mov a, #03h ; acall wait ; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #078h ; mov r3, #000h ; mov r4, #009h ; mov r5, #002h ; acall test1 ; mov tl1, #0fch ; load timer 1 mov th1, #050h ; setb tcon.6 ;start timer 1 mov a, #04h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #088h ; mov r3, #050h ; mov r4, #052h ; mov r5, #003h ; acall test1 ; ; ; mode 3 ; mov tmod, #030h ; t/c 1 in mode 3 mov th1, #000h ;load timer 1 mov tl1, #000h ; setb tcon.6 ;start timer 1 mov a, #03h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #098h ; mov r3, #000h ; mov r4, #000h ; mov r5, #003h ; acall test1 ; mov tl1, #0fch ; load timer 1 mov th1, #0ffh ; setb tcon.6 ;start timer 1 mov a, #05h ; acall wait ; nop; nop; nop; clr tcon.6 ;stop timer 1 mov r2, #0a8h ; mov r3, #0ffh ; mov r4, #0fch ; mov r5, #003h ; acall test1 ; mov p0, #002h ; test timer 1 done! end
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 4, 0x90 .p2align 4, 0x90 .globl gf256_add .type gf256_add, @function gf256_add: push %r12 push %r13 push %r14 xor %r14, %r14 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 addq (%rdx), %r8 adcq (8)(%rdx), %r9 adcq (16)(%rdx), %r10 adcq (24)(%rdx), %r11 adc $(0), %r14 mov %r8, %rax mov %r9, %rdx mov %r10, %r12 mov %r11, %r13 subq (%rcx), %rax sbbq (8)(%rcx), %rdx sbbq (16)(%rcx), %r12 sbbq (24)(%rcx), %r13 sbb $(0), %r14 cmove %rax, %r8 cmove %rdx, %r9 cmove %r12, %r10 cmove %r13, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) mov %rdi, %rax pop %r14 pop %r13 pop %r12 ret .Lfe1: .size gf256_add, .Lfe1-(gf256_add) .p2align 4, 0x90 .globl gf256_sub .type gf256_sub, @function gf256_sub: push %r12 push %r13 push %r14 xor %r14, %r14 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 subq (%rdx), %r8 sbbq (8)(%rdx), %r9 sbbq (16)(%rdx), %r10 sbbq (24)(%rdx), %r11 sbb $(0), %r14 mov %r8, %rax mov %r9, %rdx mov %r10, %r12 mov %r11, %r13 addq (%rcx), %rax adcq (8)(%rcx), %rdx adcq (16)(%rcx), %r12 adcq (24)(%rcx), %r13 test %r14, %r14 cmovne %rax, %r8 cmovne %rdx, %r9 cmovne %r12, %r10 cmovne %r13, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) mov %rdi, %rax pop %r14 pop %r13 pop %r12 ret .Lfe2: .size gf256_sub, .Lfe2-(gf256_sub) .p2align 4, 0x90 .globl gf256_neg .type gf256_neg, @function gf256_neg: push %r12 push %r13 push %r14 xor %r14, %r14 xor %r8, %r8 xor %r9, %r9 xor %r10, %r10 xor %r11, %r11 subq (%rsi), %r8 sbbq (8)(%rsi), %r9 sbbq (16)(%rsi), %r10 sbbq (24)(%rsi), %r11 sbb $(0), %r14 mov %r8, %rax mov %r9, %rcx mov %r10, %r12 mov %r11, %r13 addq (%rdx), %rax adcq (8)(%rdx), %rcx adcq (16)(%rdx), %r12 adcq (24)(%rdx), %r13 test %r14, %r14 cmovne %rax, %r8 cmovne %rcx, %r9 cmovne %r12, %r10 cmovne %r13, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) mov %rdi, %rax pop %r14 pop %r13 pop %r12 ret .Lfe3: .size gf256_neg, .Lfe3-(gf256_neg) .p2align 4, 0x90 .globl gf256_div2 .type gf256_div2, @function gf256_div2: push %r12 push %r13 push %r14 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 xor %r14, %r14 xor %rsi, %rsi mov %r8, %rax mov %r9, %rcx mov %r10, %r12 mov %r11, %r13 addq (%rdx), %rax adcq (8)(%rdx), %rcx adcq (16)(%rdx), %r12 adcq (24)(%rdx), %r13 adc $(0), %r14 test $(1), %r8 cmovne %rax, %r8 cmovne %rcx, %r9 cmovne %r12, %r10 cmovne %r13, %r11 cmovne %r14, %rsi shrd $(1), %r9, %r8 shrd $(1), %r10, %r9 shrd $(1), %r11, %r10 shrd $(1), %rsi, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) mov %rdi, %rax pop %r14 pop %r13 pop %r12 ret .Lfe4: .size gf256_div2, .Lfe4-(gf256_div2) .p2align 4, 0x90 .globl gf256_mulm .type gf256_mulm, @function gf256_mulm: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 sub $(24), %rsp movq %rdi, (%rsp) mov %rdx, %rbx mov %rcx, %rdi movq %r8, (8)(%rsp) movq (%rbx), %r14 movq (8)(%rsp), %r15 movq (%rsi), %rax mul %r14 mov %rax, %r8 mov %rdx, %r9 imul %r8, %r15 movq (8)(%rsi), %rax mul %r14 add %rax, %r9 adc $(0), %rdx mov %rdx, %r10 movq (16)(%rsi), %rax mul %r14 add %rax, %r10 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rsi), %rax mul %r14 add %rax, %r11 adc $(0), %rdx mov %rdx, %r12 xor %r13, %r13 movq (%rdi), %rax mul %r15 add %rax, %r8 adc $(0), %rdx mov %rdx, %r8 movq (8)(%rdi), %rax mul %r15 add %r8, %r9 adc $(0), %rdx add %rax, %r9 adc $(0), %rdx mov %rdx, %r8 movq (16)(%rdi), %rax mul %r15 add %r8, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %r8 movq (24)(%rdi), %rax mul %r15 add %r8, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx add %rdx, %r12 adc $(0), %r13 xor %r8, %r8 movq (8)(%rbx), %r14 movq (8)(%rsp), %r15 movq (%rsi), %rax mul %r14 add %rax, %r9 adc $(0), %rdx mov %rdx, %rcx imul %r9, %r15 movq (8)(%rsi), %rax mul %r14 add %rcx, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rsi), %rax mul %r14 add %rcx, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rsi), %rax mul %r14 add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc %rdx, %r13 adc $(0), %r8 movq (%rdi), %rax mul %r15 add %rax, %r9 adc $(0), %rdx mov %rdx, %r9 movq (8)(%rdi), %rax mul %r15 add %r9, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %r9 movq (16)(%rdi), %rax mul %r15 add %r9, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %r9 movq (24)(%rdi), %rax mul %r15 add %r9, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx add %rdx, %r13 adc $(0), %r8 xor %r9, %r9 movq (16)(%rbx), %r14 movq (8)(%rsp), %r15 movq (%rsi), %rax mul %r14 add %rax, %r10 adc $(0), %rdx mov %rdx, %rcx imul %r10, %r15 movq (8)(%rsi), %rax mul %r14 add %rcx, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rsi), %rax mul %r14 add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rsi), %rax mul %r14 add %rcx, %r13 adc $(0), %rdx add %rax, %r13 adc %rdx, %r8 adc $(0), %r9 movq (%rdi), %rax mul %r15 add %rax, %r10 adc $(0), %rdx mov %rdx, %r10 movq (8)(%rdi), %rax mul %r15 add %r10, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %r10 movq (16)(%rdi), %rax mul %r15 add %r10, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %r10 movq (24)(%rdi), %rax mul %r15 add %r10, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx add %rdx, %r8 adc $(0), %r9 xor %r10, %r10 movq (24)(%rbx), %r14 movq (8)(%rsp), %r15 movq (%rsi), %rax mul %r14 add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx imul %r11, %r15 movq (8)(%rsi), %rax mul %r14 add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rsi), %rax mul %r14 add %rcx, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rsi), %rax mul %r14 add %rcx, %r8 adc $(0), %rdx add %rax, %r8 adc %rdx, %r9 adc $(0), %r10 movq (%rdi), %rax mul %r15 add %rax, %r11 adc $(0), %rdx mov %rdx, %r11 movq (8)(%rdi), %rax mul %r15 add %r11, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %r11 movq (16)(%rdi), %rax mul %r15 add %r11, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rdi), %rax mul %r15 add %r11, %r8 adc $(0), %rdx add %rax, %r8 adc $(0), %rdx add %rdx, %r9 adc $(0), %r10 xor %r11, %r11 movq (%rsp), %rsi mov %r12, %rax mov %r13, %rbx mov %r8, %rcx mov %r9, %rdx subq (%rdi), %rax sbbq (8)(%rdi), %rbx sbbq (16)(%rdi), %rcx sbbq (24)(%rdi), %rdx sbb $(0), %r10 cmovnc %rax, %r12 cmovnc %rbx, %r13 cmovnc %rcx, %r8 cmovnc %rdx, %r9 movq %r12, (%rsi) movq %r13, (8)(%rsi) movq %r8, (16)(%rsi) movq %r9, (24)(%rsi) mov %rsi, %rax add $(24), %rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret .Lfe5: .size gf256_mulm, .Lfe5-(gf256_mulm) .p2align 4, 0x90 .globl gf256_sqrm .type gf256_sqrm, @function gf256_sqrm: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 sub $(24), %rsp movq %rdi, (%rsp) mov %rdx, %rdi movq %rcx, (8)(%rsp) movq (%rsi), %rbx movq (8)(%rsi), %rax mul %rbx mov %rax, %r9 mov %rdx, %r10 movq (16)(%rsi), %rax mul %rbx add %rax, %r10 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rsi), %rax mul %rbx add %rax, %r11 adc $(0), %rdx mov %rdx, %r12 movq (8)(%rsi), %rbx movq (16)(%rsi), %rax mul %rbx add %rax, %r11 adc $(0), %rdx mov %rdx, %rbp movq (24)(%rsi), %rax mul %rbx add %rax, %r12 adc $(0), %rdx add %rbp, %r12 adc $(0), %rdx mov %rdx, %r13 movq (16)(%rsi), %rbx movq (24)(%rsi), %rax mul %rbx add %rax, %r13 adc $(0), %rdx mov %rdx, %r14 xor %r15, %r15 shld $(1), %r14, %r15 shld $(1), %r13, %r14 shld $(1), %r12, %r13 shld $(1), %r11, %r12 shld $(1), %r10, %r11 shld $(1), %r9, %r10 shl $(1), %r9 movq (%rsi), %rax mul %rax mov %rax, %r8 add %rdx, %r9 adc $(0), %r10 movq (8)(%rsi), %rax mul %rax add %rax, %r10 adc %rdx, %r11 adc $(0), %r12 movq (16)(%rsi), %rax mul %rax add %rax, %r12 adc %rdx, %r13 adc $(0), %r14 movq (24)(%rsi), %rax mul %rax add %rax, %r14 adc %rdx, %r15 movq (8)(%rsp), %rcx imul %r8, %rcx movq (%rdi), %rax mul %rcx add %rax, %r8 adc $(0), %rdx mov %rdx, %r8 movq (8)(%rdi), %rax mul %rcx add %r8, %r9 adc $(0), %rdx add %rax, %r9 adc $(0), %rdx mov %rdx, %r8 movq (16)(%rdi), %rax mul %rcx add %r8, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %r8 movq (24)(%rdi), %rax mul %rcx add %r8, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx add %rdx, %r12 adc $(0), %r13 xor %r8, %r8 movq (8)(%rsp), %rcx imul %r9, %rcx movq (%rdi), %rax mul %rcx add %rax, %r9 adc $(0), %rdx mov %rdx, %r9 movq (8)(%rdi), %rax mul %rcx add %r9, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %r9 movq (16)(%rdi), %rax mul %rcx add %r9, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %r9 movq (24)(%rdi), %rax mul %rcx add %r9, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx add %rdx, %r13 adc $(0), %r14 xor %r9, %r9 movq (8)(%rsp), %rcx imul %r10, %rcx movq (%rdi), %rax mul %rcx add %rax, %r10 adc $(0), %rdx mov %rdx, %r10 movq (8)(%rdi), %rax mul %rcx add %r10, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %r10 movq (16)(%rdi), %rax mul %rcx add %r10, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %r10 movq (24)(%rdi), %rax mul %rcx add %r10, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx add %rdx, %r14 adc $(0), %r15 xor %r10, %r10 movq (8)(%rsp), %rcx imul %r11, %rcx movq (%rdi), %rax mul %rcx add %rax, %r11 adc $(0), %rdx mov %rdx, %r11 movq (8)(%rdi), %rax mul %rcx add %r11, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %r11 movq (16)(%rdi), %rax mul %rcx add %r11, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rdi), %rax mul %rcx add %r11, %r14 adc $(0), %rdx add %rax, %r14 adc $(0), %rdx add %rdx, %r15 adc $(0), %r8 xor %r11, %r11 movq (%rsp), %rsi mov %r12, %rax mov %r13, %rbx mov %r14, %rcx mov %r15, %rdx subq (%rdi), %rax sbbq (8)(%rdi), %rbx sbbq (16)(%rdi), %rcx sbbq (24)(%rdi), %rdx sbb $(0), %r8 cmovnc %rax, %r12 cmovnc %rbx, %r13 cmovnc %rcx, %r14 cmovnc %rdx, %r15 movq %r12, (%rsi) movq %r13, (8)(%rsi) movq %r14, (16)(%rsi) movq %r15, (24)(%rsi) mov %rsi, %rax add $(24), %rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret .Lfe6: .size gf256_sqrm, .Lfe6-(gf256_sqrm)
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.24.28316.0 TITLE C:\Users\Anubis\Desktop\UA\UAADCProjects\Individual\Parte1\EjerciciosEnsamblador\Ejemplo1\Suma.cpp .686P .XMM include listing.inc .model flat INCLUDELIB MSVCRTD INCLUDELIB OLDNAMES msvcjmc SEGMENT __D9A2886B_corecrt_stdio_config@h DB 01H __FA4B997B_corecrt_wstdio@h DB 01H __4C6EA709_stdio@h DB 01H msvcjmc ENDS PUBLIC __JustMyCode_Default ; Function compile flags: /Odt ; COMDAT __JustMyCode_Default _TEXT SEGMENT __JustMyCode_Default PROC ; COMDAT push ebp mov ebp, esp pop ebp ret 0 __JustMyCode_Default ENDP _TEXT ENDS END
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "net.h" #include "addrman.h" #include "chainparams.h" #include "core.h" #include "ui_interface.h" #ifdef WIN32 #include <string.h> #else #include <fcntl.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniupnpc.h> #include <miniupnpc/miniwget.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif #include <boost/filesystem.hpp> #include <boost/thread.hpp> // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version. #ifdef WIN32 #ifndef PROTECTION_LEVEL_UNRESTRICTED #define PROTECTION_LEVEL_UNRESTRICTED 10 #endif #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 23 #endif #endif using std::string; using std::vector; using std::list; using std::map; using std::deque; using std::pair; using std::set; namespace { const int MAX_OUTBOUND_CONNECTIONS = 8; struct ListenSocket { SOCKET socket; bool whitelisted; ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {} }; } // // Global state variables // bool fDiscover = true; bool fListen = true; uint64_t nLocalServices = NODE_NETWORK; CCriticalSection cs_mapLocalHost; map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; static CNode* pnodeSync = NULL; uint64_t nLocalHostNonce = 0; static vector<ListenSocket> vhListenSocket; CAddrMan addrman; int nMaxConnections = 125; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<string> vAddedNodes; CCriticalSection cs_vAddedNodes; NodeId nLastNodeId = 0; CCriticalSection cs_nLastNodeId; static CSemaphore *semOutbound = NULL; // Signals for message handling static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (!fListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",0),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); } return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; while (true) { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed LogPrint("net", "socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr)); return false; } } } } // used when scores of local addresses may have changed // pushes better local address to peers void static AdvertizeLocal() { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal) { pnode->PushAddress(addrLocal); pnode->addrLocal = addrLocal; } } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } AdvertizeLocal(); return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } AdvertizeLocal(); return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given network is one we can probably connect to */ bool IsReachable(enum Network net) { LOCK(cs_mapLocalHost); return vfReachable[net] && !vfLimited[net]; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { enum Network net = addr.GetNetwork(); return IsReachable(net); } bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet) { SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) return error("%s() : connection to %s failed", __func__, addrConnect.ToString()); send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL); string strLine; while (RecvLine(hSocket, strLine)) { if (strLine.empty()) { // HTTP response is separated from headers by blank line while (true) { if (!RecvLine(hSocket, strLine)) { CloseSocket(hSocket); return false; } if (pszKeyword == NULL) break; if (strLine.find(pszKeyword) != string::npos) { strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword)); break; } } CloseSocket(hSocket); if (strLine.find("<") != string::npos) strLine = strLine.substr(0, strLine.find("<")); strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r")); while (strLine.size() > 0 && isspace(strLine[strLine.size()-1])) strLine.resize(strLine.size()-1); CService addr(strLine,0,true); LogPrintf("%s() received [%s] %s\n", __func__, strLine, addr.ToString()); if (!addr.IsValid() || !addr.IsRoutable()) return false; ipRet.SetIP(addr); return true; } } CloseSocket(hSocket); return error("GetMyExternalIP() : connection closed"); } bool GetMyExternalIP(CNetAddr& ipRet) { CService addrConnect; const char* pszGet; const char* pszKeyword; for (int nLookup = 0; nLookup <= 1; nLookup++) for (int nHost = 1; nHost <= 1; nHost++) { // We should be phasing out our use of sites like these. If we need // replacements, we should ask for volunteers to put this simple // php file on their web server that prints the client IP: // <?php echo $_SERVER["REMOTE_ADDR"]; ?> if (nHost == 1) { addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org if (nLookup == 1) { CService addrIP("checkip.dyndns.org", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET / HTTP/1.1\r\n" "Host: checkip.dyndns.org\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = "Address:"; } if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet)) return true; } return false; } void ThreadGetMyExternalIP() { CNetAddr addrLocalHost; if (GetMyExternalIP(addrLocalHost)) { LogPrintf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP()); AddLocal(addrLocalHost, LOCAL_HTTP); } } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return NULL; } CNode* FindNode(const string& addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); return pnode; } } /// debug print LogPrint("net", "trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort()) : ConnectSocket(addrConnect, hSocket)) { addrman.Attempt(addrConnect); // Set to non-blocking if (!SetSocketNonBlocking(hSocket, true)) LogPrintf("ConnectNode: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } return NULL; } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { LogPrint("net", "disconnecting peer=%d\n", id); CloseSocket(hSocket); } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); // if this was the sync node, we'll need a new one if (this == pnodeSync) pnodeSync = NULL; } void CNode::PushVersion() { int nBestHeight = g_signals.GetHeight().get_value_or(0); /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); if (fLogIPs) LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id); else LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, vector<string>()), nBestHeight, true); } map<CNetAddr, int64_t> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); map<CNetAddr, int64_t>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Ban(const CNetAddr &addr) { int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } return true; } vector<CSubNet> CNode::vWhitelistedRange; CCriticalSection CNode::cs_vWhitelistedRange; bool CNode::IsWhitelistedRange(const CNetAddr &addr) { LOCK(cs_vWhitelistedRange); BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) { if (subnet.Match(addr)) return true; } return false; } void CNode::AddWhitelistedRange(const CSubNet &subnet) { LOCK(cs_vWhitelistedRange); vWhitelistedRange.push_back(subnet); } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { stats.nodeid = this->GetId(); X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(cleanSubVer); X(fInbound); X(nStartingHeight); X(nSendBytes); X(nRecvBytes); X(fWhitelisted); stats.fSyncNode = (this == pnodeSync); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : ""; } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; pch += handled; nBytes -= handled; if (msg.complete()) msg.nTime = GetTimeMicros(); } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (std::exception &e) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf("socket send error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); hSocketMax = std::max(hSocketMax, hListenSocket.socket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes){ if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = std::max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && ( pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf("socket select error %s\n", NetworkErrorString(nErr)); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) { if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) LogPrintf("Warning: Unknown socket family\n"); bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr)); } else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) { CloseSocket(hSocket); } else if (CNode::IsBanned(addr) && !whitelisted) { LogPrintf("connection from %s dropped (banned)\n", addr.ToString()); CloseSocket(hSocket); } else { CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); pnode->fWhitelisted = whitelisted; { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) LogPrint("net", "socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf("socket recv error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60)) { LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } MilliSleep(10); } } #ifdef USE_UPNP void ThreadMapPort() { string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #else /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if (r != UPNPCOMMAND_SUCCESS) LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if (externalIPAddress[0]) { LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "Bitcoin " + FormatFullVersion(); try { while (true) { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if (r!=UPNPCOMMAND_SUCCESS) LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else LogPrintf("UPnP Port Mapping successful.\n");; MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif void ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute if ((addrman.size() > 0) && (!GetBoolArg("-forcednsseed", false))) { MilliSleep(11 * 1000); LOCK(cs_vNodes); if (vNodes.size() >= 2) { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); return; } } const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { vector<CNetAddr> vIPs; vector<CAddress> vAdd; if (LookupHost(seed.host.c_str(), vIPs)) { BOOST_FOREACH(CNetAddr& ip, vIPs) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(seed.name, true)); } } LogPrintf("%d addresses found from DNS seeds\n", found); } void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0; ; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) MilliSleep(500); } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1")); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections) CAddress addr = addrman.Select(10 + std::min(nOutbound,8)*10); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while(true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH(string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, lAddresses) { vector<CService> vservNode(0); if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!pszDest) { if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort())) return false; } else if (FindNode(pszDest)) return false; CNode* pnode = ConnectNode(addrConnect, pszDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } // for now, use a very simple selection metric: the node from which we received // most recently static int64_t NodeSyncScore(const CNode *pnode) { return pnode->nLastRecv; } void static StartSync(const vector<CNode*> &vNodes) { CNode *pnodeNewSync = NULL; int64_t nBestScore = 0; int nBestHeight = g_signals.GetHeight().get_value_or(0); // Iterate over all nodes BOOST_FOREACH(CNode* pnode, vNodes) { // check preconditions for allowing a sync if (!pnode->fClient && !pnode->fOneShot && !pnode->fDisconnect && pnode->fSuccessfullyConnected && (pnode->nStartingHeight > (nBestHeight - 144)) && (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) { // if ok, compare node's score with the best so far int64_t nScore = NodeSyncScore(pnode); if (pnodeNewSync == NULL || nScore > nBestScore) { pnodeNewSync = pnode; nBestScore = nScore; } } } // if a new sync candidate was found, start sync! if (pnodeNewSync) { pnodeNewSync->fStartSync = true; pnodeSync = pnodeNewSync; } } void ThreadMessageHandler() { SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { bool fHaveSyncNode = false; vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { pnode->AddRef(); if (pnode == pnodeSync) fHaveSyncNode = true; } } if (!fHaveSyncNode) StartSync(vNodesCopy); // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!g_signals.ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) fSleep = false; } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) g_signals.SendMessages(pnode, pnode == pnodeTrickle); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } if (fSleep) MilliSleep(100); } } bool BindListenPort(const CService &addrBind, string& strError, bool fWhitelisted) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString()); LogPrintf("%s\n", strError); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } #ifndef WIN32 #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows! setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif // Set to non-blocking, incoming connections will also inherit this if (!SetSocketNonBlocking(hListenSocket, true)) { strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin Core is probably already running."), addrBind.ToString()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr)); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } LogPrintf("Bound to %s\n", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted)); if (addrBind.IsRoutable() && fDiscover && !fWhitelisted) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) BOOST_FOREACH (const CNetAddr &addr, vaddr) AddLocal(addr, LOCAL_IF); } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif // Don't use external IPv4 discovery, when -onlynet="IPv6" if (!IsLimited(NET_IPV4)) threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "ext-ip", &ThreadGetMyExternalIP)); } void StartNode(boost::thread_group& threadGroup) { if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(threadGroup); // // Start threads // if (!GetBoolArg("-dnsseed", true)) LogPrintf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed)); // Map ports with UPnP MapPort(GetBoolArg("-upnp", DEFAULT_UPNP)); // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); } bool StopNode() { LogPrintf("StopNode()\n"); MapPort(false); if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); MilliSleep(50); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() {} ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) CloseSocket(pnode->hSocket); BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket) if (hListenSocket.socket != INVALID_SOCKET) if (!CloseSocket(hListenSocket.socket)) LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError())); // clean up some globals (to help leak detection) BOOST_FOREACH(CNode *pnode, vNodes) delete pnode; BOOST_FOREACH(CNode *pnode, vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); vhListenSocket.clear(); delete semOutbound; semOutbound = NULL; delete pnodeLocalHost; pnodeLocalHost = NULL; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void RelayTransaction(const CTransaction& tx) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, ss); } void RelayTransaction(const CTransaction& tx, const CDataStream& ss) { CInv inv(MSG_TX, tx.GetHash()); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); if (pnode->pfilter) { if (pnode->pfilter->IsRelevantAndUpdate(tx)) pnode->PushInventory(inv); } else pnode->PushInventory(inv); } } void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } void CNode::Fuzz(int nChance) { if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages switch (GetRand(3)) { case 0: // xor a random byte with a random value: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend[pos] ^= (unsigned char)(GetRand(256)); } break; case 1: // delete a random byte: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend.erase(ssSend.begin()+pos); } break; case 2: // insert a random byte at a random position { CDataStream::size_type pos = GetRand(ssSend.size()); char ch = (char)GetRand(256); ssSend.insert(ssSend.begin()+pos, ch); } break; } // Chance of more than one change half the time: // (more changes exponentially less likely): Fuzz(2); } // // CAddrDB // CAddrDB::CAddrDB() { pathAddr = GetDataDir() / "peers.dat"; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); string tmpfn = strprintf("peers.dat.%04x", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open temp output file, and associate with CAutoFile boost::filesystem::path pathTmp = GetDataDir() / tmpfn; FILE *file = fopen(pathTmp.string().c_str(), "wb"); CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION); if (!fileout) return error("%s : Failed to open file %s", __func__, pathTmp.string()); // Write and commit header, data try { fileout << ssPeers; } catch (std::exception &e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } FileCommit(fileout); fileout.fclose(); // replace existing peers.dat, if any, with new peers.dat.XXXX if (!RenameOver(pathTmp, pathAddr)) return error("%s : Rename-into-place failed", __func__); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE *file = fopen(pathAddr.string().c_str(), "rb"); CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION); if (!filein) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathAddr); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception &e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error("%s : Checksum mismatch, data corrupted", __func__); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("%s : Invalid network magic number", __func__); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (std::exception &e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } return true; } unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); } unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); } CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000) { nServices = 0; hSocket = hSocketIn; nRecvVersion = INIT_PROTO_VERSION; nLastSend = 0; nLastRecv = 0; nSendBytes = 0; nRecvBytes = 0; nTimeConnected = GetTime(); addr = addrIn; addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = ""; fWhitelisted = false; fOneShot = false; fClient = false; // set by version message fInbound = fInboundIn; fNetworkNode = false; fSuccessfullyConnected = false; fDisconnect = false; nRefCount = 0; nSendSize = 0; nSendOffset = 0; hashContinue = 0; pindexLastGetBlocksBegin = 0; hashLastGetBlocksEnd = 0; nStartingHeight = -1; fStartSync = false; fGetAddr = false; fRelayTxes = false; setInventoryKnown.max_size(SendBufferSize() / 1000); pfilter = new CBloomFilter(); nPingNonceSent = 0; nPingUsecStart = 0; nPingUsecTime = 0; fPingQueued = false; { LOCK(cs_nLastNodeId); id = nLastNodeId++; } if (fLogIPs) LogPrint("net", "Added connection to %s peer=%d\n", addrName, id); else LogPrint("net", "Added connection peer=%d\n", id); // Be shy and don't send version until we hear if (hSocket != INVALID_SOCKET && !fInbound) PushVersion(); GetNodeSignals().InitializeNode(GetId(), this); } CNode::~CNode() { CloseSocket(hSocket); if (pfilter) delete pfilter; GetNodeSignals().FinalizeNode(GetId()); } void CNode::AskFor(const CInv& inv) { // We're using mapAskFor as a priority queue, // the key is the earliest time the request can be sent int64_t nRequestTime; limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv); if (it != mapAlreadyAskedFor.end()) nRequestTime = it->second; else nRequestTime = 0; LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str(), id); // Make sure not to reuse time indexes to keep things in the same order int64_t nNow = GetTimeMicros() - 1000000; static int64_t nLastTime; ++nLastTime; nNow = std::max(nNow, nLastTime); nLastTime = nNow; // Each retry is 2 minutes after the last nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow); if (it != mapAlreadyAskedFor.end()) mapAlreadyAskedFor.update(it, nRequestTime); else mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime)); mapAskFor.insert(std::make_pair(nRequestTime, inv)); } void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend) { ENTER_CRITICAL_SECTION(cs_vSend); assert(ssSend.size() == 0); ssSend << CMessageHeader(pszCommand, 0); LogPrint("net", "sending: %s ", pszCommand); } void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend) { ssSend.clear(); LEAVE_CRITICAL_SECTION(cs_vSend); LogPrint("net", "(aborted)\n"); } void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend) { // The -*messagestest options are intentionally not documented in the help message, // since they are only used during development to debug the networking code and are // not intended for end-users. if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) { LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n"); AbortMessage(); return; } if (mapArgs.count("-fuzzmessagestest")) Fuzz(GetArg("-fuzzmessagestest", 10)); if (ssSend.size() == 0) return; // Set the size unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE; memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize)); // Set the checksum uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end()); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum)); memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum)); LogPrint("net", "(%d bytes) peer=%d\n", nSize, id); deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData()); ssSend.GetAndClear(*it); nSendSize += (*it).size(); // If write queue empty, attempt "optimistic write" if (it == vSendMsg.begin()) SocketSendData(this); LEAVE_CRITICAL_SECTION(cs_vSend); } // // CNetRecord // boost::once_flag CNetRecorder::init_flag_ = BOOST_ONCE_INIT; boost::filesystem::path CNetRecorder::path_addr_; CNetRecorder::CFileWriter CNetRecorder::recorder_; void CNetRecorder::Init_() { path_addr_ = GetDataDir() / "netinfo.dat"; recorder_.Open(path_addr_); } void CNetRecorder::TryInit_() { call_once(CNetRecorder::Init_, CNetRecorder::init_flag_); } void CNetRecorder::SaveRTT(string addr, int64_t when, int64_t rtt) { TryInit_(); CRTTRecord rec(addr, when, rtt); recorder_.Write(dynamic_cast<CRecord*>(&rec)); } void CNetRecorder::SaveBandwidth(string addr, int64_t when, int64_t bandwidth) { TryInit_(); CBandwidthRecord rec(addr, when, bandwidth); recorder_.Write(dynamic_cast<CRecord*>(&rec)); } json_spirit::Object CNetRecorder::QueryRTT( string addr, int64_t start_time, int64_t end_time, int64_t unit, double result_unit_per_system_unit) { TryInit_(); size_t size = (end_time - start_time + unit - 1) / unit; vector<double> rtt(size, 0.0); vector<int> num(size, 0); set<string> addresses; CFileReader reader(path_addr_); for (CRTTRecord rec; reader.FetchNext(&rec); ) { if (rec.when() < start_time || end_time <= rec.when() || (addr != "" && rec.address() != addr)) { continue; } int64_t index = (rec.when() - start_time) / unit; rtt[index] += rec.rtt(); num[index] += 1; addresses.insert(rec.address()); } for (size_t i = 0; i < size; ++i) { if (num[i] != 0) { rtt[i] = rtt[i] / num[i] * result_unit_per_system_unit; } else { rtt[i] = 0; } } json_spirit::Array arr; for (size_t i = 0; i < size; ++i) { json_spirit::Object obj; obj.push_back(json_spirit::Pair("time", start_time + unit * i)); obj.push_back(json_spirit::Pair("rtt", rtt[i])); arr.push_back(obj); } json_spirit::Object ret; ret.push_back(json_spirit::Pair("since", int(start_time))); ret.push_back(json_spirit::Pair("until", int(end_time))); ret.push_back(json_spirit::Pair("unit", int(unit))); ret.push_back(json_spirit::Pair("node_num", int(addresses.size()))); if (addr != "") { ret.push_back(json_spirit::Pair("node_id", addr)); } ret.push_back(json_spirit::Pair("rtts", arr)); return ret; } json_spirit::Object CNetRecorder::QueryBandwidth( string addr, int64_t start_time, int64_t end_time, int64_t unit, double result_unit_per_system_unit) { TryInit_(); size_t size = (end_time - start_time + unit - 1) / unit; // ceiling. vector<double> bandwidthes(size, 0); set<string> addresses; CFileReader reader(path_addr_); for (CBandwidthRecord rec; reader.FetchNext(&rec); ) { if (rec.when() < start_time || end_time <= rec.when() || (addr != "" && rec.address() != addr)) { continue; } addresses.insert(rec.address()); int64_t index = (rec.when() - start_time) / unit; bandwidthes[index] += rec.bandwidth(); } for (size_t i = 0; i < size; ++i) { bandwidthes[i] = bandwidthes[i] * result_unit_per_system_unit; } json_spirit::Array arr; for (size_t i = 0; i < size; ++i) { json_spirit::Object obj; obj.push_back(json_spirit::Pair("time", start_time + unit * i)); obj.push_back(json_spirit::Pair("bandwidth", bandwidthes[i])); arr.push_back(obj); } json_spirit::Object ret; ret.push_back(json_spirit::Pair("since", int(start_time))); ret.push_back(json_spirit::Pair("until", int(end_time))); ret.push_back(json_spirit::Pair("unit", int(unit))); ret.push_back(json_spirit::Pair("node_num", int(addresses.size()))); if (addr != "") ret.push_back(json_spirit::Pair("node_id", addr)); ret.push_back(json_spirit::Pair("bandwidth", arr)); return ret; } // // CNetRecorder::CRTRecord // int16_t CNetRecorder::CRTTRecord::size() const { return sizeof(int16_t) + address_.length() + sizeof(int64_t) * 2; } void CNetRecorder::CRTTRecord::WriteToBuffer(char* buffer) const { int16_t len = address_.length(); memcpy((void*)buffer, (void const*)(&len), sizeof(len)); buffer += sizeof(len); memcpy((void*)buffer, (void const*)address_.c_str(), len); buffer += len; memcpy((void*)buffer, (void const*)(&when_), sizeof(when_)); buffer += sizeof(when_); memcpy((void*)buffer, (void const*)(&rtt_), sizeof(rtt_)); } void CNetRecorder::CRTTRecord::ReadFromBuffer(char const* buffer) { int16_t len; memcpy((void*)(&len), (void const*)buffer, sizeof(len)); buffer += sizeof(len); address_ = string(buffer, len); buffer += len; memcpy((void*)(&when_), (void const*)buffer, sizeof(when_)); buffer += sizeof(when_); memcpy((void*)(&rtt_), (void const*)buffer, sizeof(rtt_)); } // // CNetRecorder::CBandwidthRecord // int16_t CNetRecorder::CBandwidthRecord::size() const { return sizeof(int16_t) + address_.length() + sizeof(int64_t) * 2; } void CNetRecorder::CBandwidthRecord::WriteToBuffer(char* buffer) const { int16_t len = address_.length(); memcpy((void*)buffer, (void const*)(&len), sizeof(len)); buffer += sizeof(len); memcpy((void*)buffer, (void const*)address_.c_str(), len); buffer += len; memcpy((void*)buffer, (void const*)(&when_), sizeof(when_)); buffer += sizeof(when_); memcpy((void*)buffer, (void const*)(&bandwidth_), sizeof(bandwidth_)); } void CNetRecorder::CBandwidthRecord::ReadFromBuffer(char const* buffer) { int16_t len; memcpy((void*)(&len), (void const*)buffer, sizeof(len)); buffer += sizeof(len); address_ = string(buffer, len); buffer += len; memcpy((void*)(&when_), (void const*)buffer, sizeof(when_)); buffer += sizeof(when_); memcpy((void*)(&bandwidth_), (void const*)buffer, sizeof(bandwidth_)); } // // CNetRecorder::CFileWriter // void CNetRecorder::CFileWriter::Open(boost::filesystem::path path) { TryCreateFileIfNeed_(path); fp_ = fopen(path.string().c_str(), "rb+"); if (fp_ == NULL) LogPrint("recorder", "cannot open the file\n"); else SeekToLastValidPos_(); } void CNetRecorder::CFileWriter::Write(CNetRecorder::CRecord const* rec) { if (fp_ == NULL) return; size_t total_size = sizeof(SFileRecordHeader) + rec->size(); char* buffer = new char[total_size]; SFileRecordHeader* header = new((void*)(buffer)) SFileRecordHeader; header->type = rec->type(); header->size = rec->size(); rec->WriteToBuffer(buffer + sizeof(SFileRecordHeader)); if (fwrite((void*)(buffer), total_size, 1, fp_) < 1) LogPrint("record", "cannot write to file\n"); header->~SFileRecordHeader(); delete [] buffer; fflush(fp_); } void CNetRecorder::CFileWriter::TryCreateFileIfNeed_( boost::filesystem::path path) const { // TODO: Find a better way... FILE* fp = fopen(path.string().c_str(), "a"); if (fp != NULL) fclose(fp); } void CNetRecorder::CFileWriter::SeekToLastValidPos_() { while (true) { SFileRecordHeader head; if (fread((void*)(&head), sizeof(head), 1, fp_) < 1) break; if (fseek(fp_, head.size, SEEK_CUR) != 0) { fseek(fp_, -ssize_t(sizeof(head)), SEEK_CUR); // offset back. break; } } } // // CNetRecorder::CFileReader // CNetRecorder::CFileReader::CFileReader(boost::filesystem::path path) { fp_ = fopen(path.string().c_str(), "rb"); if (fp_ == NULL) LogPrint("recorder", "cannot reads the file\n"); } CNetRecorder::CFileReader::~CFileReader() { if (fp_ != NULL) fclose(fp_); } bool CNetRecorder::CFileReader::FetchNext(CNetRecorder::CRecord* rec) { if (fp_ == NULL) return false; SFileRecordHeader head; while (true) { if (fread((void*)(&head), sizeof(head), 1, fp_) < 1) return false; if (head.type != rec->type()) { if (fseek(fp_, head.size, SEEK_CUR) != 0) return false; continue; } break; } char* buf = new char[head.size]; if (fread((void*)(buf), head.size, 1, fp_) < 1) { return false; } rec->ReadFromBuffer((char const*)buf); delete [] buf; return true; }
; A327582: a(n) = (17 * 7^(2*n+1) + 1)/24. Sequence related to the properties of the partition function A000041 modulo a power of 7. ; 5,243,11905,583343,28583805,1400606443,68629715705,3362856069543,164779947407605,8074217422972643,395636653725659505,19386196032557315743,949923605595308471405,46546256674170115098843,2280766577034335639843305,111757562274682446352321943,5476120551459439871263775205,268329907021512553691924985043,13148165444054115130904324267105,644260106758651641414311889088143,31568745231173930429301282565319005 mov $1,49 pow $1,$0 div $1,48 mul $1,238 add $1,5 mov $0,$1
; ; file: asm_main.asm %include "asm_io.inc" ; ; initialized data is put in the .data segment ; segment .data ; uninitialized data is put in the .bss segment ; segment .bss ; ; code is put in the .text segment ; segment .text global asm_main asm_main: enter 0,0 ; setup routine pusha ; next print out result message as series of steps popa mov eax, 0 ; return back to C leave ret
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #ifndef NT2_TOOLBOX_PREDICATES_FUNCTION_SIMD_SSE_SSE4A_IS_NOT_INFINITE_HPP_INCLUDED #define NT2_TOOLBOX_PREDICATES_FUNCTION_SIMD_SSE_SSE4A_IS_NOT_INFINITE_HPP_INCLUDED #include <nt2/toolbox/predicates/function/simd/sse/ssse3/is_not_infinite.hpp> #endif
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r14 push %r15 push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x1c62, %rdx nop nop nop sub $23144, %rcx mov (%rdx), %edi nop nop nop nop xor $20958, %r14 lea addresses_A_ht+0x1b062, %r11 nop xor %r13, %r13 mov (%r11), %r15d nop inc %r13 lea addresses_WC_ht+0x167ae, %rsi lea addresses_WT_ht+0xaf2, %rdi nop nop nop nop nop xor %r14, %r14 mov $53, %rcx rep movsb nop nop cmp $6431, %rsi lea addresses_normal_ht+0x17e86, %rsi lea addresses_WT_ht+0x19cc2, %rdi nop xor %r15, %r15 mov $14, %rcx rep movsq nop nop add %rcx, %rcx lea addresses_normal_ht+0xd0a2, %rsi lea addresses_WT_ht+0xd692, %rdi clflush (%rdi) nop nop nop nop dec %r14 mov $107, %rcx rep movsb nop nop nop cmp %rcx, %rcx lea addresses_A_ht+0xe1a2, %r13 add %rsi, %rsi movb $0x61, (%r13) add %rdx, %rdx lea addresses_normal_ht+0xc382, %r11 nop nop nop nop nop inc %r15 mov (%r11), %r14 nop nop add %rsi, %rsi lea addresses_WT_ht+0x1bca2, %r14 and $12459, %r15 movb (%r14), %r11b dec %rdi lea addresses_UC_ht+0x169a2, %r11 nop nop nop nop nop add %r13, %r13 movl $0x61626364, (%r11) nop nop nop sub $27844, %rsi lea addresses_WC_ht+0xb702, %r11 dec %rcx movb $0x61, (%r11) xor %rcx, %rcx lea addresses_normal_ht+0x110a2, %rdi cmp %rcx, %rcx mov $0x6162636465666768, %rsi movq %rsi, %xmm4 vmovups %ymm4, (%rdi) nop nop nop inc %r15 lea addresses_WT_ht+0x13aa2, %rsi lea addresses_D_ht+0x1c9b2, %rdi nop nop add $58491, %r11 mov $86, %rcx rep movsb nop nop sub $56953, %r11 pop %rsi pop %rdx pop %rdi pop %rcx pop %r15 pop %r14 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %r8 push %rbp push %rcx push %rdi // Store mov $0x7be, %rcx cmp $31341, %rbp mov $0x5152535455565758, %r13 movq %r13, (%rcx) nop cmp %r13, %r13 // Store lea addresses_RW+0x14ea2, %rdi xor %r8, %r8 mov $0x5152535455565758, %rcx movq %rcx, (%rdi) nop add %rbp, %rbp // Faulty Load lea addresses_A+0x138a2, %rbp nop nop nop nop nop xor $9437, %rcx mov (%rbp), %r8d lea oracles, %rbp and $0xff, %r8 shlq $12, %r8 mov (%rbp,%r8,1), %r8 pop %rdi pop %rcx pop %rbp pop %r8 pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_P', 'size': 8, 'AVXalign': True, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': True}} {'00': 2470, '33': 35} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 */
.word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x20 .word 0x74 .word 0xc8 .word 0x11c .word 0x170 .word 0x1c4 .word 0x218 .word 0x26c .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x26 .word 0x7a .word 0xce .word 0x122 .word 0x176 .word 0x1ca .word 0x21e .word 0x272 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x2c .word 0x80 .word 0xd4 .word 0x128 .word 0x17c .word 0x1d0 .word 0x224 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x32 .word 0x86 .word 0xda .word 0x12e .word 0x182 .word 0x1d6 .word 0x22a .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x38 .word 0x8c .word 0xe0 .word 0x134 .word 0x188 .word 0x1dc .word 0x230 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x44 .word 0x98 .word 0xec .word 0x140 .word 0x194 .word 0x1e8 .word 0x23c .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x4a .word 0x9e .word 0xf2 .word 0x146 .word 0x19a .word 0x1ee .word 0x242 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x50 .word 0xa4 .word 0xf8 .word 0x14c .word 0x1a0 .word 0x1f4 .word 0x248 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x56 .word 0xaa .word 0xfe .word 0x152 .word 0x1a6 .word 0x1fa .word 0x24e .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x8 .word 0x5c .word 0xb0 .word 0x104 .word 0x158 .word 0x1ac .word 0x200 .word 0x254 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0xe .word 0x62 .word 0xb6 .word 0x10a .word 0x15e .word 0x1b2 .word 0x206 .word 0x25a .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x14 .word 0x68 .word 0xbc .word 0x110 .word 0x164 .word 0x1b8 .word 0x20c .word 0x260 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0 .word 0x0
/****************************************************************************** * * Project: GDAL Core * Purpose: Read metadata from EROS imagery. * Author: Alexander Lisovenko * Author: Dmitry Baryshnikov, polimax@mail.ru * ****************************************************************************** * Copyright (c) 2014-2015, NextGIS info@nextgis.ru * * 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 "cpl_port.h" #include "reader_eros.h" #include <cstddef> #include <cstdio> #include <cstdlib> #include "cpl_conv.h" #include "cpl_error.h" #include "cpl_string.h" #include "cpl_time.h" CPL_CVSID("$Id$") /** * GDALMDReaderEROS() */ GDALMDReaderEROS::GDALMDReaderEROS(const char *pszPath, char **papszSiblingFiles) : GDALMDReaderBase(pszPath, papszSiblingFiles) { CPLString osBaseName = CPLGetBasename(pszPath); CPLString osDirName = CPLGetDirname(pszPath); char szMetadataName[512] = {0}; size_t i; if( osBaseName.size() > 511 ) return; for(i = 0; i < osBaseName.size(); i++) { if(STARTS_WITH_CI(osBaseName + i, ".")) { CPLString osPassFileName = CPLFormFilename( osDirName, szMetadataName, "pass" ); if (CPLCheckForFile(&osPassFileName[0], papszSiblingFiles)) { m_osIMDSourceFilename = osPassFileName; break; } else { osPassFileName = CPLFormFilename( osDirName, szMetadataName, "PASS" ); if (CPLCheckForFile(&osPassFileName[0], papszSiblingFiles)) { m_osIMDSourceFilename = osPassFileName; break; } } } szMetadataName[i] = osBaseName[i]; } if(m_osIMDSourceFilename.empty()) { CPLString osPassFileName = CPLFormFilename( osDirName, szMetadataName, "pass" ); if (CPLCheckForFile(&osPassFileName[0], papszSiblingFiles)) { m_osIMDSourceFilename = osPassFileName; } else { osPassFileName = CPLFormFilename( osDirName, szMetadataName, "PASS" ); if (CPLCheckForFile(&osPassFileName[0], papszSiblingFiles)) { m_osIMDSourceFilename = osPassFileName; } } } CPLString osRPCFileName = CPLFormFilename( osDirName, szMetadataName, "rpc" ); if (CPLCheckForFile(&osRPCFileName[0], papszSiblingFiles)) { m_osRPBSourceFilename = osRPCFileName; } else { osRPCFileName = CPLFormFilename( osDirName, szMetadataName, "RPC" ); if (CPLCheckForFile(&osRPCFileName[0], papszSiblingFiles)) { m_osRPBSourceFilename = osRPCFileName; } } if(!m_osIMDSourceFilename.empty() ) CPLDebug( "MDReaderEROS", "IMD Filename: %s", m_osIMDSourceFilename.c_str() ); if(!m_osRPBSourceFilename.empty() ) CPLDebug( "MDReaderEROS", "RPB Filename: %s", m_osRPBSourceFilename.c_str() ); } /** * ~GDALMDReaderEROS() */ GDALMDReaderEROS::~GDALMDReaderEROS() { } /** * HasRequiredFiles() */ bool GDALMDReaderEROS::HasRequiredFiles() const { if (!m_osIMDSourceFilename.empty()) return true; if (!m_osRPBSourceFilename.empty()) return true; return false; } /** * GetMetadataFiles() */ char** GDALMDReaderEROS::GetMetadataFiles() const { char **papszFileList = nullptr; if(!m_osIMDSourceFilename.empty()) papszFileList= CSLAddString( papszFileList, m_osIMDSourceFilename ); if(!m_osRPBSourceFilename.empty()) papszFileList = CSLAddString( papszFileList, m_osRPBSourceFilename ); return papszFileList; } /** * LoadMetadata() */ void GDALMDReaderEROS::LoadMetadata() { if(m_bIsMetadataLoad) return; if(!m_osIMDSourceFilename.empty()) { m_papszIMDMD = LoadImdTxtFile(); } if(!m_osRPBSourceFilename.empty()) { m_papszRPCMD = GDALLoadRPCFile( m_osRPBSourceFilename ); } m_papszDEFAULTMD = CSLAddNameValue(m_papszDEFAULTMD, MD_NAME_MDTYPE, "EROS"); m_bIsMetadataLoad = true; const char* pszSatId1 = CSLFetchNameValue(m_papszIMDMD, "satellite"); const char* pszSatId2 = CSLFetchNameValue(m_papszIMDMD, "camera"); if(nullptr != pszSatId1 && nullptr != pszSatId2) { m_papszIMAGERYMD = CSLAddNameValue(m_papszIMAGERYMD, MD_NAME_SATELLITE, CPLSPrintf( "%s %s", CPLStripQuotes(pszSatId1).c_str(), CPLStripQuotes(pszSatId2).c_str())); } else if(nullptr != pszSatId1 && nullptr == pszSatId2) { m_papszIMAGERYMD = CSLAddNameValue(m_papszIMAGERYMD, MD_NAME_SATELLITE, CPLStripQuotes(pszSatId1)); } else if(nullptr == pszSatId1 && nullptr != pszSatId2) { m_papszIMAGERYMD = CSLAddNameValue(m_papszIMAGERYMD, MD_NAME_SATELLITE, CPLStripQuotes(pszSatId2)); } const char* pszCloudCover = CSLFetchNameValue(m_papszIMDMD, "overall_cc"); if(nullptr != pszCloudCover) { int nCC = atoi(pszCloudCover); if(nCC > 100 || nCC < 0) { m_papszIMAGERYMD = CSLAddNameValue(m_papszIMAGERYMD, MD_NAME_CLOUDCOVER, MD_CLOUDCOVER_NA); } else { m_papszIMAGERYMD = CSLAddNameValue(m_papszIMAGERYMD, MD_NAME_CLOUDCOVER, CPLSPrintf("%d", nCC)); } } const char* pszDate = CSLFetchNameValue(m_papszIMDMD, "sweep_start_utc"); if(nullptr != pszDate) { char buffer[80]; GIntBig timeMid = GetAcquisitionTimeFromString(CPLStripQuotes(pszDate)); struct tm tmBuf; strftime (buffer, 80, MD_DATETIMEFORMAT, CPLUnixTimeToYMDHMS(timeMid, &tmBuf)); m_papszIMAGERYMD = CSLAddNameValue(m_papszIMAGERYMD, MD_NAME_ACQDATETIME, buffer); } } /** * LoadImdTxtFile */ char** GDALMDReaderEROS::LoadImdTxtFile() { char** papszLines = CSLLoad(m_osIMDSourceFilename); if(nullptr == papszLines) return nullptr; char** papszIMD = nullptr; for(int i = 0; papszLines[i] != nullptr; i++) { const char *pszLine = papszLines[i]; if( CPLStrnlen(pszLine, 21) >= 21 ) { char szName[22]; memcpy(szName, pszLine, 21); szName[21] = 0; char* pszSpace = strchr(szName, ' '); if(pszSpace) { *pszSpace = 0; papszIMD = CSLAddNameValue(papszIMD, szName, pszLine + 20); } } } CSLDestroy(papszLines); return papszIMD; } /** * GetAcqisitionTimeFromString() */ GIntBig GDALMDReaderEROS::GetAcquisitionTimeFromString( const char* pszDateTime) { if(nullptr == pszDateTime) return 0; int iYear; int iMonth; int iDay; int iHours; int iMin; int iSec; // example: sweep_start_utc 2013-04-22,11:35:02.50724 int r = sscanf ( pszDateTime, "%d-%d-%d,%d:%d:%d.%*d", &iYear, &iMonth, &iDay, &iHours, &iMin, &iSec); if (r != 6) return 0; struct tm tmDateTime; tmDateTime.tm_sec = iSec; tmDateTime.tm_min = iMin; tmDateTime.tm_hour = iHours; tmDateTime.tm_mday = iDay; tmDateTime.tm_mon = iMonth - 1; tmDateTime.tm_year = iYear - 1900; tmDateTime.tm_isdst = -1; return CPLYMDHMSToUnixTime(&tmDateTime); }
; A172486: Number of prime knots up to nine crossings with determinant 2n+1 and signature 6. ; 0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1 add $0,28 mov $1,1 mov $2,$0 gcd $2,120 bin $1,$2
dnl Intel Pentium-III mpn_popcount, mpn_hamdist -- population count and dnl hamming distance. dnl Copyright 2000, 2002, 2004 Free Software Foundation, Inc. dnl dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 2.1 of the dnl License, or (at your option) any later version. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public dnl License along with the GNU MP Library; see the file COPYING.LIB. If dnl not, write to the Free Software Foundation, Inc., 51 Franklin Street, dnl Fifth Floor, Boston, MA 02110-1301, USA. include(`../config.m4') C popcount hamdist C P3: 6.5 7 cycles/limb include_mpn(`x86/k7/mmx/popcount.asm')
; A103644: Expansion of g.f. (3x+1)/(1+2x-6x^2-27x^3). ; Submitted by Jamie Morken(s1) ; 1,1,4,25,1,256,169,1225,5476,961,64009,25600,358801,1164241,515524,15642025,3243601,101284096,239228089,216825625,3736387876,287336401,27697946329,47210598400,79524564001,872059013281,7715514244,7364086279225,8863713885601,26665408788736,198681795275209,1949137093225,1908158534760676,1559786225468641,8382005459143849,44114986873062400,4176287096391601,482651494442475121,250859379266084164,2506949959725255625,9522846706092822001,2769209586350162176,119286309976438509529,35159498629730148025 mov $1,1 mov $2,$0 lpb $2 sub $2,1 mul $3,3 sub $1,$3 add $3,$1 lpe pow $1,2 mov $0,$1