DynAsm x86: section handling and labels

  • From: gim <gim913@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sun, 27 Nov 2016 17:14:51 +0100

Hello,

I had a problems with generating code with many jumps.
I've managed to narrow it down to following test case, it causes
invalid memory access:
(this is based on luajit 2.0.4)

```
|.arch x64
|.section code
|.globals GLOB_
|.actionlist actions

#include "dasm_x86.h"
#include <stdio.h>

void dynasmGenerator(Dst_DECL, int nopCount)
{
    int labelsCount = 1;
    dasm_growpc(Dst, labelsCount + nopCount);
    printf("labels count: %d\n", labelsCount);

    for (int i = 0; i < nopCount; ++i) {
        | jmp => (i + 1)
        | =>(i + 1):
    }

    | xor rax, rax
    | mov rax, 0x12345678ull
    | shl rax, 32
    | or rax, 0x09abcdefull

    | ret

    printf("zomg, aot done");
}
```
(and here's some boiler plate code I'm using: http://ideone.com/pWUn7g)

it's fine, when called like:
generate(&dasmState, 4 * 1024 * 1024 + 0)
but just adding 1, yields an error:
generate(&dasmState, 4 * 1024 * 1024 + 1)

invalid access happens in inside dasm_put, in case DASM_LABEL_PC
```
while (n > 0) {
    int *pb = DASM_POS2PTR(D, n); // 1
    n = *pb;                      // 2 invalid access
    *pb = pos;                    // 3
}
```

DASM_POS2PTR(D, n) expands to (D->sections[DASM_POS2SEC(pos)].rbuf + pos).

at the beginning of dasm_put, section is expanded, but only rbuf of "current"
section is altered:

  if (pos >= sec->epos) {
    DASM_M_GROW(Dst, int, ...
    sec->rbuf = sec->buf - DASM_POS2BIAS(pos);


result of DASM_POS2SEC(pos) in this case is 1, and value of rbuf for section[1]
is the one that is set in dasm_init:
for (i = 0; i < maxsection; i++) {
    D->sections[i].buf = NULL;  /* Need this for pass3. */
    D->sections[i].rbuf = D->sections[i].buf - DASM_SEC2POS(i);


Now, I'm not sure how section handling should work, so I don't know how fix
should look like

-- 
 main (int a, char *b[puts("Michal 'GiM' Spadlinski")]) {}

Other related posts:

  • » DynAsm x86: section handling and labels - gim