@@ -83,6 +83,9 @@ struct dasm_State {
8383/* The size of the core structure depends on the max. number of sections. */
8484#define DASM_PSZ (ms ) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section))
8585
86+ /* Perform potentially overflowing pointer operations in a way that avoids UB. */
87+ #define DASM_PTR_SUB (p1 , off ) ((void *) ((uintptr_t) (p1) - sizeof(*p1) * (uintptr_t) (off)))
88+ #define DASM_PTR_ADD (p1 , off ) ((void *) ((uintptr_t) (p1) + sizeof(*p1) * (uintptr_t) (off)))
8689
8790/* Initialize DynASM state. */
8891void dasm_init (Dst_DECL , int maxsection )
@@ -144,7 +147,7 @@ void dasm_setup(Dst_DECL, const void *actionlist)
144147 if (D -> pclabels ) memset ((void * )D -> pclabels , 0 , D -> pcsize );
145148 for (i = 0 ; i < D -> maxsection ; i ++ ) {
146149 D -> sections [i ].pos = DASM_SEC2POS (i );
147- D -> sections [i ].rbuf = D -> sections [i ].buf - D -> sections [i ].pos ;
150+ D -> sections [i ].rbuf = DASM_PTR_SUB ( D -> sections [i ].buf , D -> sections [i ].pos ) ;
148151 D -> sections [i ].ofs = 0 ;
149152 }
150153}
@@ -429,7 +432,7 @@ int dasm_encode(Dst_DECL, void *buffer)
429432 for (secnum = 0 ; secnum < D -> maxsection ; secnum ++ ) {
430433 dasm_Section * sec = D -> sections + secnum ;
431434 int * b = sec -> buf ;
432- int * endb = sec -> rbuf + sec -> pos ;
435+ int * endb = DASM_PTR_ADD ( sec -> rbuf , sec -> pos ) ;
433436
434437 while (b != endb ) {
435438 dasm_ActList p = D -> actionlist + * b ++ ;
@@ -463,15 +466,15 @@ int dasm_encode(Dst_DECL, void *buffer)
463466 cp [-1 ] |= ((n >> 2 ) & 0x03ffffff );
464467 } else if ((ins & 0x800 )) { /* B.cond, CBZ, CBNZ, LDR* literal */
465468 CK_REL ((n & 3 ) == 0 && ((n + 0x00100000 ) >> 21 ) == 0 , n );
466- cp [-1 ] |= ((n << 3 ) & 0x00ffffe0 );
469+ cp [-1 ] |= ((( unsigned ) n << 3 ) & 0x00ffffe0 );
467470 } else if ((ins & 0x3000 ) == 0x2000 ) { /* ADR */
468471 CK_REL (((n + 0x00100000 ) >> 21 ) == 0 , n );
469- cp [-1 ] |= ((n << 3 ) & 0x00ffffe0 ) | ((n & 3 ) << 29 );
472+ cp [-1 ] |= ((( unsigned ) n << 3 ) & 0x00ffffe0 ) | ((n & 3 ) << 29 );
470473 } else if ((ins & 0x3000 ) == 0x3000 ) { /* ADRP */
471474 cp [-1 ] |= ((n >> 9 ) & 0x00ffffe0 ) | (((n >> 12 ) & 3 ) << 29 );
472475 } else if ((ins & 0x1000 )) { /* TBZ, TBNZ */
473476 CK_REL ((n & 3 ) == 0 && ((n + 0x00008000 ) >> 16 ) == 0 , n );
474- cp [-1 ] |= ((n << 3 ) & 0x0007ffe0 );
477+ cp [-1 ] |= ((( unsigned ) n << 3 ) & 0x0007ffe0 );
475478 } else if ((ins & 0x8000 )) { /* absolute */
476479 cp [0 ] = (unsigned int )((ptrdiff_t )cp - 4 + n );
477480 cp [1 ] = (unsigned int )(((ptrdiff_t )cp - 4 + n ) >> 32 );
0 commit comments