The reason you get a bus error is because you are calling ret in your build code. ret forces the program control to pass the return address at the top of the stack that you control with push and pop . I highly recommend looking at what ret does in the Intel instruction set reference.
Below is the code that I compiled and successfully ran on an iMac running Mac OS X 10.6.7.
#include <stdio.h> /*__declspec(naked)*/ void doStuff(unsigned long int val, unsigned long int flags, unsigned char *result) { __asm { push eax push ebx push ecx mov eax, dword ptr[ebp + 8] //val mov ebx, dword ptr[ebp + 12] //flags mov ecx, dword ptr[ebp + 16] //result and eax, ebx mov [ecx], eax pop ecx pop ebx pop eax } } int main(int argc, char *argv[]) { unsigned long val = 0xAA00A1F2; unsigned long flags = 0x00100002; unsigned char result = 0x0; doStuff(val, flags, &result); printf("Result is: %2Xh\n", result); return 0; }
Noticeable changes:
- Removing
ret in an inline assembly - Using
ebp instead of esp to reference doStuff options - Changing
flags to 0x00100002
Change (1) corrects the bus error, (2) made the parameter reference a bit more consistent, and (3) is just a quick way to make sure the function is working properly.
Finally, I highly recommend that you check out GNU Debugger, GDB, if you haven't already. More information about this can be found on the project page http://www.gnu.org/software/gdb/ , as well as information about the implementation and tutorial of the Mac at http://developer.apple.com/library/mac/# documentation / DeveloperTools / gdb / gdb / gdb_toc.html .
EDIT: Added basic info / link to GDB,
source share