如何在程序集中访问结构的元素?

时间:2015-11-20 22:26:28

标签: c arrays assembly struct

给出以下结构

typedef struct {
char valid;
char tag;
char block[4];
} line;

我无法在程序集中访问struct的tag元素。该函数接受一个存储在8(%ebp)的结构数组,并且我已经成功地访问了数组中每个结构的第一个字节。但是,我现在需要访问tag字节,但无法弄清楚如何。

如果我使用:

访问valid字节

movl (%eax, %ecx, 1), %eax # ecx = offset,eax = position of array

如何访问结构的下一部分?

这是C代码。我们正在编写check_cache函数。

#include <stdio.h>
#include <assert.h>

typedef struct {
    char valid;
    char tag;
    char block[4];
} line;

unsigned char check_cache(line cache[4], unsigned char addr);

int main() {
    line cache[4];

    cache[0].valid = 0x1;
    cache[0].tag = 0x0;
    cache[0].block[0] = 0xA;
    cache[0].block[1] = 0xB;
    cache[0].block[2] = 0xC;
    cache[0].block[3] = 0xD;

    cache[1].valid = 0x0;
        cache[1].tag = 0x7;

    cache[2].valid = 0x0;
        cache[2].tag = 0xA;

    cache[3].valid = 0x1;
        cache[3].tag = 0x3;
        cache[3].block[0] = 0x2A;
        cache[3].block[1] = 0x2B;
        cache[3].block[2] = 0x2C;
        cache[3].block[3] = 0x2D;

    unsigned char res;
    int input;
    unsigned char uc;
    do 
    {
        printf("Enter a memory address (0-255) for cache access: ");
        assert(scanf("%d", &input) == 1);
        uc = (unsigned char)input;
        res = check_cache(cache, uc);
        if(res == 0xFF)
            printf("cache MISS for address 0x%x\n", uc);
        else
            printf("cache HIT for 0x%x: 0x%x\n", uc, res);
    } while(uc);
    return(0);
}

到目前为止,这是我的完整汇编代码:

.global check_cache

check_cache:
    pushl   %ebp
        movl    %esp,   %ebp

    movl    12(%ebp), %eax  
    movl    $0x3,     %ebx
    andl    %eax,     %ebx
    shrl    $0x2,     %eax
    movl    $0x3,     %ecx
    andl    %eax,     %ecx
    shrl    $0x2,     %eax
    movl    $0xF,     %edx
    andl    %eax,     %edx

    movl    8(%ebp),  %eax
    imull   $6,   %ecx
    movl    (%eax, %ecx, 1), %eax
    cmpl    $0x0,   %eax
    movl    $0, %esi    
    jle .L4 



    movl    (%eax),   %eax
    movl    4(%eax),  %eax  

    je  .L4

    popl    %ebp
    ret

.L4:    
    movl    $0xFF,    %eax
    popl    %ebp
    ret 

1 个答案:

答案 0 :(得分:1)

要回答实际问题:如果(%eax, %ecx, 1)valid成员,那么tag当然是下一个字节,因此1(%eax, %ecx, 1)