Vincent Rodomista
Vincent Rodomista

Reputation: 780

How do I access an element of a struct in assembly?

Given the following struct

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

I am having trouble accessing the tag element of the struct in assembly. The function takes in an array of structs which are stored at 8(%ebp), and I have successfully been able to access the first byte of each struct in the array. However, I now need to access the tag byte, but cannot figure out how.

If I access the valid byte with:

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

How do I access the next part of the struct?

this is the C code. We are writing the check_cache function.

#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);
}

This is my full assembly code so far:

.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 

Upvotes: 0

Views: 1386

Answers (1)

Jester
Jester

Reputation: 58822

To answer the actual question: if (%eax, %ecx, 1) is the valid member then of course the tag is the next byte, thus 1(%eax, %ecx, 1).

Upvotes: 1

Related Questions