简体   繁体   中英

asm instruction alternative in c program

I am writing a user space C program to read the hard disk.

I need to convert an assembler instruction to C program code. How can this be done?

mov eax, [rsi+0x0C]

Here eax can be any variable. However, rsi is the base address register with value 0xc1617000 . This value does not change.

You can assign values to pointers in C. Try this:

uint8_t *rsi = (uint8_t*)(uintptr_t) 0xc1617000; // The uintptr_t cast isn't really needed, but might help portability.
uint32_t value = *(uint32_t *)(rsi + 0x0C);

A shorter version, of course is:

uint32_t value = *(uint32_t *)0xc161700C;

Basically you interpret that constant as a pointer to uint32_t , and then dereference it.

Following http://www.cs.virginia.edu/~evans/cs216/guides/x86.html :

mov eax, [rsi+0x0C]

means

move the 4 Byte word at the address rsi+0x0C to the EAX register

that's what this line of assembler means; you say

Here eax can be any variable

Typically, EAX is the return value of some function, but I'll not go into this.

Since this is trivial:

int variable = *((unsigned int*) 0xc161700C; 

notice that it's totally up to your compiler whether it actually copies over that value -- in many cases, the compiler will be able to do that only when the value of variable is actually used. If asking for the address of variable , you might either be getting a new address, or actually 0xc161700C .

Since this is basic C, I'm not so confident I want to let you play with my hard drive ;) notice that for programs running in unprivileged (non-kernel mode), access to physical memory addresses is impossible in general.

EDIT

On linux the program is crashing when accessing the location. May be because its outside the bound of process memory. Any idea how to access the memory outside the bound of process memory

As I said here and in the comments: If your code is running as a program (in userland ), you can never access raw physical memory addresses. Your process sees its own memory with physical memory being mapped there in pages -- there's no possibility to access raw physical memory without the help of kernel mode. That is the beauty of memory mapping as done on any modern CPU: programs can't fiddle directly with hardware.

Under Linux, things might be relatively easy: open or mmap /dev/mem as root and access the right position in that file -- it's an emulation of direct access to memory as accessible by the operating system.

However, what you're doing is hazardous, and Linux usually already supports as much AHCI as it should -- are you sure you're already using a linux kernel of the last ten years?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM