3. Agenda
4. Mach-O structure 5. Dynamic linking details 6. Run-time hooking 7. Compiling
8. Generating assembler 9. Assembling to object file 10. Compiling
11. clang -S# Compile, but don't assemble 12. clang -c# Asseble, but don't link Object file (Mach-O format) 13. Object file
14. Object code 15. Relocation 16. Symbols 17. Debugging info 18. Symbols in object files
19. Undefined functions References to static data
20. Undefined variables 21. Linking
22. Linking
23. Executables and dynamic-linked Mach-O have no undefined symbols 24. Dynamic-linked library
25. Used to be linked against like any other object file during linking by ld, but does not become a part of executable 26. Could be loaded on executable startup or manually in code at any moment 27. Loading
28. Process memory layout Arguments & environment Stack unused memory Heap Uninitialized data Initialized data Text 29. File mapping into memory
30. Data maps copy-on-write 31. Introducing Mach-O 32. File layout 33. otool CLI exploring
34. -v (verbose) rulez $ otool -h Example.app/Contents/MacOS/Example Example.app/Contents/MacOS/Example(architecture i386): Mach header magic cputype cpusubtypecapsfiletypencmds sizeofcmds flags 0xFEEDFACE 7 3 0x00219 23560x00000085 Example.app/Contents/MacOS/Example (architecture ppc): Mach header magic cputype cpusubtypecapsfiletypencmds sizeofcmds flags 0xFEEDFACE 18 0 0x00217 24120x00000085 35. Mach-O View GUI advantages http://sourceforge.net/projects/machoview 36. Header struct mach_header { uint32_t magic; cpu_type_t cputype; cpu_subtype_t cpusubtype; uint32_t filetype; uint32_t ncmds; uint32_t sizeofcmds; uint32_t flags; }; 37. Load Commands x32 x64 38. Example - LC_SYMTAB struct load_command { uint32_t cmd; uint32_t cmdsize; //custom fields }; 39. Introducing Fat Mach-O
40. { 41. uint32_t magic;//0xCAFEBABE 42. uint32_t nfat_arch; 43. }; 44. struct fat_arch 45. { cpu_type_t cputype; 46. cpu_subtype_t cpusubtype; 47. uint32_t offset; 48. uint32_t size; 49. uint32_t align; 50. }; 51. Let's explore dynamic linking
52. void libtest();//from libtest.dylib int main() { libtest();//calls puts() from libSystem.B.dylib return 0; } 53. File libtest.c #include void libtest()//just a simple library function { puts("libtest: calls the original puts()"); } 54. Debugging external call
55. Debugging external call
56. Debugging external call
57.
58. jump to __dyld_stub_binding_helper for actual linking 59. Dynamic linker - dyld
60. Let's hook 61. Mach-O hook tool
62. mach_substitutionmach_hook ( void const * handle , char const * function_name , mach_substitutionsubstitution ); 63. voidmach_hook_free (void * handle ); Just download it and run the test project! 64. Mach-O exploring (live demo)
65. libtest: calls the original puts() 66. ----------------------------- 67. libtest: calls the original puts() 68. HOOKED! 69. ----------------------------- 70. libtest: calls the original puts() 71. Questions
Top Related