kernel32/tests: Add a test to check some fields in fake dlls.
[wine.git] / dlls / dbghelp / macho_module.c
bloba0623352a7346442bfcce3ae5d4979756981fd15
1 /*
2 * File macho_module.c - processing of Mach-O files
3 * Originally based on elf_module.c
5 * Copyright (C) 1996, Eric Youngdale.
6 * 1999-2007 Eric Pouech
7 * 2009 Ken Thomases, CodeWeavers Inc.
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "config.h"
25 #include "wine/port.h"
27 #ifdef HAVE_MACH_O_LOADER_H
28 #include <CoreFoundation/CFString.h>
29 #define LoadResource mac_LoadResource
30 #define GetCurrentThread mac_GetCurrentThread
31 #include <CoreServices/CoreServices.h>
32 #undef LoadResource
33 #undef GetCurrentThread
34 #undef DPRINTF
35 #endif
37 #include <stdio.h>
38 #include <assert.h>
39 #include <stdarg.h>
40 #include <errno.h>
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #ifdef HAVE_SYS_MMAN_H
45 # include <sys/mman.h>
46 #endif
48 #include "ntstatus.h"
49 #define WIN32_NO_STATUS
50 #include "dbghelp_private.h"
51 #include "winternl.h"
52 #include "wine/library.h"
53 #include "wine/debug.h"
54 #include "wine/heap.h"
55 #include "image_private.h"
57 #ifdef HAVE_MACH_O_LOADER_H
59 #include <mach-o/fat.h>
60 #include <mach-o/loader.h>
61 #include <mach-o/nlist.h>
62 #include <mach-o/dyld.h>
64 #ifdef HAVE_MACH_O_DYLD_IMAGES_H
65 #include <mach-o/dyld_images.h>
66 #else
67 struct dyld_image_info {
68 const struct mach_header *imageLoadAddress;
69 const char *imageFilePath;
70 uintptr_t imageFileModDate;
73 struct dyld_all_image_infos {
74 uint32_t version;
75 uint32_t infoArrayCount;
76 const struct dyld_image_info *infoArray;
77 void* notification;
78 int processDetachedFromSharedRegion;
80 #endif
82 #ifdef WORDS_BIGENDIAN
83 #define swap_ulong_be_to_host(n) (n)
84 #else
85 #define swap_ulong_be_to_host(n) (RtlUlongByteSwap(n))
86 #endif
88 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp_macho);
91 /* Bitmask for Mach-O image header flags indicating that the image is in dyld's
92 shared cached. That implies that its segments are mapped non-contiguously.
93 This value isn't defined anywhere in headers. It's used in dyld and in
94 debuggers which support OS X as a magic number.
96 The flag also isn't set in the on-disk image file. It's only set in
97 memory by dyld. */
98 #define MACHO_DYLD_IN_SHARED_CACHE 0x80000000
101 #define UUID_STRING_LEN 37 /* 16 bytes at 2 hex digits apiece, 4 dashes, and the null terminator */
104 struct macho_module_info
106 struct image_file_map file_map;
107 unsigned long load_addr;
108 unsigned short in_use : 1,
109 is_loader : 1;
112 struct section_info
114 BOOL split_segs;
115 unsigned int section_index;
118 #define MACHO_INFO_DEBUG_HEADER 0x0001
119 #define MACHO_INFO_MODULE 0x0002
120 #define MACHO_INFO_NAME 0x0004
122 struct macho_info
124 unsigned flags; /* IN one (or several) of the MACHO_INFO constants */
125 unsigned long dbg_hdr_addr; /* OUT address of debug header (if MACHO_INFO_DEBUG_HEADER is set) */
126 struct module* module; /* OUT loaded module (if MACHO_INFO_MODULE is set) */
127 const WCHAR* module_name; /* OUT found module name (if MACHO_INFO_NAME is set) */
130 static void macho_unmap_file(struct image_file_map* fmap);
132 static char* format_uuid(const uint8_t uuid[16], char out[UUID_STRING_LEN])
134 sprintf(out, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
135 uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
136 uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
137 return out;
140 /******************************************************************
141 * macho_calc_range
143 * For a range (offset & length) of a single architecture within
144 * a Mach-O file, calculate the page-aligned range of the whole file
145 * that encompasses it. For a fat binary, the architecture will
146 * itself be offset within the file, so take that into account.
148 static void macho_calc_range(const struct macho_file_map* fmap, unsigned long offset,
149 unsigned long len, unsigned long* out_aligned_offset,
150 unsigned long* out_aligned_end, unsigned long* out_aligned_len,
151 unsigned long* out_misalign)
153 unsigned long pagemask = sysconf( _SC_PAGESIZE ) - 1;
154 unsigned long file_offset, misalign;
156 file_offset = fmap->arch_offset + offset;
157 misalign = file_offset & pagemask;
158 *out_aligned_offset = file_offset - misalign;
159 *out_aligned_end = (file_offset + len + pagemask) & ~pagemask;
160 if (out_aligned_len)
161 *out_aligned_len = *out_aligned_end - *out_aligned_offset;
162 if (out_misalign)
163 *out_misalign = misalign;
166 /******************************************************************
167 * macho_map_range
169 * Maps a range (offset, length in bytes) from a Mach-O file into memory
171 static const char* macho_map_range(const struct macho_file_map* fmap, unsigned long offset, unsigned long len,
172 const char** base)
174 unsigned long misalign, aligned_offset, aligned_map_end, map_size;
175 const void* aligned_ptr;
177 TRACE("(%p/%d, 0x%08lx, 0x%08lx)\n", fmap, fmap->fd, offset, len);
179 macho_calc_range(fmap, offset, len, &aligned_offset, &aligned_map_end,
180 &map_size, &misalign);
182 aligned_ptr = mmap(NULL, map_size, PROT_READ, MAP_PRIVATE, fmap->fd, aligned_offset);
184 TRACE("Mapped (0x%08lx - 0x%08lx) to %p\n", aligned_offset, aligned_map_end, aligned_ptr);
186 if (aligned_ptr == MAP_FAILED) return IMAGE_NO_MAP;
187 if (base)
188 *base = aligned_ptr;
189 return (const char*)aligned_ptr + misalign;
192 /******************************************************************
193 * macho_unmap_range
195 * Unmaps a range (offset, length in bytes) of a Mach-O file from memory
197 static void macho_unmap_range(const char** base, const void** mapped, const struct macho_file_map* fmap,
198 unsigned long offset, unsigned long len)
200 TRACE("(%p, %p, %p/%d, 0x%08lx, 0x%08lx)\n", base, mapped, fmap, fmap->fd, offset, len);
202 if ((mapped && *mapped != IMAGE_NO_MAP) || (base && *base != IMAGE_NO_MAP))
204 unsigned long misalign, aligned_offset, aligned_map_end, map_size;
205 void* aligned_ptr;
207 macho_calc_range(fmap, offset, len, &aligned_offset, &aligned_map_end,
208 &map_size, &misalign);
210 if (mapped)
211 aligned_ptr = (char*)*mapped - misalign;
212 else
213 aligned_ptr = (void*)*base;
214 if (munmap(aligned_ptr, map_size) < 0)
215 WARN("Couldn't unmap the range\n");
216 TRACE("Unmapped (0x%08lx - 0x%08lx) from %p - %p\n", aligned_offset, aligned_map_end, aligned_ptr, (char*)aligned_ptr + map_size);
217 if (mapped)
218 *mapped = IMAGE_NO_MAP;
219 if (base)
220 *base = IMAGE_NO_MAP;
224 /******************************************************************
225 * macho_map_ranges
227 * Maps two ranges (offset, length in bytes) from a Mach-O file
228 * into memory. If the two ranges overlap, use one mmap so that
229 * the munmap doesn't fragment the mapping.
231 static BOOL macho_map_ranges(const struct macho_file_map* fmap,
232 unsigned long offset1, unsigned long len1,
233 unsigned long offset2, unsigned long len2,
234 const void** mapped1, const void** mapped2)
236 unsigned long aligned_offset1, aligned_map_end1;
237 unsigned long aligned_offset2, aligned_map_end2;
239 TRACE("(%p/%d, 0x%08lx, 0x%08lx, 0x%08lx, 0x%08lx, %p, %p)\n", fmap, fmap->fd,
240 offset1, len1, offset2, len2, mapped1, mapped2);
242 macho_calc_range(fmap, offset1, len1, &aligned_offset1, &aligned_map_end1, NULL, NULL);
243 macho_calc_range(fmap, offset2, len2, &aligned_offset2, &aligned_map_end2, NULL, NULL);
245 if (aligned_map_end1 < aligned_offset2 || aligned_map_end2 < aligned_offset1)
247 *mapped1 = macho_map_range(fmap, offset1, len1, NULL);
248 if (*mapped1 != IMAGE_NO_MAP)
250 *mapped2 = macho_map_range(fmap, offset2, len2, NULL);
251 if (*mapped2 == IMAGE_NO_MAP)
252 macho_unmap_range(NULL, mapped1, fmap, offset1, len1);
255 else
257 if (offset1 < offset2)
259 *mapped1 = macho_map_range(fmap, offset1, offset2 + len2 - offset1, NULL);
260 if (*mapped1 != IMAGE_NO_MAP)
261 *mapped2 = (const char*)*mapped1 + offset2 - offset1;
263 else
265 *mapped2 = macho_map_range(fmap, offset2, offset1 + len1 - offset2, NULL);
266 if (*mapped2 != IMAGE_NO_MAP)
267 *mapped1 = (const char*)*mapped2 + offset1 - offset2;
271 TRACE(" => %p, %p\n", *mapped1, *mapped2);
273 return (*mapped1 != IMAGE_NO_MAP) && (*mapped2 != IMAGE_NO_MAP);
276 /******************************************************************
277 * macho_unmap_ranges
279 * Unmaps two ranges (offset, length in bytes) of a Mach-O file
280 * from memory. Use for ranges which were mapped by
281 * macho_map_ranges.
283 static void macho_unmap_ranges(const struct macho_file_map* fmap,
284 unsigned long offset1, unsigned long len1,
285 unsigned long offset2, unsigned long len2,
286 const void** mapped1, const void** mapped2)
288 unsigned long aligned_offset1, aligned_map_end1;
289 unsigned long aligned_offset2, aligned_map_end2;
291 TRACE("(%p/%d, 0x%08lx, 0x%08lx, 0x%08lx, 0x%08lx, %p/%p, %p/%p)\n", fmap, fmap->fd,
292 offset1, len1, offset2, len2, mapped1, *mapped1, mapped2, *mapped2);
294 macho_calc_range(fmap, offset1, len1, &aligned_offset1, &aligned_map_end1, NULL, NULL);
295 macho_calc_range(fmap, offset2, len2, &aligned_offset2, &aligned_map_end2, NULL, NULL);
297 if (aligned_map_end1 < aligned_offset2 || aligned_map_end2 < aligned_offset1)
299 macho_unmap_range(NULL, mapped1, fmap, offset1, len1);
300 macho_unmap_range(NULL, mapped2, fmap, offset2, len2);
302 else
304 if (offset1 < offset2)
306 macho_unmap_range(NULL, mapped1, fmap, offset1, offset2 + len2 - offset1);
307 *mapped2 = IMAGE_NO_MAP;
309 else
311 macho_unmap_range(NULL, mapped2, fmap, offset2, offset1 + len1 - offset2);
312 *mapped1 = IMAGE_NO_MAP;
317 /******************************************************************
318 * macho_find_section
320 BOOL macho_find_section(struct image_file_map* ifm, const char* segname, const char* sectname, struct image_section_map* ism)
322 struct macho_file_map* fmap;
323 unsigned i;
324 char tmp[sizeof(fmap->sect[0].section.sectname)];
326 /* Other parts of dbghelp use section names like ".eh_frame". Mach-O uses
327 names like "__eh_frame". Convert those. */
328 if (sectname[0] == '.')
330 lstrcpynA(tmp, "__", sizeof(tmp));
331 lstrcpynA(tmp + 2, sectname + 1, sizeof(tmp) - 2);
332 sectname = tmp;
335 while (ifm)
337 fmap = &ifm->u.macho;
338 for (i = 0; i < fmap->num_sections; i++)
340 if (!fmap->sect[i].ignored &&
341 strcmp(fmap->sect[i].section.sectname, sectname) == 0 &&
342 (!segname || strcmp(fmap->sect[i].section.segname, segname) == 0))
344 ism->fmap = ifm;
345 ism->sidx = i;
346 return TRUE;
349 ifm = fmap->dsym;
352 ism->fmap = NULL;
353 ism->sidx = -1;
354 return FALSE;
357 /******************************************************************
358 * macho_map_section
360 const char* macho_map_section(struct image_section_map* ism)
362 struct macho_file_map* fmap = &ism->fmap->u.macho;
364 assert(ism->fmap->modtype == DMT_MACHO);
365 if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.macho.num_sections || fmap->sect[ism->sidx].ignored)
366 return IMAGE_NO_MAP;
368 return macho_map_range(fmap, fmap->sect[ism->sidx].section.offset, fmap->sect[ism->sidx].section.size,
369 &fmap->sect[ism->sidx].mapped);
372 /******************************************************************
373 * macho_unmap_section
375 void macho_unmap_section(struct image_section_map* ism)
377 struct macho_file_map* fmap = &ism->fmap->u.macho;
379 if (ism->sidx >= 0 && ism->sidx < fmap->num_sections && fmap->sect[ism->sidx].mapped != IMAGE_NO_MAP)
381 macho_unmap_range(&fmap->sect[ism->sidx].mapped, NULL, fmap, fmap->sect[ism->sidx].section.offset,
382 fmap->sect[ism->sidx].section.size);
386 /******************************************************************
387 * macho_get_map_rva
389 DWORD_PTR macho_get_map_rva(const struct image_section_map* ism)
391 if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.macho.num_sections ||
392 ism->fmap->u.macho.sect[ism->sidx].ignored)
393 return 0;
394 return ism->fmap->u.macho.sect[ism->sidx].section.addr - ism->fmap->u.macho.segs_start;
397 /******************************************************************
398 * macho_get_map_size
400 unsigned macho_get_map_size(const struct image_section_map* ism)
402 if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.macho.num_sections ||
403 ism->fmap->u.macho.sect[ism->sidx].ignored)
404 return 0;
405 return ism->fmap->u.macho.sect[ism->sidx].section.size;
408 /******************************************************************
409 * macho_map_load_commands
411 * Maps the load commands from a Mach-O file into memory
413 static const struct load_command* macho_map_load_commands(struct macho_file_map* fmap)
415 if (fmap->load_commands == IMAGE_NO_MAP)
417 fmap->load_commands = (const struct load_command*) macho_map_range(
418 fmap, fmap->header_size, fmap->mach_header.sizeofcmds, NULL);
419 TRACE("Mapped load commands: %p\n", fmap->load_commands);
422 return fmap->load_commands;
425 /******************************************************************
426 * macho_unmap_load_commands
428 * Unmaps the load commands of a Mach-O file from memory
430 static void macho_unmap_load_commands(struct macho_file_map* fmap)
432 if (fmap->load_commands != IMAGE_NO_MAP)
434 TRACE("Unmapping load commands: %p\n", fmap->load_commands);
435 macho_unmap_range(NULL, (const void**)&fmap->load_commands, fmap,
436 fmap->header_size, fmap->mach_header.sizeofcmds);
440 /******************************************************************
441 * macho_next_load_command
443 * Advance to the next load command
445 static const struct load_command* macho_next_load_command(const struct load_command* lc)
447 return (const struct load_command*)((const char*)lc + lc->cmdsize);
450 /******************************************************************
451 * macho_enum_load_commands
453 * Enumerates the load commands for a Mach-O file, selecting by
454 * the command type, calling a callback for each. If the callback
455 * returns <0, that indicates an error. If it returns >0, that means
456 * it's not interested in getting any more load commands.
457 * If this function returns <0, that's an error produced by the
458 * callback. If >=0, that's the count of load commands successfully
459 * processed.
461 static int macho_enum_load_commands(struct image_file_map *ifm, unsigned cmd,
462 int (*cb)(struct image_file_map*, const struct load_command*, void*),
463 void* user)
465 struct macho_file_map* fmap = &ifm->u.macho;
466 const struct load_command* lc;
467 int i;
468 int count = 0;
470 TRACE("(%p/%d, %u, %p, %p)\n", fmap, fmap->fd, cmd, cb, user);
472 if ((lc = macho_map_load_commands(fmap)) == IMAGE_NO_MAP) return -1;
474 TRACE("%d total commands\n", fmap->mach_header.ncmds);
476 for (i = 0; i < fmap->mach_header.ncmds; i++, lc = macho_next_load_command(lc))
478 int result;
480 if (cmd && cmd != lc->cmd) continue;
481 count++;
483 result = cb(ifm, lc, user);
484 TRACE("load_command[%d] (%p), cmd %u; callback => %d\n", i, lc, lc->cmd, result);
485 if (result) return (result < 0) ? result : count;
488 return count;
491 /******************************************************************
492 * macho_count_sections
494 * Callback for macho_enum_load_commands. Counts the number of
495 * significant sections in a Mach-O file. All commands are
496 * expected to be of LC_SEGMENT[_64] type.
498 static int macho_count_sections(struct image_file_map* ifm, const struct load_command* lc, void* user)
500 char segname[16];
501 uint32_t nsects;
503 if (ifm->addr_size == 32)
505 const struct segment_command *sc = (const struct segment_command *)lc;
506 memcpy(segname, sc->segname, sizeof(segname));
507 nsects = sc->nsects;
509 else
511 const struct segment_command_64 *sc = (const struct segment_command_64 *)lc;
512 memcpy(segname, sc->segname, sizeof(segname));
513 nsects = sc->nsects;
516 TRACE("(%p/%d, %p, %p) segment %s\n", ifm, ifm->u.macho.fd, lc, user,
517 debugstr_an(segname, sizeof(segname)));
519 ifm->u.macho.num_sections += nsects;
520 return 0;
523 /******************************************************************
524 * macho_load_section_info
526 * Callback for macho_enum_load_commands. Accumulates the address
527 * range covered by the segments of a Mach-O file and builds the
528 * section map. All commands are expected to be of LC_SEGMENT[_64] type.
530 static int macho_load_section_info(struct image_file_map* ifm, const struct load_command* lc, void* user)
532 struct macho_file_map* fmap = &ifm->u.macho;
533 struct section_info* info = user;
534 BOOL ignore;
535 int i;
536 unsigned long tmp, page_mask = sysconf( _SC_PAGESIZE ) - 1;
537 uint64_t vmaddr, vmsize;
538 char segname[16];
539 uint32_t nsects;
540 const void *sections;
542 if (ifm->addr_size == 32)
544 const struct segment_command *sc = (const struct segment_command *)lc;
545 vmaddr = sc->vmaddr;
546 vmsize = sc->vmsize;
547 memcpy(segname, sc->segname, sizeof(segname));
548 nsects = sc->nsects;
549 sections = (const void *)(sc + 1);
551 else
553 const struct segment_command_64 *sc = (const struct segment_command_64 *)lc;
554 vmaddr = sc->vmaddr;
555 vmsize = sc->vmsize;
556 memcpy(segname, sc->segname, sizeof(segname));
557 nsects = sc->nsects;
558 sections = (const void *)(sc + 1);
561 TRACE("(%p/%d, %p, %p) before: 0x%08lx - 0x%08lx\n", fmap, fmap->fd, lc, user,
562 (unsigned long)fmap->segs_start, (unsigned long)fmap->segs_size);
563 TRACE("Segment command vm: 0x%08lx - 0x%08lx\n", (unsigned long)vmaddr,
564 (unsigned long)(vmaddr + vmsize));
566 /* Images in the dyld shared cache have their segments mapped non-contiguously.
567 We don't know how to properly locate any of the segments other than __TEXT,
568 so ignore them. */
569 ignore = (info->split_segs && strcmp(segname, SEG_TEXT));
571 if (!strncmp(segname, "WINE_", 5))
572 TRACE("Ignoring special Wine segment %s\n", debugstr_an(segname, sizeof(segname)));
573 else if (!strncmp(segname, "__PAGEZERO", 10))
574 TRACE("Ignoring __PAGEZERO segment\n");
575 else if (ignore)
576 TRACE("Ignoring %s segment because image has split segments\n", segname);
577 else
579 /* If this segment starts before previously-known earliest, record new earliest. */
580 if (vmaddr < fmap->segs_start)
581 fmap->segs_start = vmaddr;
583 /* If this segment extends beyond previously-known furthest, record new furthest. */
584 tmp = (vmaddr + vmsize + page_mask) & ~page_mask;
585 if (fmap->segs_size < tmp) fmap->segs_size = tmp;
587 TRACE("after: 0x%08lx - 0x%08lx\n", (unsigned long)fmap->segs_start, (unsigned long)fmap->segs_size);
590 for (i = 0; i < nsects; i++)
592 if (ifm->addr_size == 32)
594 const struct section *section = &((const struct section *)sections)[i];
595 memcpy(fmap->sect[info->section_index].section.sectname, section->sectname, sizeof(section->sectname));
596 memcpy(fmap->sect[info->section_index].section.segname, section->segname, sizeof(section->segname));
597 fmap->sect[info->section_index].section.addr = section->addr;
598 fmap->sect[info->section_index].section.size = section->size;
599 fmap->sect[info->section_index].section.offset = section->offset;
600 fmap->sect[info->section_index].section.align = section->align;
601 fmap->sect[info->section_index].section.reloff = section->reloff;
602 fmap->sect[info->section_index].section.nreloc = section->nreloc;
603 fmap->sect[info->section_index].section.flags = section->flags;
605 else
606 fmap->sect[info->section_index].section = ((const struct section_64 *)sections)[i];
608 fmap->sect[info->section_index].mapped = IMAGE_NO_MAP;
609 fmap->sect[info->section_index].ignored = ignore;
610 info->section_index++;
613 return 0;
616 /******************************************************************
617 * find_uuid
619 * Callback for macho_enum_load_commands. Records the UUID load
620 * command of a Mach-O file.
622 static int find_uuid(struct image_file_map* ifm, const struct load_command* lc, void* user)
624 ifm->u.macho.uuid = (const struct uuid_command*)lc;
625 return 1;
628 /******************************************************************
629 * reset_file_map
631 static inline void reset_file_map(struct image_file_map* ifm)
633 struct macho_file_map* fmap = &ifm->u.macho;
635 fmap->fd = -1;
636 fmap->dsym = NULL;
637 fmap->load_commands = IMAGE_NO_MAP;
638 fmap->uuid = NULL;
639 fmap->num_sections = 0;
640 fmap->sect = NULL;
643 /******************************************************************
644 * macho_map_file
646 * Maps a Mach-O file into memory (and checks it's a real Mach-O file)
648 static BOOL macho_map_file(struct process *pcs, const WCHAR *filenameW,
649 BOOL split_segs, struct image_file_map* ifm)
651 struct macho_file_map* fmap = &ifm->u.macho;
652 struct fat_header fat_header;
653 struct stat statbuf;
654 int i;
655 char* filename;
656 unsigned len;
657 struct section_info info;
658 BOOL ret = FALSE;
659 cpu_type_t target_cpu = (pcs->is_64bit) ? CPU_TYPE_X86_64 : CPU_TYPE_X86;
660 uint32_t target_magic = (pcs->is_64bit) ? MH_MAGIC_64 : MH_MAGIC;
661 uint32_t target_cmd = (pcs->is_64bit) ? LC_SEGMENT_64 : LC_SEGMENT;
663 TRACE("(%s, %p)\n", debugstr_w(filenameW), fmap);
665 reset_file_map(ifm);
667 ifm->modtype = DMT_MACHO;
668 ifm->addr_size = (pcs->is_64bit) ? 64 : 32;
669 fmap->header_size = (pcs->is_64bit) ? sizeof(struct mach_header_64) : sizeof(struct mach_header);
671 len = WideCharToMultiByte(CP_UNIXCP, 0, filenameW, -1, NULL, 0, NULL, NULL);
672 if (!(filename = HeapAlloc(GetProcessHeap(), 0, len)))
674 WARN("failed to allocate filename buffer\n");
675 return FALSE;
677 WideCharToMultiByte(CP_UNIXCP, 0, filenameW, -1, filename, len, NULL, NULL);
679 /* check that the file exists */
680 if (stat(filename, &statbuf) == -1 || S_ISDIR(statbuf.st_mode))
682 TRACE("stat() failed or %s is directory: %s\n", debugstr_a(filename), strerror(errno));
683 goto done;
686 /* Now open the file, so that we can mmap() it. */
687 if ((fmap->fd = open(filename, O_RDONLY)) == -1)
689 TRACE("failed to open file %s: %d\n", debugstr_a(filename), errno);
690 goto done;
693 if (read(fmap->fd, &fat_header, sizeof(fat_header)) != sizeof(fat_header))
695 TRACE("failed to read fat header: %d\n", errno);
696 goto done;
698 TRACE("... got possible fat header\n");
700 /* Fat header is always in big-endian order. */
701 if (swap_ulong_be_to_host(fat_header.magic) == FAT_MAGIC)
703 int narch = swap_ulong_be_to_host(fat_header.nfat_arch);
704 for (i = 0; i < narch; i++)
706 struct fat_arch fat_arch;
707 if (read(fmap->fd, &fat_arch, sizeof(fat_arch)) != sizeof(fat_arch))
708 goto done;
709 if (swap_ulong_be_to_host(fat_arch.cputype) == target_cpu)
711 fmap->arch_offset = swap_ulong_be_to_host(fat_arch.offset);
712 break;
715 if (i >= narch) goto done;
716 TRACE("... found target arch (%d)\n", target_cpu);
718 else
720 fmap->arch_offset = 0;
721 TRACE("... not a fat header\n");
724 /* Individual architecture (standalone or within a fat file) is in its native byte order. */
725 lseek(fmap->fd, fmap->arch_offset, SEEK_SET);
726 if (read(fmap->fd, &fmap->mach_header, sizeof(fmap->mach_header)) != sizeof(fmap->mach_header))
727 goto done;
728 TRACE("... got possible Mach header\n");
729 /* and check for a Mach-O header */
730 if (fmap->mach_header.magic != target_magic ||
731 fmap->mach_header.cputype != target_cpu) goto done;
732 /* Make sure the file type is one of the ones we expect. */
733 switch (fmap->mach_header.filetype)
735 case MH_EXECUTE:
736 case MH_DYLIB:
737 case MH_DYLINKER:
738 case MH_BUNDLE:
739 case MH_DSYM:
740 break;
741 default:
742 goto done;
744 TRACE("... verified Mach header\n");
746 fmap->num_sections = 0;
747 if (macho_enum_load_commands(ifm, target_cmd, macho_count_sections, NULL) < 0)
748 goto done;
749 TRACE("%d sections\n", fmap->num_sections);
751 fmap->sect = HeapAlloc(GetProcessHeap(), 0, fmap->num_sections * sizeof(fmap->sect[0]));
752 if (!fmap->sect)
753 goto done;
755 fmap->segs_size = 0;
756 fmap->segs_start = ~0L;
758 info.split_segs = split_segs;
759 info.section_index = 0;
760 if (macho_enum_load_commands(ifm, target_cmd, macho_load_section_info, &info) < 0)
762 fmap->num_sections = 0;
763 goto done;
766 fmap->segs_size -= fmap->segs_start;
767 TRACE("segs_start: 0x%08lx, segs_size: 0x%08lx\n", (unsigned long)fmap->segs_start,
768 (unsigned long)fmap->segs_size);
770 if (macho_enum_load_commands(ifm, LC_UUID, find_uuid, NULL) < 0)
771 goto done;
772 if (fmap->uuid)
774 char uuid_string[UUID_STRING_LEN];
775 TRACE("UUID %s\n", format_uuid(fmap->uuid->uuid, uuid_string));
777 else
778 TRACE("no UUID found\n");
780 ret = TRUE;
781 done:
782 if (!ret)
783 macho_unmap_file(ifm);
784 HeapFree(GetProcessHeap(), 0, filename);
785 return ret;
788 /******************************************************************
789 * macho_unmap_file
791 * Unmaps a Mach-O file from memory (previously mapped with macho_map_file)
793 static void macho_unmap_file(struct image_file_map* ifm)
795 struct image_file_map* cursor;
797 TRACE("(%p/%d)\n", ifm, ifm->u.macho.fd);
799 cursor = ifm;
800 while (cursor)
802 struct image_file_map* next;
804 if (ifm->u.macho.fd != -1)
806 struct image_section_map ism;
808 ism.fmap = ifm;
809 for (ism.sidx = 0; ism.sidx < ifm->u.macho.num_sections; ism.sidx++)
810 macho_unmap_section(&ism);
812 HeapFree(GetProcessHeap(), 0, ifm->u.macho.sect);
813 macho_unmap_load_commands(&ifm->u.macho);
814 close(ifm->u.macho.fd);
815 ifm->u.macho.fd = -1;
818 next = cursor->u.macho.dsym;
819 if (cursor != ifm)
820 HeapFree(GetProcessHeap(), 0, cursor);
821 cursor = next;
825 /******************************************************************
826 * macho_sect_is_code
828 * Checks if a section, identified by sectidx which is a 1-based
829 * index into the sections of all segments, in order of load
830 * commands, contains code.
832 static BOOL macho_sect_is_code(struct macho_file_map* fmap, unsigned char sectidx)
834 BOOL ret;
836 TRACE("(%p/%d, %u)\n", fmap, fmap->fd, sectidx);
838 if (!sectidx) return FALSE;
840 sectidx--; /* convert from 1-based to 0-based */
841 if (sectidx >= fmap->num_sections || fmap->sect[sectidx].ignored) return FALSE;
843 ret = (!(fmap->sect[sectidx].section.flags & SECTION_TYPE) &&
844 (fmap->sect[sectidx].section.flags & (S_ATTR_PURE_INSTRUCTIONS|S_ATTR_SOME_INSTRUCTIONS)));
845 TRACE("-> %d\n", ret);
846 return ret;
849 struct symtab_elt
851 struct hash_table_elt ht_elt;
852 struct symt_compiland* compiland;
853 unsigned long addr;
854 unsigned char is_code:1,
855 is_public:1,
856 is_global:1,
857 used:1;
860 struct macho_debug_info
862 struct macho_file_map* fmap;
863 struct module* module;
864 struct pool pool;
865 struct hash_table ht_symtab;
868 /******************************************************************
869 * macho_stabs_def_cb
871 * Callback for stabs_parse. Collect symbol definitions.
873 static void macho_stabs_def_cb(struct module* module, unsigned long load_offset,
874 const char* name, unsigned long offset,
875 BOOL is_public, BOOL is_global, unsigned char sectidx,
876 struct symt_compiland* compiland, void* user)
878 struct macho_debug_info* mdi = user;
879 struct symtab_elt* ste;
881 TRACE("(%p, 0x%08lx, %s, 0x%08lx, %d, %d, %u, %p, %p/%p/%d)\n", module, load_offset,
882 debugstr_a(name), offset, is_public, is_global, sectidx,
883 compiland, mdi, mdi->fmap, mdi->fmap->fd);
885 /* Defer the creation of new non-debugging symbols until after we've
886 * finished parsing the stabs. */
887 ste = pool_alloc(&mdi->pool, sizeof(*ste));
888 ste->ht_elt.name = pool_strdup(&mdi->pool, name);
889 ste->compiland = compiland;
890 ste->addr = load_offset + offset;
891 ste->is_code = !!macho_sect_is_code(mdi->fmap, sectidx);
892 ste->is_public = !!is_public;
893 ste->is_global = !!is_global;
894 ste->used = 0;
895 hash_table_add(&mdi->ht_symtab, &ste->ht_elt);
898 /******************************************************************
899 * macho_parse_symtab
901 * Callback for macho_enum_load_commands. Processes the LC_SYMTAB
902 * load commands from the Mach-O file.
904 static int macho_parse_symtab(struct image_file_map* ifm,
905 const struct load_command* lc, void* user)
907 struct macho_file_map* fmap = &ifm->u.macho;
908 const struct symtab_command* sc = (const struct symtab_command*)lc;
909 struct macho_debug_info* mdi = user;
910 const char* stabstr;
911 int ret = 0;
912 size_t stabsize = (ifm->addr_size == 32) ? sizeof(struct nlist) : sizeof(struct nlist_64);
913 const char *stab;
915 TRACE("(%p/%d, %p, %p) %u syms at 0x%08x, strings 0x%08x - 0x%08x\n", fmap, fmap->fd, lc,
916 user, sc->nsyms, sc->symoff, sc->stroff, sc->stroff + sc->strsize);
918 if (!macho_map_ranges(fmap, sc->symoff, sc->nsyms * stabsize,
919 sc->stroff, sc->strsize, (const void**)&stab, (const void**)&stabstr))
920 return 0;
922 if (!stabs_parse(mdi->module,
923 mdi->module->format_info[DFI_MACHO]->u.macho_info->load_addr - fmap->segs_start,
924 stab, sc->nsyms * stabsize,
925 stabstr, sc->strsize, macho_stabs_def_cb, mdi))
926 ret = -1;
928 macho_unmap_ranges(fmap, sc->symoff, sc->nsyms * stabsize,
929 sc->stroff, sc->strsize, (const void**)&stab, (const void**)&stabstr);
931 return ret;
934 /******************************************************************
935 * macho_finish_stabs
937 * Integrate the non-debugging symbols we've gathered into the
938 * symbols that were generated during stabs parsing.
940 static void macho_finish_stabs(struct module* module, struct hash_table* ht_symtab)
942 struct hash_table_iter hti_ours;
943 struct symtab_elt* ste;
944 BOOL adjusted = FALSE;
946 TRACE("(%p, %p)\n", module, ht_symtab);
948 /* For each of our non-debugging symbols, see if it can provide some
949 * missing details to one of the module's known symbols. */
950 hash_table_iter_init(ht_symtab, &hti_ours, NULL);
951 while ((ste = hash_table_iter_up(&hti_ours)))
953 struct hash_table_iter hti_modules;
954 void* ptr;
955 struct symt_ht* sym;
956 struct symt_function* func;
957 struct symt_data* data;
959 hash_table_iter_init(&module->ht_symbols, &hti_modules, ste->ht_elt.name);
960 while ((ptr = hash_table_iter_up(&hti_modules)))
962 sym = CONTAINING_RECORD(ptr, struct symt_ht, hash_elt);
964 if (strcmp(sym->hash_elt.name, ste->ht_elt.name))
965 continue;
967 switch (sym->symt.tag)
969 case SymTagFunction:
970 func = (struct symt_function*)sym;
971 if (func->address == module->format_info[DFI_MACHO]->u.macho_info->load_addr)
973 TRACE("Adjusting function %p/%s!%s from 0x%08lx to 0x%08lx\n", func,
974 debugstr_w(module->module.ModuleName), sym->hash_elt.name,
975 func->address, ste->addr);
976 func->address = ste->addr;
977 adjusted = TRUE;
979 if (func->address == ste->addr)
980 ste->used = 1;
981 break;
982 case SymTagData:
983 data = (struct symt_data*)sym;
984 switch (data->kind)
986 case DataIsGlobal:
987 case DataIsFileStatic:
988 if (data->u.var.offset == module->format_info[DFI_MACHO]->u.macho_info->load_addr)
990 TRACE("Adjusting data symbol %p/%s!%s from 0x%08lx to 0x%08lx\n",
991 data, debugstr_w(module->module.ModuleName), sym->hash_elt.name,
992 data->u.var.offset, ste->addr);
993 data->u.var.offset = ste->addr;
994 adjusted = TRUE;
996 if (data->u.var.offset == ste->addr)
998 enum DataKind new_kind;
1000 new_kind = ste->is_global ? DataIsGlobal : DataIsFileStatic;
1001 if (data->kind != new_kind)
1003 WARN("Changing kind for %p/%s!%s from %d to %d\n", sym,
1004 debugstr_w(module->module.ModuleName), sym->hash_elt.name,
1005 (int)data->kind, (int)new_kind);
1006 data->kind = new_kind;
1007 adjusted = TRUE;
1009 ste->used = 1;
1011 break;
1012 default:;
1014 break;
1015 default:
1016 TRACE("Ignoring tag %u\n", sym->symt.tag);
1017 break;
1022 if (adjusted)
1024 /* since we may have changed some addresses, mark the module to be resorted */
1025 module->sortlist_valid = FALSE;
1028 /* Mark any of our non-debugging symbols which fall on an already-used
1029 * address as "used". This allows us to skip them in the next loop,
1030 * below. We do this in separate loops because symt_new_* marks the
1031 * list as needing sorting and symt_find_nearest sorts if needed,
1032 * causing thrashing. */
1033 if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
1035 hash_table_iter_init(ht_symtab, &hti_ours, NULL);
1036 while ((ste = hash_table_iter_up(&hti_ours)))
1038 struct symt_ht* sym;
1039 ULONG64 addr;
1041 if (ste->used) continue;
1043 sym = symt_find_nearest(module, ste->addr);
1044 if (sym)
1045 symt_get_address(&sym->symt, &addr);
1046 if (sym && ste->addr == addr)
1048 ULONG64 size = 0;
1049 DWORD kind = -1;
1051 ste->used = 1;
1053 /* If neither symbol has a correct size (ours never does), we
1054 * consider them both to be markers. No warning is needed in
1055 * that case.
1056 * Also, we check that we don't have two symbols, one local, the other
1057 * global, which is legal.
1059 symt_get_info(module, &sym->symt, TI_GET_LENGTH, &size);
1060 symt_get_info(module, &sym->symt, TI_GET_DATAKIND, &kind);
1061 if (size && kind == (ste->is_global ? DataIsGlobal : DataIsFileStatic))
1062 FIXME("Duplicate in %s: %s<%08lx> %s<%s-%s>\n",
1063 debugstr_w(module->module.ModuleName),
1064 ste->ht_elt.name, ste->addr,
1065 sym->hash_elt.name,
1066 wine_dbgstr_longlong(addr), wine_dbgstr_longlong(size));
1071 /* For any of our remaining non-debugging symbols which have no match
1072 * among the module's known symbols, add them as new symbols. */
1073 hash_table_iter_init(ht_symtab, &hti_ours, NULL);
1074 while ((ste = hash_table_iter_up(&hti_ours)))
1076 if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY) && !ste->used)
1078 if (ste->is_code)
1080 symt_new_function(module, ste->compiland, ste->ht_elt.name,
1081 ste->addr, 0, NULL);
1083 else
1085 struct location loc;
1087 loc.kind = loc_absolute;
1088 loc.reg = 0;
1089 loc.offset = ste->addr;
1090 symt_new_global_variable(module, ste->compiland, ste->ht_elt.name,
1091 !ste->is_global, loc, 0, NULL);
1094 ste->used = 1;
1097 if (ste->is_public && !(dbghelp_options & SYMOPT_NO_PUBLICS))
1099 symt_new_public(module, ste->compiland, ste->ht_elt.name, ste->is_code, ste->addr, 0);
1104 /******************************************************************
1105 * try_dsym
1107 * Try to load a debug symbol file from the given path and check
1108 * if its UUID matches the UUID of an already-mapped file. If so,
1109 * stash the file map in the "dsym" field of the file and return
1110 * TRUE. If it can't be mapped or its UUID doesn't match, return
1111 * FALSE.
1113 static BOOL try_dsym(struct process *pcs, const WCHAR* path, struct macho_file_map* fmap)
1115 struct image_file_map dsym_ifm;
1117 if (macho_map_file(pcs, path, FALSE, &dsym_ifm))
1119 char uuid_string[UUID_STRING_LEN];
1121 if (dsym_ifm.u.macho.uuid && !memcmp(dsym_ifm.u.macho.uuid->uuid, fmap->uuid->uuid, sizeof(fmap->uuid->uuid)))
1123 TRACE("found matching debug symbol file at %s\n", debugstr_w(path));
1124 fmap->dsym = HeapAlloc(GetProcessHeap(), 0, sizeof(dsym_ifm));
1125 *fmap->dsym = dsym_ifm;
1126 return TRUE;
1129 TRACE("candidate debug symbol file at %s has wrong UUID %s; ignoring\n", debugstr_w(path),
1130 format_uuid(dsym_ifm.u.macho.uuid->uuid, uuid_string));
1132 macho_unmap_file(&dsym_ifm);
1134 else
1135 TRACE("couldn't map file at %s\n", debugstr_w(path));
1137 return FALSE;
1140 /******************************************************************
1141 * find_and_map_dsym
1143 * Search for a debugging symbols file associated with a module and
1144 * map it. First look for a .dSYM bundle next to the module file
1145 * (e.g. <path>.dSYM/Contents/Resources/DWARF/<basename of path>)
1146 * as produced by dsymutil. Next, look for a .dwarf file next to
1147 * the module file (e.g. <path>.dwarf) as produced by
1148 * "dsymutil --flat". Finally, use Spotlight to search for a
1149 * .dSYM bundle with the same UUID as the module file.
1151 static void find_and_map_dsym(struct process *pcs, struct module* module)
1153 static const WCHAR dot_dsym[] = {'.','d','S','Y','M',0};
1154 static const WCHAR dsym_subpath[] = {'/','C','o','n','t','e','n','t','s','/','R','e','s','o','u','r','c','e','s','/','D','W','A','R','F','/',0};
1155 static const WCHAR dot_dwarf[] = {'.','d','w','a','r','f',0};
1156 struct macho_file_map* fmap = &module->format_info[DFI_MACHO]->u.macho_info->file_map.u.macho;
1157 const WCHAR* p;
1158 size_t len;
1159 WCHAR* path = NULL;
1160 char uuid_string[UUID_STRING_LEN];
1161 CFStringRef uuid_cfstring;
1162 CFStringRef query_string;
1163 MDQueryRef query = NULL;
1165 /* Without a UUID, we can't verify that any debug info file we find corresponds
1166 to this file. Better to have no debug info than incorrect debug info. */
1167 if (!fmap->uuid)
1168 return;
1170 if ((p = strrchrW(module->module.LoadedImageName, '/')))
1171 p++;
1172 else
1173 p = module->module.LoadedImageName;
1174 len = strlenW(module->module.LoadedImageName) + strlenW(dot_dsym) + strlenW(dsym_subpath) + strlenW(p) + 1;
1175 path = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1176 if (!path)
1177 return;
1178 strcpyW(path, module->module.LoadedImageName);
1179 strcatW(path, dot_dsym);
1180 strcatW(path, dsym_subpath);
1181 strcatW(path, p);
1183 if (try_dsym(pcs, path, fmap))
1184 goto found;
1186 strcpyW(path + strlenW(module->module.LoadedImageName), dot_dwarf);
1188 if (try_dsym(pcs, path, fmap))
1189 goto found;
1191 format_uuid(fmap->uuid->uuid, uuid_string);
1192 uuid_cfstring = CFStringCreateWithCString(NULL, uuid_string, kCFStringEncodingASCII);
1193 query_string = CFStringCreateWithFormat(NULL, NULL, CFSTR("com_apple_xcode_dsym_uuids == \"%@\""), uuid_cfstring);
1194 CFRelease(uuid_cfstring);
1195 query = MDQueryCreate(NULL, query_string, NULL, NULL);
1196 CFRelease(query_string);
1197 MDQuerySetMaxCount(query, 1);
1198 if (MDQueryExecute(query, kMDQuerySynchronous) && MDQueryGetResultCount(query) >= 1)
1200 MDItemRef item = (MDItemRef)MDQueryGetResultAtIndex(query, 0);
1201 CFStringRef item_path = MDItemCopyAttribute(item, kMDItemPath);
1202 if (item_path)
1204 CFIndex item_path_len = CFStringGetLength(item_path);
1205 if (item_path_len + strlenW(dsym_subpath) + strlenW(p) >= len)
1207 HeapFree(GetProcessHeap(), 0, path);
1208 len = item_path_len + strlenW(dsym_subpath) + strlenW(p) + 1;
1209 path = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1211 CFStringGetCharacters(item_path, CFRangeMake(0, item_path_len), (UniChar*)path);
1212 strcpyW(path + item_path_len, dsym_subpath);
1213 strcatW(path, p);
1214 CFRelease(item_path);
1216 if (try_dsym(pcs, path, fmap))
1217 goto found;
1221 found:
1222 HeapFree(GetProcessHeap(), 0, path);
1223 if (query) CFRelease(query);
1226 /******************************************************************
1227 * image_uses_split_segs
1229 * Determine if the Mach-O image loaded at a particular address in
1230 * the given process is in the dyld shared cache and therefore has
1231 * its segments mapped non-contiguously.
1233 * The image header has to be loaded from the process's memory
1234 * because the relevant flag is only set in memory, not in the file.
1236 static BOOL image_uses_split_segs(HANDLE process, unsigned long load_addr)
1238 BOOL split_segs = FALSE;
1240 if (process && load_addr)
1242 struct process *pcs = process_find_by_handle(process);
1243 cpu_type_t target_cpu = (pcs->is_64bit) ? CPU_TYPE_X86_64 : CPU_TYPE_X86;
1244 uint32_t target_magic = (pcs->is_64bit) ? MH_MAGIC_64 : MH_MAGIC;
1245 struct mach_header header;
1247 if (ReadProcessMemory(process, (void*)load_addr, &header, sizeof(header), NULL) &&
1248 header.magic == target_magic && header.cputype == target_cpu &&
1249 header.flags & MACHO_DYLD_IN_SHARED_CACHE)
1251 split_segs = TRUE;
1255 return split_segs;
1258 /******************************************************************
1259 * macho_load_debug_info
1261 * Loads Mach-O debugging information from the module image file.
1263 BOOL macho_load_debug_info(struct process *pcs, struct module* module)
1265 BOOL ret = FALSE;
1266 struct macho_debug_info mdi;
1267 int result;
1268 struct image_file_map *ifm;
1269 struct macho_file_map *fmap;
1271 if (module->type != DMT_MACHO || !module->format_info[DFI_MACHO]->u.macho_info)
1273 ERR("Bad Mach-O module '%s'\n", debugstr_w(module->module.LoadedImageName));
1274 return FALSE;
1277 ifm = &module->format_info[DFI_MACHO]->u.macho_info->file_map;
1278 fmap = &ifm->u.macho;
1280 TRACE("(%p, %p/%d)\n", module, fmap, fmap->fd);
1282 module->module.SymType = SymExport;
1284 if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
1286 find_and_map_dsym(pcs, module);
1288 if (dwarf2_parse(module, module->reloc_delta, NULL /* FIXME: some thunks to deal with ? */,
1289 &module->format_info[DFI_MACHO]->u.macho_info->file_map))
1290 ret = TRUE;
1293 mdi.fmap = fmap;
1294 mdi.module = module;
1295 pool_init(&mdi.pool, 65536);
1296 hash_table_init(&mdi.pool, &mdi.ht_symtab, 256);
1297 result = macho_enum_load_commands(ifm, LC_SYMTAB, macho_parse_symtab, &mdi);
1298 if (result > 0)
1299 ret = TRUE;
1300 else if (result < 0)
1301 WARN("Couldn't correctly read stabs\n");
1303 if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY) && fmap->dsym)
1305 mdi.fmap = &fmap->dsym->u.macho;
1306 result = macho_enum_load_commands(fmap->dsym, LC_SYMTAB, macho_parse_symtab, &mdi);
1307 if (result > 0)
1308 ret = TRUE;
1309 else if (result < 0)
1310 WARN("Couldn't correctly read stabs\n");
1313 macho_finish_stabs(module, &mdi.ht_symtab);
1315 pool_destroy(&mdi.pool);
1316 return ret;
1319 /******************************************************************
1320 * macho_fetch_file_info
1322 * Gathers some more information for a Mach-O module from a given file
1324 BOOL macho_fetch_file_info(HANDLE process, const WCHAR* name, unsigned long load_addr, DWORD_PTR* base,
1325 DWORD* size, DWORD* checksum)
1327 struct image_file_map fmap;
1328 struct process *pcs;
1329 BOOL split_segs;
1331 TRACE("(%s, %p, %p, %p)\n", debugstr_w(name), base, size, checksum);
1333 pcs = process_find_by_handle(process);
1334 if (!pcs) return FALSE;
1336 split_segs = image_uses_split_segs(process, load_addr);
1337 if (!macho_map_file(pcs, name, split_segs, &fmap)) return FALSE;
1338 if (base) *base = fmap.u.macho.segs_start;
1339 *size = fmap.u.macho.segs_size;
1340 *checksum = calc_crc32(fmap.u.macho.fd);
1341 macho_unmap_file(&fmap);
1342 return TRUE;
1345 /******************************************************************
1346 * macho_module_remove
1348 static void macho_module_remove(struct process* pcs, struct module_format* modfmt)
1350 macho_unmap_file(&modfmt->u.macho_info->file_map);
1351 HeapFree(GetProcessHeap(), 0, modfmt);
1355 /******************************************************************
1356 * get_dyld_image_info_address
1358 static ULONG_PTR get_dyld_image_info_address(struct process* pcs)
1360 NTSTATUS status;
1361 PROCESS_BASIC_INFORMATION pbi;
1362 ULONG_PTR dyld_image_info_address = 0;
1363 BOOL ret;
1365 /* Get address of PEB */
1366 status = NtQueryInformationProcess(pcs->handle, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
1367 if (status == STATUS_SUCCESS)
1369 /* Read dyld image info address from PEB */
1370 if (!pcs->is_64bit)
1371 ret = ReadProcessMemory(pcs->handle, &pbi.PebBaseAddress->Reserved[0],
1372 &dyld_image_info_address, sizeof(dyld_image_info_address), NULL);
1373 else
1375 PEB32 *peb32 = (PEB32 *)pbi.PebBaseAddress;
1376 ULONG addr32;
1377 ret = ReadProcessMemory(pcs->handle, &peb32->Reserved[0], &addr32,
1378 sizeof(addr32), NULL);
1379 dyld_image_info_address = addr32;
1382 if (ret)
1383 TRACE("got dyld_image_info_address %#lx from PEB %p\n",
1384 dyld_image_info_address, pbi.PebBaseAddress);
1387 #ifndef __LP64__ /* No reading the symtab with nlist(3) in LP64 */
1388 if (!dyld_image_info_address)
1390 static void* dyld_all_image_infos_addr;
1392 /* Our next best guess is that dyld was loaded at its base address
1393 and we can find the dyld image infos address by looking up its symbol. */
1394 if (!dyld_all_image_infos_addr)
1396 struct nlist nl[2];
1397 memset(nl, 0, sizeof(nl));
1398 nl[0].n_un.n_name = (char*)"_dyld_all_image_infos";
1399 if (!nlist("/usr/lib/dyld", nl))
1400 dyld_all_image_infos_addr = (void*)nl[0].n_value;
1403 if (dyld_all_image_infos_addr)
1405 TRACE("got dyld_image_info_address %p from /usr/lib/dyld symbol table\n",
1406 dyld_all_image_infos_addr);
1407 dyld_image_info_address = (ULONG_PTR)dyld_all_image_infos_addr;
1410 #endif
1412 return dyld_image_info_address;
1415 /******************************************************************
1416 * macho_load_file
1418 * Loads the information for Mach-O module stored in 'filename'.
1419 * The module has been loaded at 'load_addr' address.
1420 * returns
1421 * FALSE if the file cannot be found/opened or if the file doesn't
1422 * contain symbolic info (or this info cannot be read or parsed)
1423 * TRUE on success
1425 static BOOL macho_load_file(struct process* pcs, const WCHAR* filename,
1426 unsigned long load_addr, struct macho_info* macho_info)
1428 BOOL ret = TRUE;
1429 BOOL split_segs;
1430 struct image_file_map fmap;
1432 TRACE("(%p/%p, %s, 0x%08lx, %p/0x%08x)\n", pcs, pcs->handle, debugstr_w(filename),
1433 load_addr, macho_info, macho_info->flags);
1435 split_segs = image_uses_split_segs(pcs->handle, load_addr);
1436 if (!macho_map_file(pcs, filename, split_segs, &fmap)) return FALSE;
1438 /* Find the dynamic loader's table of images loaded into the process.
1440 if (macho_info->flags & MACHO_INFO_DEBUG_HEADER)
1442 macho_info->dbg_hdr_addr = (unsigned long)get_dyld_image_info_address(pcs);
1443 ret = TRUE;
1446 if (macho_info->flags & MACHO_INFO_MODULE)
1448 struct macho_module_info *macho_module_info;
1449 struct module_format* modfmt =
1450 HeapAlloc(GetProcessHeap(), 0, sizeof(struct module_format) + sizeof(struct macho_module_info));
1451 if (!modfmt) goto leave;
1452 if (!load_addr)
1453 load_addr = fmap.u.macho.segs_start;
1454 macho_info->module = module_new(pcs, filename, DMT_MACHO, FALSE, load_addr,
1455 fmap.u.macho.segs_size, 0, calc_crc32(fmap.u.macho.fd));
1456 if (!macho_info->module)
1458 HeapFree(GetProcessHeap(), 0, modfmt);
1459 goto leave;
1461 macho_info->module->reloc_delta = macho_info->module->module.BaseOfImage - fmap.u.macho.segs_start;
1462 macho_module_info = (void*)(modfmt + 1);
1463 macho_info->module->format_info[DFI_MACHO] = modfmt;
1465 modfmt->module = macho_info->module;
1466 modfmt->remove = macho_module_remove;
1467 modfmt->loc_compute = NULL;
1468 modfmt->u.macho_info = macho_module_info;
1470 macho_module_info->load_addr = load_addr;
1472 macho_module_info->file_map = fmap;
1473 reset_file_map(&fmap);
1474 if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
1475 macho_info->module->module.SymType = SymDeferred;
1476 else if (!macho_load_debug_info(pcs, macho_info->module))
1477 ret = FALSE;
1479 macho_info->module->format_info[DFI_MACHO]->u.macho_info->in_use = 1;
1480 macho_info->module->format_info[DFI_MACHO]->u.macho_info->is_loader = 0;
1481 TRACE("module = %p\n", macho_info->module);
1484 if (macho_info->flags & MACHO_INFO_NAME)
1486 WCHAR* ptr;
1487 ptr = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(filename) + 1) * sizeof(WCHAR));
1488 if (ptr)
1490 strcpyW(ptr, filename);
1491 macho_info->module_name = ptr;
1493 else ret = FALSE;
1494 TRACE("module_name = %p %s\n", macho_info->module_name, debugstr_w(macho_info->module_name));
1496 leave:
1497 macho_unmap_file(&fmap);
1499 TRACE(" => %d\n", ret);
1500 return ret;
1503 /******************************************************************
1504 * macho_load_file_from_path
1505 * Tries to load a Mach-O file from a set of paths (separated by ':')
1507 static BOOL macho_load_file_from_path(struct process* pcs,
1508 const WCHAR* filename,
1509 unsigned long load_addr,
1510 const char* path,
1511 struct macho_info* macho_info)
1513 BOOL ret = FALSE;
1514 WCHAR *s, *t, *fn;
1515 WCHAR* pathW = NULL;
1516 unsigned len;
1518 TRACE("(%p/%p, %s, 0x%08lx, %s, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
1519 debugstr_a(path), macho_info);
1521 if (!path) return FALSE;
1523 len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
1524 pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1525 if (!pathW) return FALSE;
1526 MultiByteToWideChar(CP_UNIXCP, 0, path, -1, pathW, len);
1528 for (s = pathW; s && *s; s = (t) ? (t+1) : NULL)
1530 t = strchrW(s, ':');
1531 if (t) *t = '\0';
1532 fn = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(filename) + 1 + lstrlenW(s) + 1) * sizeof(WCHAR));
1533 if (!fn) break;
1534 strcpyW(fn, s);
1535 strcatW(fn, S_SlashW);
1536 strcatW(fn, filename);
1537 ret = macho_load_file(pcs, fn, load_addr, macho_info);
1538 HeapFree(GetProcessHeap(), 0, fn);
1539 if (ret) break;
1540 s = (t) ? (t+1) : NULL;
1543 TRACE(" => %d\n", ret);
1544 HeapFree(GetProcessHeap(), 0, pathW);
1545 return ret;
1548 /******************************************************************
1549 * macho_load_file_from_dll_path
1551 * Tries to load a Mach-O file from the dll path
1553 static BOOL macho_load_file_from_dll_path(struct process* pcs,
1554 const WCHAR* filename,
1555 unsigned long load_addr,
1556 struct macho_info* macho_info)
1558 BOOL ret = FALSE;
1559 unsigned int index = 0;
1560 const char *path;
1562 TRACE("(%p/%p, %s, 0x%08lx, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
1563 macho_info);
1565 while (!ret && (path = wine_dll_enum_load_path( index++ )))
1567 WCHAR *name;
1568 unsigned len;
1570 len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
1572 name = HeapAlloc( GetProcessHeap(), 0,
1573 (len + lstrlenW(filename) + 2) * sizeof(WCHAR) );
1575 if (!name) break;
1576 MultiByteToWideChar(CP_UNIXCP, 0, path, -1, name, len);
1577 strcatW( name, S_SlashW );
1578 strcatW( name, filename );
1579 ret = macho_load_file(pcs, name, load_addr, macho_info);
1580 HeapFree( GetProcessHeap(), 0, name );
1582 TRACE(" => %d\n", ret);
1583 return ret;
1586 /******************************************************************
1587 * macho_search_and_load_file
1589 * Lookup a file in standard Mach-O locations, and if found, load it
1591 static BOOL macho_search_and_load_file(struct process* pcs, const WCHAR* filename,
1592 unsigned long load_addr,
1593 struct macho_info* macho_info)
1595 BOOL ret = FALSE;
1596 struct module* module;
1597 static const WCHAR S_libstdcPPW[] = {'l','i','b','s','t','d','c','+','+','\0'};
1598 const WCHAR* p;
1600 TRACE("(%p/%p, %s, 0x%08lx, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
1601 macho_info);
1603 if (filename == NULL || *filename == '\0') return FALSE;
1604 if ((module = module_is_already_loaded(pcs, filename)))
1606 macho_info->module = module;
1607 module->format_info[DFI_MACHO]->u.macho_info->in_use = 1;
1608 return module->module.SymType;
1611 if (strstrW(filename, S_libstdcPPW)) return FALSE; /* We know we can't do it */
1613 /* If has no directories, try PATH first. */
1614 if (!strchrW(filename, '/'))
1616 ret = macho_load_file_from_path(pcs, filename, load_addr,
1617 getenv("PATH"), macho_info);
1619 /* Try DYLD_LIBRARY_PATH, with just the filename (no directories). */
1620 if (!ret)
1622 if ((p = strrchrW(filename, '/'))) p++;
1623 else p = filename;
1624 ret = macho_load_file_from_path(pcs, p, load_addr,
1625 getenv("DYLD_LIBRARY_PATH"), macho_info);
1627 /* Try the path as given. */
1628 if (!ret)
1629 ret = macho_load_file(pcs, filename, load_addr, macho_info);
1630 /* Try DYLD_FALLBACK_LIBRARY_PATH, with just the filename (no directories). */
1631 if (!ret)
1633 const char* fallback = getenv("DYLD_FALLBACK_LIBRARY_PATH");
1634 if (!fallback)
1635 fallback = "/usr/local/lib:/lib:/usr/lib";
1636 ret = macho_load_file_from_path(pcs, p, load_addr, fallback, macho_info);
1638 if (!ret && !strchrW(filename, '/'))
1639 ret = macho_load_file_from_dll_path(pcs, filename, load_addr, macho_info);
1641 return ret;
1644 /******************************************************************
1645 * macho_enum_modules_internal
1647 * Enumerate Mach-O modules from a running process
1649 static BOOL macho_enum_modules_internal(const struct process* pcs,
1650 const WCHAR* main_name,
1651 enum_modules_cb cb, void* user)
1653 struct dyld_all_image_infos image_infos;
1654 struct dyld_image_info* info_array = NULL;
1655 unsigned long len;
1656 int i;
1657 char bufstr[256];
1658 WCHAR bufstrW[MAX_PATH];
1659 BOOL ret = FALSE;
1661 TRACE("(%p/%p, %s, %p, %p)\n", pcs, pcs->handle, debugstr_w(main_name), cb,
1662 user);
1664 if (!pcs->dbg_hdr_addr ||
1665 !ReadProcessMemory(pcs->handle, (void*)pcs->dbg_hdr_addr,
1666 &image_infos, sizeof(image_infos), NULL) ||
1667 !image_infos.infoArray)
1668 goto done;
1669 TRACE("Process has %u image infos at %p\n", image_infos.infoArrayCount, image_infos.infoArray);
1671 len = image_infos.infoArrayCount * sizeof(info_array[0]);
1672 info_array = HeapAlloc(GetProcessHeap(), 0, len);
1673 if (!info_array ||
1674 !ReadProcessMemory(pcs->handle, image_infos.infoArray,
1675 info_array, len, NULL))
1676 goto done;
1677 TRACE("... read image infos\n");
1679 for (i = 0; i < image_infos.infoArrayCount; i++)
1681 if (info_array[i].imageFilePath != NULL &&
1682 ReadProcessMemory(pcs->handle, info_array[i].imageFilePath, bufstr, sizeof(bufstr), NULL))
1684 bufstr[sizeof(bufstr) - 1] = '\0';
1685 TRACE("[%d] image file %s\n", i, debugstr_a(bufstr));
1686 MultiByteToWideChar(CP_UNIXCP, 0, bufstr, -1, bufstrW, ARRAY_SIZE(bufstrW));
1687 if (main_name && !bufstrW[0]) strcpyW(bufstrW, main_name);
1688 if (!cb(bufstrW, (unsigned long)info_array[i].imageLoadAddress, user)) break;
1692 ret = TRUE;
1693 done:
1694 HeapFree(GetProcessHeap(), 0, info_array);
1695 return ret;
1698 struct macho_sync
1700 struct process* pcs;
1701 struct macho_info macho_info;
1704 static BOOL macho_enum_sync_cb(const WCHAR* name, unsigned long addr, void* user)
1706 struct macho_sync* ms = user;
1708 TRACE("(%s, 0x%08lx, %p)\n", debugstr_w(name), addr, user);
1709 macho_search_and_load_file(ms->pcs, name, addr, &ms->macho_info);
1710 return TRUE;
1713 /******************************************************************
1714 * macho_synchronize_module_list
1716 * Rescans the debuggee's modules list and synchronizes it with
1717 * the one from 'pcs', ie:
1718 * - if a module is in debuggee and not in pcs, it's loaded into pcs
1719 * - if a module is in pcs and not in debuggee, it's unloaded from pcs
1721 BOOL macho_synchronize_module_list(struct process* pcs)
1723 struct module* module;
1724 struct macho_sync ms;
1726 TRACE("(%p/%p)\n", pcs, pcs->handle);
1728 for (module = pcs->lmodules; module; module = module->next)
1730 if (module->type == DMT_MACHO && !module->is_virtual)
1731 module->format_info[DFI_MACHO]->u.macho_info->in_use = 0;
1734 ms.pcs = pcs;
1735 ms.macho_info.flags = MACHO_INFO_MODULE;
1736 if (!macho_enum_modules_internal(pcs, NULL, macho_enum_sync_cb, &ms))
1737 return FALSE;
1739 module = pcs->lmodules;
1740 while (module)
1742 if (module->type == DMT_MACHO && !module->is_virtual &&
1743 !module->format_info[DFI_MACHO]->u.macho_info->in_use &&
1744 !module->format_info[DFI_MACHO]->u.macho_info->is_loader)
1746 module_remove(pcs, module);
1747 /* restart all over */
1748 module = pcs->lmodules;
1750 else module = module->next;
1752 return TRUE;
1755 /******************************************************************
1756 * macho_search_loader
1758 * Lookup in a running Mach-O process the loader, and sets its Mach-O link
1759 * address (for accessing the list of loaded images) in pcs.
1760 * If flags is MACHO_INFO_MODULE, the module for the loader is also
1761 * added as a module into pcs.
1763 static BOOL macho_search_loader(struct process* pcs, struct macho_info* macho_info)
1765 WCHAR *loader = get_wine_loader_name(pcs);
1766 BOOL ret = FALSE;
1767 ULONG_PTR dyld_image_info_address;
1768 struct dyld_all_image_infos image_infos;
1769 struct dyld_image_info image_info;
1770 uint32_t len;
1771 char path[PATH_MAX];
1772 BOOL got_path = FALSE;
1774 dyld_image_info_address = get_dyld_image_info_address(pcs);
1775 if (dyld_image_info_address &&
1776 ReadProcessMemory(pcs->handle, (void*)dyld_image_info_address, &image_infos, sizeof(image_infos), NULL) &&
1777 image_infos.infoArray && image_infos.infoArrayCount &&
1778 ReadProcessMemory(pcs->handle, image_infos.infoArray, &image_info, sizeof(image_info), NULL) &&
1779 image_info.imageFilePath)
1781 for (len = sizeof(path); len > 0; len /= 2)
1783 if (ReadProcessMemory(pcs->handle, image_info.imageFilePath, path, len, NULL))
1785 path[len - 1] = 0;
1786 got_path = TRUE;
1787 TRACE("got executable path from target's dyld image info: %s\n", debugstr_a(path));
1788 break;
1793 /* If we couldn't get the executable path from the target process, try our
1794 own. It will almost always be the same. */
1795 if (!got_path)
1797 len = sizeof(path);
1798 if (!_NSGetExecutablePath(path, &len))
1800 got_path = TRUE;
1801 TRACE("using own executable path: %s\n", debugstr_a(path));
1805 if (got_path)
1807 WCHAR* pathW;
1809 len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
1810 pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1811 if (pathW)
1813 MultiByteToWideChar(CP_UNIXCP, 0, path, -1, pathW, len);
1814 ret = macho_load_file(pcs, pathW, 0, macho_info);
1815 HeapFree(GetProcessHeap(), 0, pathW);
1819 if (!ret)
1820 ret = macho_search_and_load_file(pcs, loader, 0, macho_info);
1821 heap_free(loader);
1822 return ret;
1825 /******************************************************************
1826 * macho_read_wine_loader_dbg_info
1828 * Try to find a decent wine executable which could have loaded the debuggee
1830 BOOL macho_read_wine_loader_dbg_info(struct process* pcs)
1832 struct macho_info macho_info;
1834 TRACE("(%p/%p)\n", pcs, pcs->handle);
1835 macho_info.flags = MACHO_INFO_DEBUG_HEADER | MACHO_INFO_MODULE;
1836 if (!macho_search_loader(pcs, &macho_info)) return FALSE;
1837 macho_info.module->format_info[DFI_MACHO]->u.macho_info->is_loader = 1;
1838 module_set_module(macho_info.module, S_WineLoaderW);
1839 return (pcs->dbg_hdr_addr = macho_info.dbg_hdr_addr) != 0;
1842 /******************************************************************
1843 * macho_enum_modules
1845 * Enumerates the Mach-O loaded modules from a running target (hProc)
1846 * This function doesn't require that someone has called SymInitialize
1847 * on this very process.
1849 BOOL macho_enum_modules(HANDLE hProc, enum_modules_cb cb, void* user)
1851 struct process pcs;
1852 struct macho_info macho_info;
1853 BOOL ret;
1855 TRACE("(%p, %p, %p)\n", hProc, cb, user);
1856 memset(&pcs, 0, sizeof(pcs));
1857 pcs.handle = hProc;
1858 macho_info.flags = MACHO_INFO_DEBUG_HEADER | MACHO_INFO_NAME;
1859 if (!macho_search_loader(&pcs, &macho_info)) return FALSE;
1860 pcs.dbg_hdr_addr = macho_info.dbg_hdr_addr;
1861 ret = macho_enum_modules_internal(&pcs, macho_info.module_name, cb, user);
1862 HeapFree(GetProcessHeap(), 0, (char*)macho_info.module_name);
1863 return ret;
1866 struct macho_load
1868 struct process* pcs;
1869 struct macho_info macho_info;
1870 const WCHAR* name;
1871 BOOL ret;
1874 /******************************************************************
1875 * macho_load_cb
1877 * Callback for macho_load_module, used to walk the list of loaded
1878 * modules.
1880 static BOOL macho_load_cb(const WCHAR* name, unsigned long addr, void* user)
1882 struct macho_load* ml = user;
1883 const WCHAR* p;
1885 TRACE("(%s, 0x%08lx, %p)\n", debugstr_w(name), addr, user);
1887 /* memcmp is needed for matches when bufstr contains also version information
1888 * ml->name: libc.so, name: libc.so.6.0
1890 p = strrchrW(name, '/');
1891 if (!p++) p = name;
1892 if (!memcmp(p, ml->name, lstrlenW(ml->name) * sizeof(WCHAR)))
1894 ml->ret = macho_search_and_load_file(ml->pcs, name, addr, &ml->macho_info);
1895 return FALSE;
1897 return TRUE;
1900 /******************************************************************
1901 * macho_load_module
1903 * Loads a Mach-O module and stores it in process' module list.
1904 * Also, find module real name and load address from
1905 * the real loaded modules list in pcs address space.
1907 struct module* macho_load_module(struct process* pcs, const WCHAR* name, unsigned long addr)
1909 struct macho_load ml;
1911 TRACE("(%p/%p, %s, 0x%08lx)\n", pcs, pcs->handle, debugstr_w(name), addr);
1913 ml.macho_info.flags = MACHO_INFO_MODULE;
1914 ml.ret = FALSE;
1916 if (pcs->dbg_hdr_addr) /* we're debugging a live target */
1918 ml.pcs = pcs;
1919 /* do only the lookup from the filename, not the path (as we lookup module
1920 * name in the process' loaded module list)
1922 ml.name = strrchrW(name, '/');
1923 if (!ml.name++) ml.name = name;
1924 ml.ret = FALSE;
1926 if (!macho_enum_modules_internal(pcs, NULL, macho_load_cb, &ml))
1927 return NULL;
1929 else if (addr)
1931 ml.name = name;
1932 ml.ret = macho_search_and_load_file(pcs, ml.name, addr, &ml.macho_info);
1934 if (!ml.ret) return NULL;
1935 assert(ml.macho_info.module);
1936 return ml.macho_info.module;
1939 #else /* HAVE_MACH_O_LOADER_H */
1941 BOOL macho_find_section(struct image_file_map* ifm, const char* segname, const char* sectname, struct image_section_map* ism)
1943 return FALSE;
1946 const char* macho_map_section(struct image_section_map* ism)
1948 return NULL;
1951 void macho_unmap_section(struct image_section_map* ism)
1955 DWORD_PTR macho_get_map_rva(const struct image_section_map* ism)
1957 return 0;
1960 unsigned macho_get_map_size(const struct image_section_map* ism)
1962 return 0;
1965 BOOL macho_synchronize_module_list(struct process* pcs)
1967 return FALSE;
1970 BOOL macho_fetch_file_info(HANDLE process, const WCHAR* name, unsigned long load_addr, DWORD_PTR* base,
1971 DWORD* size, DWORD* checksum)
1973 return FALSE;
1976 BOOL macho_read_wine_loader_dbg_info(struct process* pcs)
1978 return FALSE;
1981 BOOL macho_enum_modules(HANDLE hProc, enum_modules_cb cb, void* user)
1983 return FALSE;
1986 struct module* macho_load_module(struct process* pcs, const WCHAR* name, unsigned long addr)
1988 return NULL;
1991 BOOL macho_load_debug_info(struct process *pcs, struct module* module)
1993 return FALSE;
1995 #endif /* HAVE_MACH_O_LOADER_H */