bytecodealliance / wasm-micro-runtime

WebAssembly Micro Runtime (WAMR)
Apache License 2.0
4.66k stars 577 forks source link

[Question] Different OP_CODE sequence when print the same variable? #3572

Open sjrrr13 opened 6 days ago

sjrrr13 commented 6 days ago

Subject of the issue

I've tried to print the OP_CODE for debugging, and I found that when print the same variable with different prefix string, the OP_CODE sequences are different. I wonder why there is such difference or what's the behavior of the extra different OP_CODE, because I think that the prefix string of printf should not impact the OP_CODE sequence.

Test case

This is my code to print OP_CODE in core/iwasm/interpreter/wasm_interp_classic.c:

static void
print_opcode(WASMOpcode op)
{
#define NAME(n)                                   \
    case (n):                                     \
        os_printf("goto *frame_ip = %s\n", #n);   \
        break;

    switch (op) {
        NAME(WASM_OP_UNREACHABLE)
        NAME(WASM_OP_NOP)
        NAME(WASM_OP_BLOCK)
        ...
        NAME(WASM_OP_ATOMIC_PREFIX)
        default:
            os_printf("unknown op 0x%x\n", op);
    }
#undef NAME
}

#define FETCH_OPCODE_AND_DISPATCH()                 \
    {                                               \
        print_opcode(*frame_ip);                    \
        goto *handle_table[*frame_ip++];            \
    }                                               \
    (void)0

And this is my code for printing a variable:

typedef struct  {
    char c;
} letters;

void
test_ptr()
{
    char *f = malloc(3 * sizeof(char));
    letters g[1];

    f[0] = 'a';
    f[1] = 'b';
    f[2] = 0;

    g[0].c = f[1];
    // [Warning!] Different OP_CODE seq between the following two lines !!!
    // printf("c = %c\n", g[0].c);
    printf("g[0].c = %c\n", g[0].c);
    free(f);
}

int
main(int argc, char *argv[])
{
    test_ptr();
    return 0;
}

And this is the script to build the test application:

/opt/wasi-sdk/bin/clang -O0 ./test_read.c \
        -z stack-size=131072 \
        -Wl,--export=__heap_base -Wl,--export=__data_end \
        -Wl,--export=malloc -Wl,--export=free \
        -o test_read.wasm \
        -Wl,--allow-undefined

Expected behavior

Whether I use printf("c = %c\n", g[0].c); or printf("g[0].c = %c\n", g[0].c); to print g[0].c, the OP_CODE sequences should be the same.

Actual behavior

I recorded the OP_CODE sequence of printf("c = %c\n", g[0].c); and printf("g[0].c = %c\n", g[0].c);, but there are many differences between the two sequences, for example:

image

There are more differences between those two sequence.

My environment

Extra Info

I use wasm2wat to convert wasm file to wat file, and converted two wasm files with different print sentences(printf("c = %c\n", g[0].c); and printf("g[0].c = %c\n", g[0].c);). Then I compared the two wat files and found no difference between them.