0

Suppose there's a struct

struct info{
  struct stat information;
  char * filename
}

Then I set the offset of filename pointer

size_t fOffset = offsetof(struct info, filename);

now what is the fOffset?

And in the SPARC assembly, I want to get the actual string in filename. This is what I wrote so far. The parameter is a pointer of info struct

set   fOffset, %l0
ld    [%l0], %l1

add   %i0, %l1, %l2
ld  [%l2], %l2

ldub  [%l2], %o0

I thought now %o0 will store the string, but clearly it does not. Someone help me?

faker
  • 5
  • 2
  • 1
    The offset will depend on the definition of `struct stat` and implementation and/or configuration of the compiler to use. – MikeCAT Mar 05 '17 at 04:36
  • I don't think this question relates to struct stat, it's about the char pointer member in the struct info – faker Mar 05 '17 at 04:44
  • 1
    The value of `fOffset` will probably be `sizeof(struct stat)` — possibly plus some padding, but probably not. You can't determine that size in assembly; you have to know the correct size — or use C and not assembly. – Jonathan Leffler Mar 05 '17 at 04:56
  • In C/C++ the memory layout of structure/class fields is done in the same order, as they are defined, so at offset 0 of structure `info` there are usually any internal data needed by particular platform compiler (on 99% of platforms that is either nothing, or virtual functions table pointer, if some virtual function is defined). On next free reasonably padded offset will be all the `stat` data. No pointer, but it's content. And on next free reasonably padded offset will be pointer to char (So you need complete definition of `stat` structure and complete platform + compile time settings to know) – Ped7g Mar 05 '17 at 16:35

1 Answers1

0

You have done the fOffset declaration properly, so it will contain the offset of filename in the structure. I also think your assembly is correct, though I'm not sure what you mean by "%o2 will store the string". At the end of your code, %l2 is a pointer to the string, and %o2 will contain the first byte of the string. So your code looks correct to me.

Some ideas of what may be going wrong:

  • since filename is a pointer, you need to initialize it to something, probably with malloc. If you don't do this, then you'll probably get a fault on the ldub instruction since the pointer will be invalid
  • I'm guessing you are using a 32 bit userland from your code, but in case you are running a 64 bit userland, all those "ld" instructions need to be "ldx"

Also note that you can simplify the sequence:

add   %i0, %l1, %l2
ld  [%l2], %l2

To just one instruction:

ld [%i0+%l1], %l2
Rob Gardner
  • 201
  • 1
  • 4