user32: Add a test to show that fonts returned by SystemParametersInfo(SPI_GETNONCLIE...
[wine.git] / dlls / dbghelp / macho_module.c
blob3e91403ac6fa1a60bee9eb76150ca9fcefa58385
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 "image_private.h"
56 #ifdef HAVE_MACH_O_LOADER_H
58 #include <mach-o/fat.h>
59 #include <mach-o/loader.h>
60 #include <mach-o/nlist.h>
62 #ifdef HAVE_MACH_O_DYLD_IMAGES_H
63 #include <mach-o/dyld_images.h>
64 #else
65 struct dyld_image_info {
66 const struct mach_header *imageLoadAddress;
67 const char *imageFilePath;
68 uintptr_t imageFileModDate;
71 struct dyld_all_image_infos {
72 uint32_t version;
73 uint32_t infoArrayCount;
74 const struct dyld_image_info *infoArray;
75 void* notification;
76 int processDetachedFromSharedRegion;
78 #endif
80 #ifdef WORDS_BIGENDIAN
81 #define swap_ulong_be_to_host(n) (n)
82 #else
83 #define swap_ulong_be_to_host(n) (RtlUlongByteSwap(n))
84 #endif
86 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp_macho);
89 #ifdef _WIN64
90 typedef struct segment_command_64 macho_segment_command;
91 typedef struct nlist_64 macho_nlist;
93 #define TARGET_CPU_TYPE CPU_TYPE_X86_64
94 #define TARGET_MH_MAGIC MH_MAGIC_64
95 #define TARGET_SEGMENT_COMMAND LC_SEGMENT_64
96 #else
97 typedef struct segment_command macho_segment_command;
98 typedef struct nlist macho_nlist;
100 #define TARGET_CPU_TYPE CPU_TYPE_X86
101 #define TARGET_MH_MAGIC MH_MAGIC
102 #define TARGET_SEGMENT_COMMAND LC_SEGMENT
103 #endif
106 #define UUID_STRING_LEN 37 /* 16 bytes at 2 hex digits apiece, 4 dashes, and the null terminator */
109 struct macho_module_info
111 struct image_file_map file_map;
112 unsigned long load_addr;
113 unsigned short in_use : 1,
114 is_loader : 1;
117 #define MACHO_INFO_DEBUG_HEADER 0x0001
118 #define MACHO_INFO_MODULE 0x0002
119 #define MACHO_INFO_NAME 0x0004
121 struct macho_info
123 unsigned flags; /* IN one (or several) of the MACHO_INFO constants */
124 unsigned long dbg_hdr_addr; /* OUT address of debug header (if MACHO_INFO_DEBUG_HEADER is set) */
125 struct module* module; /* OUT loaded module (if MACHO_INFO_MODULE is set) */
126 const WCHAR* module_name; /* OUT found module name (if MACHO_INFO_NAME is set) */
129 static void macho_unmap_file(struct image_file_map* fmap);
131 static char* format_uuid(const uint8_t uuid[16], char out[UUID_STRING_LEN])
133 sprintf(out, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
134 uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
135 uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
136 return out;
139 /******************************************************************
140 * macho_calc_range
142 * For a range (offset & length) of a single architecture within
143 * a Mach-O file, calculate the page-aligned range of the whole file
144 * that encompasses it. For a fat binary, the architecture will
145 * itself be offset within the file, so take that into account.
147 static void macho_calc_range(const struct macho_file_map* fmap, unsigned long offset,
148 unsigned long len, unsigned long* out_aligned_offset,
149 unsigned long* out_aligned_end, unsigned long* out_aligned_len,
150 unsigned long* out_misalign)
152 unsigned long pagemask = sysconf( _SC_PAGESIZE ) - 1;
153 unsigned long file_offset, misalign;
155 file_offset = fmap->arch_offset + offset;
156 misalign = file_offset & pagemask;
157 *out_aligned_offset = file_offset - misalign;
158 *out_aligned_end = (file_offset + len + pagemask) & ~pagemask;
159 if (out_aligned_len)
160 *out_aligned_len = *out_aligned_end - *out_aligned_offset;
161 if (out_misalign)
162 *out_misalign = misalign;
165 /******************************************************************
166 * macho_map_range
168 * Maps a range (offset, length in bytes) from a Mach-O file into memory
170 static const char* macho_map_range(const struct macho_file_map* fmap, unsigned long offset, unsigned long len,
171 const char** base)
173 unsigned long misalign, aligned_offset, aligned_map_end, map_size;
174 const void* aligned_ptr;
176 TRACE("(%p/%d, 0x%08lx, 0x%08lx)\n", fmap, fmap->fd, offset, len);
178 macho_calc_range(fmap, offset, len, &aligned_offset, &aligned_map_end,
179 &map_size, &misalign);
181 aligned_ptr = mmap(NULL, map_size, PROT_READ, MAP_PRIVATE, fmap->fd, aligned_offset);
183 TRACE("Mapped (0x%08lx - 0x%08lx) to %p\n", aligned_offset, aligned_map_end, aligned_ptr);
185 if (aligned_ptr == MAP_FAILED) return IMAGE_NO_MAP;
186 if (base)
187 *base = aligned_ptr;
188 return (const char*)aligned_ptr + misalign;
191 /******************************************************************
192 * macho_unmap_range
194 * Unmaps a range (offset, length in bytes) of a Mach-O file from memory
196 static void macho_unmap_range(const char** base, const void** mapped, const struct macho_file_map* fmap,
197 unsigned long offset, unsigned long len)
199 TRACE("(%p, %p, %p/%d, 0x%08lx, 0x%08lx)\n", base, mapped, fmap, fmap->fd, offset, len);
201 if ((mapped && *mapped != IMAGE_NO_MAP) || (base && *base != IMAGE_NO_MAP))
203 unsigned long misalign, aligned_offset, aligned_map_end, map_size;
204 void* aligned_ptr;
206 macho_calc_range(fmap, offset, len, &aligned_offset, &aligned_map_end,
207 &map_size, &misalign);
209 if (mapped)
210 aligned_ptr = (char*)*mapped - misalign;
211 else
212 aligned_ptr = (void*)*base;
213 if (munmap(aligned_ptr, map_size) < 0)
214 WARN("Couldn't unmap the range\n");
215 TRACE("Unmapped (0x%08lx - 0x%08lx) from %p - %p\n", aligned_offset, aligned_map_end, aligned_ptr, (char*)aligned_ptr + map_size);
216 if (mapped)
217 *mapped = IMAGE_NO_MAP;
218 if (base)
219 *base = IMAGE_NO_MAP;
223 /******************************************************************
224 * macho_map_ranges
226 * Maps two ranges (offset, length in bytes) from a Mach-O file
227 * into memory. If the two ranges overlap, use one mmap so that
228 * the munmap doesn't fragment the mapping.
230 static BOOL macho_map_ranges(const struct macho_file_map* fmap,
231 unsigned long offset1, unsigned long len1,
232 unsigned long offset2, unsigned long len2,
233 const void** mapped1, const void** mapped2)
235 unsigned long aligned_offset1, aligned_map_end1;
236 unsigned long aligned_offset2, aligned_map_end2;
238 TRACE("(%p/%d, 0x%08lx, 0x%08lx, 0x%08lx, 0x%08lx, %p, %p)\n", fmap, fmap->fd,
239 offset1, len1, offset2, len2, mapped1, mapped2);
241 macho_calc_range(fmap, offset1, len1, &aligned_offset1, &aligned_map_end1, NULL, NULL);
242 macho_calc_range(fmap, offset2, len2, &aligned_offset2, &aligned_map_end2, NULL, NULL);
244 if (aligned_map_end1 < aligned_offset2 || aligned_map_end2 < aligned_offset1)
246 *mapped1 = macho_map_range(fmap, offset1, len1, NULL);
247 if (*mapped1 != IMAGE_NO_MAP)
249 *mapped2 = macho_map_range(fmap, offset2, len2, NULL);
250 if (*mapped2 == IMAGE_NO_MAP)
251 macho_unmap_range(NULL, mapped1, fmap, offset1, len1);
254 else
256 if (offset1 < offset2)
258 *mapped1 = macho_map_range(fmap, offset1, offset2 + len2 - offset1, NULL);
259 if (*mapped1 != IMAGE_NO_MAP)
260 *mapped2 = (const char*)*mapped1 + offset2 - offset1;
262 else
264 *mapped2 = macho_map_range(fmap, offset2, offset1 + len1 - offset2, NULL);
265 if (*mapped2 != IMAGE_NO_MAP)
266 *mapped1 = (const char*)*mapped2 + offset1 - offset2;
270 TRACE(" => %p, %p\n", *mapped1, *mapped2);
272 return (*mapped1 != IMAGE_NO_MAP) && (*mapped2 != IMAGE_NO_MAP);
275 /******************************************************************
276 * macho_unmap_ranges
278 * Unmaps two ranges (offset, length in bytes) of a Mach-O file
279 * from memory. Use for ranges which were mapped by
280 * macho_map_ranges.
282 static void macho_unmap_ranges(const struct macho_file_map* fmap,
283 unsigned long offset1, unsigned long len1,
284 unsigned long offset2, unsigned long len2,
285 const void** mapped1, const void** mapped2)
287 unsigned long aligned_offset1, aligned_map_end1;
288 unsigned long aligned_offset2, aligned_map_end2;
290 TRACE("(%p/%d, 0x%08lx, 0x%08lx, 0x%08lx, 0x%08lx, %p/%p, %p/%p)\n", fmap, fmap->fd,
291 offset1, len1, offset2, len2, mapped1, *mapped1, mapped2, *mapped2);
293 macho_calc_range(fmap, offset1, len1, &aligned_offset1, &aligned_map_end1, NULL, NULL);
294 macho_calc_range(fmap, offset2, len2, &aligned_offset2, &aligned_map_end2, NULL, NULL);
296 if (aligned_map_end1 < aligned_offset2 || aligned_map_end2 < aligned_offset1)
298 macho_unmap_range(NULL, mapped1, fmap, offset1, len1);
299 macho_unmap_range(NULL, mapped2, fmap, offset2, len2);
301 else
303 if (offset1 < offset2)
305 macho_unmap_range(NULL, mapped1, fmap, offset1, offset2 + len2 - offset1);
306 *mapped2 = IMAGE_NO_MAP;
308 else
310 macho_unmap_range(NULL, mapped2, fmap, offset2, offset1 + len1 - offset2);
311 *mapped1 = IMAGE_NO_MAP;
316 /******************************************************************
317 * macho_find_section
319 BOOL macho_find_section(struct image_file_map* ifm, const char* segname, const char* sectname, struct image_section_map* ism)
321 struct macho_file_map* fmap;
322 unsigned i;
323 char tmp[sizeof(fmap->sect[0].section->sectname)];
325 /* Other parts of dbghelp use section names like ".eh_frame". Mach-O uses
326 names like "__eh_frame". Convert those. */
327 if (sectname[0] == '.')
329 lstrcpynA(tmp, "__", sizeof(tmp));
330 lstrcpynA(tmp + 2, sectname + 1, sizeof(tmp) - 2);
331 sectname = tmp;
334 while (ifm)
336 fmap = &ifm->u.macho;
337 for (i = 0; i < fmap->num_sections; i++)
339 if (strcmp(fmap->sect[i].section->sectname, sectname) == 0 &&
340 (!segname || strcmp(fmap->sect[i].section->sectname, segname) == 0))
342 ism->fmap = ifm;
343 ism->sidx = i;
344 return TRUE;
347 ifm = fmap->dsym;
350 ism->fmap = NULL;
351 ism->sidx = -1;
352 return FALSE;
355 /******************************************************************
356 * macho_map_section
358 const char* macho_map_section(struct image_section_map* ism)
360 struct macho_file_map* fmap = &ism->fmap->u.macho;
362 assert(ism->fmap->modtype == DMT_MACHO);
363 if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.macho.num_sections)
364 return IMAGE_NO_MAP;
366 return macho_map_range(fmap, fmap->sect[ism->sidx].section->offset, fmap->sect[ism->sidx].section->size,
367 &fmap->sect[ism->sidx].mapped);
370 /******************************************************************
371 * macho_unmap_section
373 void macho_unmap_section(struct image_section_map* ism)
375 struct macho_file_map* fmap = &ism->fmap->u.macho;
377 if (ism->sidx >= 0 && ism->sidx < fmap->num_sections && fmap->sect[ism->sidx].mapped != IMAGE_NO_MAP)
379 macho_unmap_range(&fmap->sect[ism->sidx].mapped, NULL, fmap, fmap->sect[ism->sidx].section->offset,
380 fmap->sect[ism->sidx].section->size);
384 /******************************************************************
385 * macho_get_map_rva
387 DWORD_PTR macho_get_map_rva(const struct image_section_map* ism)
389 if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.macho.num_sections)
390 return 0;
391 return ism->fmap->u.macho.sect[ism->sidx].section->addr - ism->fmap->u.macho.segs_start;
394 /******************************************************************
395 * macho_get_map_size
397 unsigned macho_get_map_size(const struct image_section_map* ism)
399 if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.macho.num_sections)
400 return 0;
401 return ism->fmap->u.macho.sect[ism->sidx].section->size;
404 /******************************************************************
405 * macho_map_load_commands
407 * Maps the load commands from a Mach-O file into memory
409 static const struct load_command* macho_map_load_commands(struct macho_file_map* fmap)
411 if (fmap->load_commands == IMAGE_NO_MAP)
413 fmap->load_commands = (const struct load_command*) macho_map_range(
414 fmap, sizeof(fmap->mach_header), fmap->mach_header.sizeofcmds, NULL);
415 TRACE("Mapped load commands: %p\n", fmap->load_commands);
418 return fmap->load_commands;
421 /******************************************************************
422 * macho_unmap_load_commands
424 * Unmaps the load commands of a Mach-O file from memory
426 static void macho_unmap_load_commands(struct macho_file_map* fmap)
428 if (fmap->load_commands != IMAGE_NO_MAP)
430 TRACE("Unmapping load commands: %p\n", fmap->load_commands);
431 macho_unmap_range(NULL, (const void**)&fmap->load_commands, fmap,
432 sizeof(fmap->mach_header), fmap->mach_header.sizeofcmds);
436 /******************************************************************
437 * macho_next_load_command
439 * Advance to the next load command
441 static const struct load_command* macho_next_load_command(const struct load_command* lc)
443 return (const struct load_command*)((const char*)lc + lc->cmdsize);
446 /******************************************************************
447 * macho_enum_load_commands
449 * Enumerates the load commands for a Mach-O file, selecting by
450 * the command type, calling a callback for each. If the callback
451 * returns <0, that indicates an error. If it returns >0, that means
452 * it's not interested in getting any more load commands.
453 * If this function returns <0, that's an error produced by the
454 * callback. If >=0, that's the count of load commands successfully
455 * processed.
457 static int macho_enum_load_commands(struct macho_file_map* fmap, unsigned cmd,
458 int (*cb)(struct macho_file_map*, const struct load_command*, void*),
459 void* user)
461 const struct load_command* lc;
462 int i;
463 int count = 0;
465 TRACE("(%p/%d, %u, %p, %p)\n", fmap, fmap->fd, cmd, cb, user);
467 if ((lc = macho_map_load_commands(fmap)) == IMAGE_NO_MAP) return -1;
469 TRACE("%d total commands\n", fmap->mach_header.ncmds);
471 for (i = 0; i < fmap->mach_header.ncmds; i++, lc = macho_next_load_command(lc))
473 int result;
475 if (cmd && cmd != lc->cmd) continue;
476 count++;
478 result = cb(fmap, lc, user);
479 TRACE("load_command[%d] (%p), cmd %u; callback => %d\n", i, lc, lc->cmd, result);
480 if (result) return (result < 0) ? result : count;
483 return count;
486 /******************************************************************
487 * macho_count_sections
489 * Callback for macho_enum_load_commands. Counts the number of
490 * significant sections in a Mach-O file. All commands are
491 * expected to be of LC_SEGMENT[_64] type.
493 static int macho_count_sections(struct macho_file_map* fmap, const struct load_command* lc, void* user)
495 const macho_segment_command* sc = (const macho_segment_command*)lc;
497 TRACE("(%p/%d, %p, %p) segment %s\n", fmap, fmap->fd, lc, user, debugstr_an(sc->segname, sizeof(sc->segname)));
499 fmap->num_sections += sc->nsects;
500 return 0;
503 /******************************************************************
504 * macho_load_section_info
506 * Callback for macho_enum_load_commands. Accumulates the address
507 * range covered by the segments of a Mach-O file and builds the
508 * section map. All commands are expected to be of LC_SEGMENT[_64] type.
510 static int macho_load_section_info(struct macho_file_map* fmap, const struct load_command* lc, void* user)
512 const macho_segment_command* sc = (const macho_segment_command*)lc;
513 int* section_index = (int*)user;
514 const macho_section* section;
515 int i;
516 unsigned long tmp, page_mask = sysconf( _SC_PAGESIZE ) - 1;
518 TRACE("(%p/%d, %p, %p) before: 0x%08lx - 0x%08lx\n", fmap, fmap->fd, lc, user,
519 (unsigned long)fmap->segs_start, (unsigned long)fmap->segs_size);
520 TRACE("Segment command vm: 0x%08lx - 0x%08lx\n", (unsigned long)sc->vmaddr,
521 (unsigned long)(sc->vmaddr + sc->vmsize));
523 if (!strncmp(sc->segname, "WINE_", 5))
524 TRACE("Ignoring special Wine segment %s\n", debugstr_an(sc->segname, sizeof(sc->segname)));
525 else if (!strncmp(sc->segname, "__PAGEZERO", 10))
526 TRACE("Ignoring __PAGEZERO segment\n");
527 else
529 /* If this segment starts before previously-known earliest, record new earliest. */
530 if (sc->vmaddr < fmap->segs_start)
531 fmap->segs_start = sc->vmaddr;
533 /* If this segment extends beyond previously-known furthest, record new furthest. */
534 tmp = (sc->vmaddr + sc->vmsize + page_mask) & ~page_mask;
535 if (fmap->segs_size < tmp) fmap->segs_size = tmp;
537 TRACE("after: 0x%08lx - 0x%08lx\n", (unsigned long)fmap->segs_start, (unsigned long)fmap->segs_size);
540 section = (const macho_section*)(sc + 1);
541 for (i = 0; i < sc->nsects; i++)
543 fmap->sect[*section_index].section = &section[i];
544 fmap->sect[*section_index].mapped = IMAGE_NO_MAP;
545 (*section_index)++;
548 return 0;
551 /******************************************************************
552 * find_uuid
554 * Callback for macho_enum_load_commands. Records the UUID load
555 * command of a Mach-O file.
557 static int find_uuid(struct macho_file_map* fmap, const struct load_command* lc, void* user)
559 fmap->uuid = (const struct uuid_command*)lc;
560 return 1;
563 /******************************************************************
564 * reset_file_map
566 static inline void reset_file_map(struct image_file_map* ifm)
568 struct macho_file_map* fmap = &ifm->u.macho;
570 fmap->fd = -1;
571 fmap->dsym = NULL;
572 fmap->load_commands = IMAGE_NO_MAP;
573 fmap->uuid = NULL;
574 fmap->num_sections = 0;
575 fmap->sect = NULL;
578 /******************************************************************
579 * macho_map_file
581 * Maps a Mach-O file into memory (and checks it's a real Mach-O file)
583 static BOOL macho_map_file(const WCHAR* filenameW, struct image_file_map* ifm)
585 struct macho_file_map* fmap = &ifm->u.macho;
586 struct fat_header fat_header;
587 struct stat statbuf;
588 int i;
589 char* filename;
590 unsigned len;
591 BOOL ret = FALSE;
593 TRACE("(%s, %p)\n", debugstr_w(filenameW), fmap);
595 reset_file_map(ifm);
597 ifm->modtype = DMT_MACHO;
598 #ifdef _WIN64
599 ifm->addr_size = 64;
600 #else
601 ifm->addr_size = 32;
602 #endif
604 len = WideCharToMultiByte(CP_UNIXCP, 0, filenameW, -1, NULL, 0, NULL, NULL);
605 if (!(filename = HeapAlloc(GetProcessHeap(), 0, len)))
607 WARN("failed to allocate filename buffer\n");
608 return FALSE;
610 WideCharToMultiByte(CP_UNIXCP, 0, filenameW, -1, filename, len, NULL, NULL);
612 /* check that the file exists */
613 if (stat(filename, &statbuf) == -1 || S_ISDIR(statbuf.st_mode))
615 TRACE("stat() failed or %s is directory: %s\n", debugstr_a(filename), strerror(errno));
616 goto done;
619 /* Now open the file, so that we can mmap() it. */
620 if ((fmap->fd = open(filename, O_RDONLY)) == -1)
622 TRACE("failed to open file %s: %d\n", debugstr_a(filename), errno);
623 goto done;
626 if (read(fmap->fd, &fat_header, sizeof(fat_header)) != sizeof(fat_header))
628 TRACE("failed to read fat header: %d\n", errno);
629 goto done;
631 TRACE("... got possible fat header\n");
633 /* Fat header is always in big-endian order. */
634 if (swap_ulong_be_to_host(fat_header.magic) == FAT_MAGIC)
636 int narch = swap_ulong_be_to_host(fat_header.nfat_arch);
637 for (i = 0; i < narch; i++)
639 struct fat_arch fat_arch;
640 if (read(fmap->fd, &fat_arch, sizeof(fat_arch)) != sizeof(fat_arch))
641 goto done;
642 if (swap_ulong_be_to_host(fat_arch.cputype) == TARGET_CPU_TYPE)
644 fmap->arch_offset = swap_ulong_be_to_host(fat_arch.offset);
645 break;
648 if (i >= narch) goto done;
649 TRACE("... found target arch (%d)\n", TARGET_CPU_TYPE);
651 else
653 fmap->arch_offset = 0;
654 TRACE("... not a fat header\n");
657 /* Individual architecture (standalone or within a fat file) is in its native byte order. */
658 lseek(fmap->fd, fmap->arch_offset, SEEK_SET);
659 if (read(fmap->fd, &fmap->mach_header, sizeof(fmap->mach_header)) != sizeof(fmap->mach_header))
660 goto done;
661 TRACE("... got possible Mach header\n");
662 /* and check for a Mach-O header */
663 if (fmap->mach_header.magic != TARGET_MH_MAGIC ||
664 fmap->mach_header.cputype != TARGET_CPU_TYPE) goto done;
665 /* Make sure the file type is one of the ones we expect. */
666 switch (fmap->mach_header.filetype)
668 case MH_EXECUTE:
669 case MH_DYLIB:
670 case MH_DYLINKER:
671 case MH_BUNDLE:
672 case MH_DSYM:
673 break;
674 default:
675 goto done;
677 TRACE("... verified Mach header\n");
679 fmap->num_sections = 0;
680 if (macho_enum_load_commands(fmap, TARGET_SEGMENT_COMMAND, macho_count_sections, NULL) < 0)
681 goto done;
682 TRACE("%d sections\n", fmap->num_sections);
684 fmap->sect = HeapAlloc(GetProcessHeap(), 0, fmap->num_sections * sizeof(fmap->sect[0]));
685 if (!fmap->sect)
686 goto done;
688 fmap->segs_size = 0;
689 fmap->segs_start = ~0L;
691 i = 0;
692 if (macho_enum_load_commands(fmap, TARGET_SEGMENT_COMMAND, macho_load_section_info, &i) < 0)
694 fmap->num_sections = 0;
695 goto done;
698 fmap->segs_size -= fmap->segs_start;
699 TRACE("segs_start: 0x%08lx, segs_size: 0x%08lx\n", (unsigned long)fmap->segs_start,
700 (unsigned long)fmap->segs_size);
702 if (macho_enum_load_commands(fmap, LC_UUID, find_uuid, NULL) < 0)
703 goto done;
704 if (fmap->uuid)
706 char uuid_string[UUID_STRING_LEN];
707 TRACE("UUID %s\n", format_uuid(fmap->uuid->uuid, uuid_string));
709 else
710 TRACE("no UUID found\n");
712 ret = TRUE;
713 done:
714 if (!ret)
715 macho_unmap_file(ifm);
716 HeapFree(GetProcessHeap(), 0, filename);
717 return ret;
720 /******************************************************************
721 * macho_unmap_file
723 * Unmaps a Mach-O file from memory (previously mapped with macho_map_file)
725 static void macho_unmap_file(struct image_file_map* ifm)
727 struct image_file_map* cursor;
729 TRACE("(%p/%d)\n", ifm, ifm->u.macho.fd);
731 cursor = ifm;
732 while (cursor)
734 struct image_file_map* next;
736 if (ifm->u.macho.fd != -1)
738 struct image_section_map ism;
740 ism.fmap = ifm;
741 for (ism.sidx = 0; ism.sidx < ifm->u.macho.num_sections; ism.sidx++)
742 macho_unmap_section(&ism);
744 HeapFree(GetProcessHeap(), 0, ifm->u.macho.sect);
745 macho_unmap_load_commands(&ifm->u.macho);
746 close(ifm->u.macho.fd);
747 ifm->u.macho.fd = -1;
750 next = cursor->u.macho.dsym;
751 if (cursor != ifm)
752 HeapFree(GetProcessHeap(), 0, cursor);
753 cursor = next;
757 /******************************************************************
758 * macho_sect_is_code
760 * Checks if a section, identified by sectidx which is a 1-based
761 * index into the sections of all segments, in order of load
762 * commands, contains code.
764 static BOOL macho_sect_is_code(struct macho_file_map* fmap, unsigned char sectidx)
766 BOOL ret;
768 TRACE("(%p/%d, %u)\n", fmap, fmap->fd, sectidx);
770 if (!sectidx) return FALSE;
772 sectidx--; /* convert from 1-based to 0-based */
773 if (sectidx >= fmap->num_sections) return FALSE;
775 ret = (!(fmap->sect[sectidx].section->flags & SECTION_TYPE) &&
776 (fmap->sect[sectidx].section->flags & (S_ATTR_PURE_INSTRUCTIONS|S_ATTR_SOME_INSTRUCTIONS)));
777 TRACE("-> %d\n", ret);
778 return ret;
781 struct symtab_elt
783 struct hash_table_elt ht_elt;
784 struct symt_compiland* compiland;
785 unsigned long addr;
786 unsigned char is_code:1,
787 is_public:1,
788 is_global:1,
789 used:1;
792 struct macho_debug_info
794 struct macho_file_map* fmap;
795 struct module* module;
796 struct pool pool;
797 struct hash_table ht_symtab;
800 /******************************************************************
801 * macho_stabs_def_cb
803 * Callback for stabs_parse. Collect symbol definitions.
805 static void macho_stabs_def_cb(struct module* module, unsigned long load_offset,
806 const char* name, unsigned long offset,
807 BOOL is_public, BOOL is_global, unsigned char sectidx,
808 struct symt_compiland* compiland, void* user)
810 struct macho_debug_info* mdi = user;
811 struct symtab_elt* ste;
813 TRACE("(%p, 0x%08lx, %s, 0x%08lx, %d, %d, %u, %p, %p/%p/%d)\n", module, load_offset,
814 debugstr_a(name), offset, is_public, is_global, sectidx,
815 compiland, mdi, mdi->fmap, mdi->fmap->fd);
817 /* Defer the creation of new non-debugging symbols until after we've
818 * finished parsing the stabs. */
819 ste = pool_alloc(&mdi->pool, sizeof(*ste));
820 ste->ht_elt.name = pool_strdup(&mdi->pool, name);
821 ste->compiland = compiland;
822 ste->addr = load_offset + offset;
823 ste->is_code = !!macho_sect_is_code(mdi->fmap, sectidx);
824 ste->is_public = !!is_public;
825 ste->is_global = !!is_global;
826 ste->used = 0;
827 hash_table_add(&mdi->ht_symtab, &ste->ht_elt);
830 /******************************************************************
831 * macho_parse_symtab
833 * Callback for macho_enum_load_commands. Processes the LC_SYMTAB
834 * load commands from the Mach-O file.
836 static int macho_parse_symtab(struct macho_file_map* fmap,
837 const struct load_command* lc, void* user)
839 const struct symtab_command* sc = (const struct symtab_command*)lc;
840 struct macho_debug_info* mdi = user;
841 const macho_nlist* stab;
842 const char* stabstr;
843 int ret = 0;
845 TRACE("(%p/%d, %p, %p) %u syms at 0x%08x, strings 0x%08x - 0x%08x\n", fmap, fmap->fd, lc,
846 user, sc->nsyms, sc->symoff, sc->stroff, sc->stroff + sc->strsize);
848 if (!macho_map_ranges(fmap, sc->symoff, sc->nsyms * sizeof(macho_nlist),
849 sc->stroff, sc->strsize, (const void**)&stab, (const void**)&stabstr))
850 return 0;
852 if (!stabs_parse(mdi->module,
853 mdi->module->format_info[DFI_MACHO]->u.macho_info->load_addr - fmap->segs_start,
854 stab, sc->nsyms * sizeof(macho_nlist),
855 stabstr, sc->strsize, macho_stabs_def_cb, mdi))
856 ret = -1;
858 macho_unmap_ranges(fmap, sc->symoff, sc->nsyms * sizeof(macho_nlist),
859 sc->stroff, sc->strsize, (const void**)&stab, (const void**)&stabstr);
861 return ret;
864 /******************************************************************
865 * macho_finish_stabs
867 * Integrate the non-debugging symbols we've gathered into the
868 * symbols that were generated during stabs parsing.
870 static void macho_finish_stabs(struct module* module, struct hash_table* ht_symtab)
872 struct hash_table_iter hti_ours;
873 struct symtab_elt* ste;
874 BOOL adjusted = FALSE;
876 TRACE("(%p, %p)\n", module, ht_symtab);
878 /* For each of our non-debugging symbols, see if it can provide some
879 * missing details to one of the module's known symbols. */
880 hash_table_iter_init(ht_symtab, &hti_ours, NULL);
881 while ((ste = hash_table_iter_up(&hti_ours)))
883 struct hash_table_iter hti_modules;
884 void* ptr;
885 struct symt_ht* sym;
886 struct symt_function* func;
887 struct symt_data* data;
889 hash_table_iter_init(&module->ht_symbols, &hti_modules, ste->ht_elt.name);
890 while ((ptr = hash_table_iter_up(&hti_modules)))
892 sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
894 if (strcmp(sym->hash_elt.name, ste->ht_elt.name))
895 continue;
897 switch (sym->symt.tag)
899 case SymTagFunction:
900 func = (struct symt_function*)sym;
901 if (func->address == module->format_info[DFI_MACHO]->u.macho_info->load_addr)
903 TRACE("Adjusting function %p/%s!%s from 0x%08lx to 0x%08lx\n", func,
904 debugstr_w(module->module.ModuleName), sym->hash_elt.name,
905 func->address, ste->addr);
906 func->address = ste->addr;
907 adjusted = TRUE;
909 if (func->address == ste->addr)
910 ste->used = 1;
911 break;
912 case SymTagData:
913 data = (struct symt_data*)sym;
914 switch (data->kind)
916 case DataIsGlobal:
917 case DataIsFileStatic:
918 if (data->u.var.offset == module->format_info[DFI_MACHO]->u.macho_info->load_addr)
920 TRACE("Adjusting data symbol %p/%s!%s from 0x%08lx to 0x%08lx\n",
921 data, debugstr_w(module->module.ModuleName), sym->hash_elt.name,
922 data->u.var.offset, ste->addr);
923 data->u.var.offset = ste->addr;
924 adjusted = TRUE;
926 if (data->u.var.offset == ste->addr)
928 enum DataKind new_kind;
930 new_kind = ste->is_global ? DataIsGlobal : DataIsFileStatic;
931 if (data->kind != new_kind)
933 WARN("Changing kind for %p/%s!%s from %d to %d\n", sym,
934 debugstr_w(module->module.ModuleName), sym->hash_elt.name,
935 (int)data->kind, (int)new_kind);
936 data->kind = new_kind;
937 adjusted = TRUE;
939 ste->used = 1;
941 break;
942 default:;
944 break;
945 default:
946 TRACE("Ignoring tag %u\n", sym->symt.tag);
947 break;
952 if (adjusted)
954 /* since we may have changed some addresses, mark the module to be resorted */
955 module->sortlist_valid = FALSE;
958 /* Mark any of our non-debugging symbols which fall on an already-used
959 * address as "used". This allows us to skip them in the next loop,
960 * below. We do this in separate loops because symt_new_* marks the
961 * list as needing sorting and symt_find_nearest sorts if needed,
962 * causing thrashing. */
963 if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
965 hash_table_iter_init(ht_symtab, &hti_ours, NULL);
966 while ((ste = hash_table_iter_up(&hti_ours)))
968 struct symt_ht* sym;
969 ULONG64 addr;
971 if (ste->used) continue;
973 sym = symt_find_nearest(module, ste->addr);
974 if (sym)
975 symt_get_address(&sym->symt, &addr);
976 if (sym && ste->addr == addr)
978 ULONG64 size = 0;
979 DWORD kind = -1;
981 ste->used = 1;
983 /* If neither symbol has a correct size (ours never does), we
984 * consider them both to be markers. No warning is needed in
985 * that case.
986 * Also, we check that we don't have two symbols, one local, the other
987 * global, which is legal.
989 symt_get_info(module, &sym->symt, TI_GET_LENGTH, &size);
990 symt_get_info(module, &sym->symt, TI_GET_DATAKIND, &kind);
991 if (size && kind == (ste->is_global ? DataIsGlobal : DataIsFileStatic))
992 FIXME("Duplicate in %s: %s<%08lx> %s<%s-%s>\n",
993 debugstr_w(module->module.ModuleName),
994 ste->ht_elt.name, ste->addr,
995 sym->hash_elt.name,
996 wine_dbgstr_longlong(addr), wine_dbgstr_longlong(size));
1001 /* For any of our remaining non-debugging symbols which have no match
1002 * among the module's known symbols, add them as new symbols. */
1003 hash_table_iter_init(ht_symtab, &hti_ours, NULL);
1004 while ((ste = hash_table_iter_up(&hti_ours)))
1006 if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY) && !ste->used)
1008 if (ste->is_code)
1010 symt_new_function(module, ste->compiland, ste->ht_elt.name,
1011 ste->addr, 0, NULL);
1013 else
1015 struct location loc;
1017 loc.kind = loc_absolute;
1018 loc.reg = 0;
1019 loc.offset = ste->addr;
1020 symt_new_global_variable(module, ste->compiland, ste->ht_elt.name,
1021 !ste->is_global, loc, 0, NULL);
1024 ste->used = 1;
1027 if (ste->is_public && !(dbghelp_options & SYMOPT_NO_PUBLICS))
1029 symt_new_public(module, ste->compiland, ste->ht_elt.name, ste->addr, 0);
1034 /******************************************************************
1035 * try_dsym
1037 * Try to load a debug symbol file from the given path and check
1038 * if its UUID matches the UUID of an already-mapped file. If so,
1039 * stash the file map in the "dsym" field of the file and return
1040 * TRUE. If it can't be mapped or its UUID doesn't match, return
1041 * FALSE.
1043 static BOOL try_dsym(const WCHAR* path, struct macho_file_map* fmap)
1045 struct image_file_map dsym_ifm;
1047 if (macho_map_file(path, &dsym_ifm))
1049 char uuid_string[UUID_STRING_LEN];
1051 if (dsym_ifm.u.macho.uuid && !memcmp(dsym_ifm.u.macho.uuid->uuid, fmap->uuid->uuid, sizeof(fmap->uuid->uuid)))
1053 TRACE("found matching debug symbol file at %s\n", debugstr_w(path));
1054 fmap->dsym = HeapAlloc(GetProcessHeap(), 0, sizeof(dsym_ifm));
1055 *fmap->dsym = dsym_ifm;
1056 return TRUE;
1059 TRACE("candidate debug symbol file at %s has wrong UUID %s; ignoring\n", debugstr_w(path),
1060 format_uuid(dsym_ifm.u.macho.uuid->uuid, uuid_string));
1062 macho_unmap_file(&dsym_ifm);
1064 else
1065 TRACE("couldn't map file at %s\n", debugstr_w(path));
1067 return FALSE;
1070 /******************************************************************
1071 * find_and_map_dsym
1073 * Search for a debugging symbols file associated with a module and
1074 * map it. First look for a .dSYM bundle next to the module file
1075 * (e.g. <path>.dSYM/Contents/Resources/DWARF/<basename of path>)
1076 * as produced by dsymutil. Next, look for a .dwarf file next to
1077 * the module file (e.g. <path>.dwarf) as produced by
1078 * "dsymutil --flat". Finally, use Spotlight to search for a
1079 * .dSYM bundle with the same UUID as the module file.
1081 static void find_and_map_dsym(struct module* module)
1083 static const WCHAR dot_dsym[] = {'.','d','S','Y','M',0};
1084 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};
1085 static const WCHAR dot_dwarf[] = {'.','d','w','a','r','f',0};
1086 struct macho_file_map* fmap = &module->format_info[DFI_MACHO]->u.macho_info->file_map.u.macho;
1087 const WCHAR* p;
1088 size_t len;
1089 WCHAR* path = NULL;
1090 char uuid_string[UUID_STRING_LEN];
1091 CFStringRef uuid_cfstring;
1092 CFStringRef query_string;
1093 MDQueryRef query = NULL;
1095 /* Without a UUID, we can't verify that any debug info file we find corresponds
1096 to this file. Better to have no debug info than incorrect debug info. */
1097 if (!fmap->uuid)
1098 return;
1100 if ((p = strrchrW(module->module.LoadedImageName, '/')))
1101 p++;
1102 else
1103 p = module->module.LoadedImageName;
1104 len = strlenW(module->module.LoadedImageName) + strlenW(dot_dsym) + strlenW(dsym_subpath) + strlenW(p) + 1;
1105 path = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1106 if (!path)
1107 return;
1108 strcpyW(path, module->module.LoadedImageName);
1109 strcatW(path, dot_dsym);
1110 strcatW(path, dsym_subpath);
1111 strcatW(path, p);
1113 if (try_dsym(path, fmap))
1114 goto found;
1116 strcpyW(path + strlenW(module->module.LoadedImageName), dot_dwarf);
1118 if (try_dsym(path, fmap))
1119 goto found;
1121 format_uuid(fmap->uuid->uuid, uuid_string);
1122 uuid_cfstring = CFStringCreateWithCString(NULL, uuid_string, kCFStringEncodingASCII);
1123 query_string = CFStringCreateWithFormat(NULL, NULL, CFSTR("com_apple_xcode_dsym_uuids == \"%@\""), uuid_cfstring);
1124 CFRelease(uuid_cfstring);
1125 query = MDQueryCreate(NULL, query_string, NULL, NULL);
1126 CFRelease(query_string);
1127 MDQuerySetMaxCount(query, 1);
1128 if (MDQueryExecute(query, kMDQuerySynchronous) && MDQueryGetResultCount(query) >= 1)
1130 MDItemRef item = (MDItemRef)MDQueryGetResultAtIndex(query, 0);
1131 CFStringRef item_path = MDItemCopyAttribute(item, kMDItemPath);
1132 if (item_path)
1134 CFIndex item_path_len = CFStringGetLength(item_path);
1135 if (item_path_len + strlenW(dsym_subpath) + strlenW(p) >= len)
1137 HeapFree(GetProcessHeap(), 0, path);
1138 len = item_path_len + strlenW(dsym_subpath) + strlenW(p) + 1;
1139 path = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1141 CFStringGetCharacters(item_path, CFRangeMake(0, item_path_len), (UniChar*)path);
1142 strcpyW(path + item_path_len, dsym_subpath);
1143 strcatW(path, p);
1144 CFRelease(item_path);
1146 if (try_dsym(path, fmap))
1147 goto found;
1151 found:
1152 HeapFree(GetProcessHeap(), 0, path);
1153 if (query) CFRelease(query);
1156 /******************************************************************
1157 * macho_load_debug_info
1159 * Loads Mach-O debugging information from the module image file.
1161 BOOL macho_load_debug_info(struct module* module)
1163 BOOL ret = FALSE;
1164 struct macho_debug_info mdi;
1165 int result;
1166 struct macho_file_map *fmap;
1168 if (module->type != DMT_MACHO || !module->format_info[DFI_MACHO]->u.macho_info)
1170 ERR("Bad Mach-O module '%s'\n", debugstr_w(module->module.LoadedImageName));
1171 return FALSE;
1174 fmap = &module->format_info[DFI_MACHO]->u.macho_info->file_map.u.macho;
1176 TRACE("(%p, %p/%d)\n", module, fmap, fmap->fd);
1178 module->module.SymType = SymExport;
1180 if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
1182 find_and_map_dsym(module);
1184 if (dwarf2_parse(module, module->reloc_delta, NULL /* FIXME: some thunks to deal with ? */,
1185 &module->format_info[DFI_MACHO]->u.macho_info->file_map))
1186 ret = TRUE;
1189 mdi.fmap = fmap;
1190 mdi.module = module;
1191 pool_init(&mdi.pool, 65536);
1192 hash_table_init(&mdi.pool, &mdi.ht_symtab, 256);
1193 result = macho_enum_load_commands(fmap, LC_SYMTAB, macho_parse_symtab, &mdi);
1194 if (result > 0)
1195 ret = TRUE;
1196 else if (result < 0)
1197 WARN("Couldn't correctly read stabs\n");
1199 if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY) && fmap->dsym)
1201 mdi.fmap = &fmap->dsym->u.macho;
1202 result = macho_enum_load_commands(mdi.fmap, LC_SYMTAB, macho_parse_symtab, &mdi);
1203 if (result > 0)
1204 ret = TRUE;
1205 else if (result < 0)
1206 WARN("Couldn't correctly read stabs\n");
1209 macho_finish_stabs(module, &mdi.ht_symtab);
1211 pool_destroy(&mdi.pool);
1212 return ret;
1215 /******************************************************************
1216 * macho_fetch_file_info
1218 * Gathers some more information for a Mach-O module from a given file
1220 BOOL macho_fetch_file_info(const WCHAR* name, DWORD_PTR* base,
1221 DWORD* size, DWORD* checksum)
1223 struct image_file_map fmap;
1225 TRACE("(%s, %p, %p, %p)\n", debugstr_w(name), base, size, checksum);
1227 if (!macho_map_file(name, &fmap)) return FALSE;
1228 if (base) *base = fmap.u.macho.segs_start;
1229 *size = fmap.u.macho.segs_size;
1230 *checksum = calc_crc32(fmap.u.macho.fd);
1231 macho_unmap_file(&fmap);
1232 return TRUE;
1235 /******************************************************************
1236 * macho_module_remove
1238 static void macho_module_remove(struct process* pcs, struct module_format* modfmt)
1240 macho_unmap_file(&modfmt->u.macho_info->file_map);
1241 HeapFree(GetProcessHeap(), 0, modfmt);
1244 /******************************************************************
1245 * macho_load_file
1247 * Loads the information for Mach-O module stored in 'filename'.
1248 * The module has been loaded at 'load_addr' address.
1249 * returns
1250 * FALSE if the file cannot be found/opened or if the file doesn't
1251 * contain symbolic info (or this info cannot be read or parsed)
1252 * TRUE on success
1254 static BOOL macho_load_file(struct process* pcs, const WCHAR* filename,
1255 unsigned long load_addr, struct macho_info* macho_info)
1257 BOOL ret = TRUE;
1258 struct image_file_map fmap;
1260 TRACE("(%p/%p, %s, 0x%08lx, %p/0x%08x)\n", pcs, pcs->handle, debugstr_w(filename),
1261 load_addr, macho_info, macho_info->flags);
1263 if (!macho_map_file(filename, &fmap)) return FALSE;
1265 /* Find the dynamic loader's table of images loaded into the process.
1267 if (macho_info->flags & MACHO_INFO_DEBUG_HEADER)
1269 PROCESS_BASIC_INFORMATION pbi;
1270 NTSTATUS status;
1272 ret = FALSE;
1274 /* Get address of PEB */
1275 status = NtQueryInformationProcess(pcs->handle, ProcessBasicInformation,
1276 &pbi, sizeof(pbi), NULL);
1277 if (status == STATUS_SUCCESS)
1279 ULONG_PTR dyld_image_info;
1281 /* Read dyld image info address from PEB */
1282 if (ReadProcessMemory(pcs->handle, &pbi.PebBaseAddress->Reserved[0],
1283 &dyld_image_info, sizeof(dyld_image_info), NULL))
1285 TRACE("got dyld_image_info 0x%08lx from PEB %p MacDyldImageInfo %p\n",
1286 (unsigned long)dyld_image_info, pbi.PebBaseAddress, &pbi.PebBaseAddress->Reserved);
1287 macho_info->dbg_hdr_addr = dyld_image_info;
1288 ret = TRUE;
1292 #ifndef __LP64__ /* No reading the symtab with nlist(3) in LP64 */
1293 if (!ret)
1295 static void* dyld_all_image_infos_addr;
1297 /* Our next best guess is that dyld was loaded at its base address
1298 and we can find the dyld image infos address by looking up its symbol. */
1299 if (!dyld_all_image_infos_addr)
1301 struct nlist nl[2];
1302 memset(nl, 0, sizeof(nl));
1303 nl[0].n_un.n_name = (char*)"_dyld_all_image_infos";
1304 if (!nlist("/usr/lib/dyld", nl))
1305 dyld_all_image_infos_addr = (void*)nl[0].n_value;
1308 if (dyld_all_image_infos_addr)
1310 TRACE("got dyld_image_info %p from /usr/lib/dyld symbol table\n",
1311 dyld_all_image_infos_addr);
1312 macho_info->dbg_hdr_addr = (unsigned long)dyld_all_image_infos_addr;
1313 ret = TRUE;
1316 #endif
1319 if (macho_info->flags & MACHO_INFO_MODULE)
1321 struct macho_module_info *macho_module_info;
1322 struct module_format* modfmt =
1323 HeapAlloc(GetProcessHeap(), 0, sizeof(struct module_format) + sizeof(struct macho_module_info));
1324 if (!modfmt) goto leave;
1325 if (!load_addr)
1326 load_addr = fmap.u.macho.segs_start;
1327 macho_info->module = module_new(pcs, filename, DMT_MACHO, FALSE, load_addr,
1328 fmap.u.macho.segs_size, 0, calc_crc32(fmap.u.macho.fd));
1329 if (!macho_info->module)
1331 HeapFree(GetProcessHeap(), 0, modfmt);
1332 goto leave;
1334 macho_info->module->reloc_delta = macho_info->module->module.BaseOfImage - fmap.u.macho.segs_start;
1335 macho_module_info = (void*)(modfmt + 1);
1336 macho_info->module->format_info[DFI_MACHO] = modfmt;
1338 modfmt->module = macho_info->module;
1339 modfmt->remove = macho_module_remove;
1340 modfmt->loc_compute = NULL;
1341 modfmt->u.macho_info = macho_module_info;
1343 macho_module_info->load_addr = load_addr;
1345 macho_module_info->file_map = fmap;
1346 reset_file_map(&fmap);
1347 if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
1348 macho_info->module->module.SymType = SymDeferred;
1349 else if (!macho_load_debug_info(macho_info->module))
1350 ret = FALSE;
1352 macho_info->module->format_info[DFI_MACHO]->u.macho_info->in_use = 1;
1353 macho_info->module->format_info[DFI_MACHO]->u.macho_info->is_loader = 0;
1354 TRACE("module = %p\n", macho_info->module);
1357 if (macho_info->flags & MACHO_INFO_NAME)
1359 WCHAR* ptr;
1360 ptr = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(filename) + 1) * sizeof(WCHAR));
1361 if (ptr)
1363 strcpyW(ptr, filename);
1364 macho_info->module_name = ptr;
1366 else ret = FALSE;
1367 TRACE("module_name = %p %s\n", macho_info->module_name, debugstr_w(macho_info->module_name));
1369 leave:
1370 macho_unmap_file(&fmap);
1372 TRACE(" => %d\n", ret);
1373 return ret;
1376 /******************************************************************
1377 * macho_load_file_from_path
1378 * Tries to load a Mach-O file from a set of paths (separated by ':')
1380 static BOOL macho_load_file_from_path(struct process* pcs,
1381 const WCHAR* filename,
1382 unsigned long load_addr,
1383 const char* path,
1384 struct macho_info* macho_info)
1386 BOOL ret = FALSE;
1387 WCHAR *s, *t, *fn;
1388 WCHAR* pathW = NULL;
1389 unsigned len;
1391 TRACE("(%p/%p, %s, 0x%08lx, %s, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
1392 debugstr_a(path), macho_info);
1394 if (!path) return FALSE;
1396 len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
1397 pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1398 if (!pathW) return FALSE;
1399 MultiByteToWideChar(CP_UNIXCP, 0, path, -1, pathW, len);
1401 for (s = pathW; s && *s; s = (t) ? (t+1) : NULL)
1403 t = strchrW(s, ':');
1404 if (t) *t = '\0';
1405 fn = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(filename) + 1 + lstrlenW(s) + 1) * sizeof(WCHAR));
1406 if (!fn) break;
1407 strcpyW(fn, s);
1408 strcatW(fn, S_SlashW);
1409 strcatW(fn, filename);
1410 ret = macho_load_file(pcs, fn, load_addr, macho_info);
1411 HeapFree(GetProcessHeap(), 0, fn);
1412 if (ret) break;
1413 s = (t) ? (t+1) : NULL;
1416 TRACE(" => %d\n", ret);
1417 HeapFree(GetProcessHeap(), 0, pathW);
1418 return ret;
1421 /******************************************************************
1422 * macho_load_file_from_dll_path
1424 * Tries to load a Mach-O file from the dll path
1426 static BOOL macho_load_file_from_dll_path(struct process* pcs,
1427 const WCHAR* filename,
1428 unsigned long load_addr,
1429 struct macho_info* macho_info)
1431 BOOL ret = FALSE;
1432 unsigned int index = 0;
1433 const char *path;
1435 TRACE("(%p/%p, %s, 0x%08lx, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
1436 macho_info);
1438 while (!ret && (path = wine_dll_enum_load_path( index++ )))
1440 WCHAR *name;
1441 unsigned len;
1443 len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
1445 name = HeapAlloc( GetProcessHeap(), 0,
1446 (len + lstrlenW(filename) + 2) * sizeof(WCHAR) );
1448 if (!name) break;
1449 MultiByteToWideChar(CP_UNIXCP, 0, path, -1, name, len);
1450 strcatW( name, S_SlashW );
1451 strcatW( name, filename );
1452 ret = macho_load_file(pcs, name, load_addr, macho_info);
1453 HeapFree( GetProcessHeap(), 0, name );
1455 TRACE(" => %d\n", ret);
1456 return ret;
1459 /******************************************************************
1460 * macho_search_and_load_file
1462 * Lookup a file in standard Mach-O locations, and if found, load it
1464 static BOOL macho_search_and_load_file(struct process* pcs, const WCHAR* filename,
1465 unsigned long load_addr,
1466 struct macho_info* macho_info)
1468 BOOL ret = FALSE;
1469 struct module* module;
1470 static const WCHAR S_libstdcPPW[] = {'l','i','b','s','t','d','c','+','+','\0'};
1471 const WCHAR* p;
1473 TRACE("(%p/%p, %s, 0x%08lx, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
1474 macho_info);
1476 if (filename == NULL || *filename == '\0') return FALSE;
1477 if ((module = module_is_already_loaded(pcs, filename)))
1479 macho_info->module = module;
1480 module->format_info[DFI_MACHO]->u.macho_info->in_use = 1;
1481 return module->module.SymType;
1484 if (strstrW(filename, S_libstdcPPW)) return FALSE; /* We know we can't do it */
1486 /* If has no directories, try LD_LIBRARY_PATH first. */
1487 if (!strchrW(filename, '/'))
1489 ret = macho_load_file_from_path(pcs, filename, load_addr,
1490 getenv("PATH"), macho_info);
1492 /* Try DYLD_LIBRARY_PATH, with just the filename (no directories). */
1493 if (!ret)
1495 if ((p = strrchrW(filename, '/'))) p++;
1496 else p = filename;
1497 ret = macho_load_file_from_path(pcs, p, load_addr,
1498 getenv("DYLD_LIBRARY_PATH"), macho_info);
1500 /* Try the path as given. */
1501 if (!ret)
1502 ret = macho_load_file(pcs, filename, load_addr, macho_info);
1503 /* Try DYLD_FALLBACK_LIBRARY_PATH, with just the filename (no directories). */
1504 if (!ret)
1506 ret = macho_load_file_from_path(pcs, p, load_addr,
1507 getenv("DYLD_FALLBACK_LIBRARY_PATH"), macho_info);
1509 if (!ret && !strchrW(filename, '/'))
1510 ret = macho_load_file_from_dll_path(pcs, filename, load_addr, macho_info);
1512 return ret;
1515 /******************************************************************
1516 * macho_enum_modules_internal
1518 * Enumerate Mach-O modules from a running process
1520 static BOOL macho_enum_modules_internal(const struct process* pcs,
1521 const WCHAR* main_name,
1522 enum_modules_cb cb, void* user)
1524 struct dyld_all_image_infos image_infos;
1525 struct dyld_image_info* info_array = NULL;
1526 unsigned long len;
1527 int i;
1528 char bufstr[256];
1529 WCHAR bufstrW[MAX_PATH];
1530 BOOL ret = FALSE;
1532 TRACE("(%p/%p, %s, %p, %p)\n", pcs, pcs->handle, debugstr_w(main_name), cb,
1533 user);
1535 if (!pcs->dbg_hdr_addr ||
1536 !ReadProcessMemory(pcs->handle, (void*)pcs->dbg_hdr_addr,
1537 &image_infos, sizeof(image_infos), NULL) ||
1538 !image_infos.infoArray)
1539 goto done;
1540 TRACE("Process has %u image infos at %p\n", image_infos.infoArrayCount, image_infos.infoArray);
1542 len = image_infos.infoArrayCount * sizeof(info_array[0]);
1543 info_array = HeapAlloc(GetProcessHeap(), 0, len);
1544 if (!info_array ||
1545 !ReadProcessMemory(pcs->handle, image_infos.infoArray,
1546 info_array, len, NULL))
1547 goto done;
1548 TRACE("... read image infos\n");
1550 for (i = 0; i < image_infos.infoArrayCount; i++)
1552 if (info_array[i].imageFilePath != NULL &&
1553 ReadProcessMemory(pcs->handle, info_array[i].imageFilePath, bufstr, sizeof(bufstr), NULL))
1555 bufstr[sizeof(bufstr) - 1] = '\0';
1556 TRACE("[%d] image file %s\n", i, debugstr_a(bufstr));
1557 MultiByteToWideChar(CP_UNIXCP, 0, bufstr, -1, bufstrW, sizeof(bufstrW) / sizeof(WCHAR));
1558 if (main_name && !bufstrW[0]) strcpyW(bufstrW, main_name);
1559 if (!cb(bufstrW, (unsigned long)info_array[i].imageLoadAddress, user)) break;
1563 ret = TRUE;
1564 done:
1565 HeapFree(GetProcessHeap(), 0, info_array);
1566 return ret;
1569 struct macho_sync
1571 struct process* pcs;
1572 struct macho_info macho_info;
1575 static BOOL macho_enum_sync_cb(const WCHAR* name, unsigned long addr, void* user)
1577 struct macho_sync* ms = user;
1579 TRACE("(%s, 0x%08lx, %p)\n", debugstr_w(name), addr, user);
1580 macho_search_and_load_file(ms->pcs, name, addr, &ms->macho_info);
1581 return TRUE;
1584 /******************************************************************
1585 * macho_synchronize_module_list
1587 * Rescans the debuggee's modules list and synchronizes it with
1588 * the one from 'pcs', ie:
1589 * - if a module is in debuggee and not in pcs, it's loaded into pcs
1590 * - if a module is in pcs and not in debuggee, it's unloaded from pcs
1592 BOOL macho_synchronize_module_list(struct process* pcs)
1594 struct module* module;
1595 struct macho_sync ms;
1597 TRACE("(%p/%p)\n", pcs, pcs->handle);
1599 for (module = pcs->lmodules; module; module = module->next)
1601 if (module->type == DMT_MACHO && !module->is_virtual)
1602 module->format_info[DFI_MACHO]->u.macho_info->in_use = 0;
1605 ms.pcs = pcs;
1606 ms.macho_info.flags = MACHO_INFO_MODULE;
1607 if (!macho_enum_modules_internal(pcs, NULL, macho_enum_sync_cb, &ms))
1608 return FALSE;
1610 module = pcs->lmodules;
1611 while (module)
1613 if (module->type == DMT_MACHO && !module->is_virtual &&
1614 !module->format_info[DFI_MACHO]->u.macho_info->in_use &&
1615 !module->format_info[DFI_MACHO]->u.macho_info->is_loader)
1617 module_remove(pcs, module);
1618 /* restart all over */
1619 module = pcs->lmodules;
1621 else module = module->next;
1623 return TRUE;
1626 /******************************************************************
1627 * macho_search_loader
1629 * Lookup in a running Mach-O process the loader, and sets its Mach-O link
1630 * address (for accessing the list of loaded images) in pcs.
1631 * If flags is MACHO_INFO_MODULE, the module for the loader is also
1632 * added as a module into pcs.
1634 static BOOL macho_search_loader(struct process* pcs, struct macho_info* macho_info)
1636 return macho_search_and_load_file(pcs, get_wine_loader_name(), 0, macho_info);
1639 /******************************************************************
1640 * macho_read_wine_loader_dbg_info
1642 * Try to find a decent wine executable which could have loaded the debuggee
1644 BOOL macho_read_wine_loader_dbg_info(struct process* pcs)
1646 struct macho_info macho_info;
1648 TRACE("(%p/%p)\n", pcs, pcs->handle);
1649 macho_info.flags = MACHO_INFO_DEBUG_HEADER | MACHO_INFO_MODULE;
1650 if (!macho_search_loader(pcs, &macho_info)) return FALSE;
1651 macho_info.module->format_info[DFI_MACHO]->u.macho_info->is_loader = 1;
1652 module_set_module(macho_info.module, S_WineLoaderW);
1653 return (pcs->dbg_hdr_addr = macho_info.dbg_hdr_addr) != 0;
1656 /******************************************************************
1657 * macho_enum_modules
1659 * Enumerates the Mach-O loaded modules from a running target (hProc)
1660 * This function doesn't require that someone has called SymInitialize
1661 * on this very process.
1663 BOOL macho_enum_modules(HANDLE hProc, enum_modules_cb cb, void* user)
1665 struct process pcs;
1666 struct macho_info macho_info;
1667 BOOL ret;
1669 TRACE("(%p, %p, %p)\n", hProc, cb, user);
1670 memset(&pcs, 0, sizeof(pcs));
1671 pcs.handle = hProc;
1672 macho_info.flags = MACHO_INFO_DEBUG_HEADER | MACHO_INFO_NAME;
1673 if (!macho_search_loader(&pcs, &macho_info)) return FALSE;
1674 pcs.dbg_hdr_addr = macho_info.dbg_hdr_addr;
1675 ret = macho_enum_modules_internal(&pcs, macho_info.module_name, cb, user);
1676 HeapFree(GetProcessHeap(), 0, (char*)macho_info.module_name);
1677 return ret;
1680 struct macho_load
1682 struct process* pcs;
1683 struct macho_info macho_info;
1684 const WCHAR* name;
1685 BOOL ret;
1688 /******************************************************************
1689 * macho_load_cb
1691 * Callback for macho_load_module, used to walk the list of loaded
1692 * modules.
1694 static BOOL macho_load_cb(const WCHAR* name, unsigned long addr, void* user)
1696 struct macho_load* ml = user;
1697 const WCHAR* p;
1699 TRACE("(%s, 0x%08lx, %p)\n", debugstr_w(name), addr, user);
1701 /* memcmp is needed for matches when bufstr contains also version information
1702 * ml->name: libc.so, name: libc.so.6.0
1704 p = strrchrW(name, '/');
1705 if (!p++) p = name;
1706 if (!memcmp(p, ml->name, lstrlenW(ml->name) * sizeof(WCHAR)))
1708 ml->ret = macho_search_and_load_file(ml->pcs, name, addr, &ml->macho_info);
1709 return FALSE;
1711 return TRUE;
1714 /******************************************************************
1715 * macho_load_module
1717 * Loads a Mach-O module and stores it in process' module list.
1718 * Also, find module real name and load address from
1719 * the real loaded modules list in pcs address space.
1721 struct module* macho_load_module(struct process* pcs, const WCHAR* name, unsigned long addr)
1723 struct macho_load ml;
1725 TRACE("(%p/%p, %s, 0x%08lx)\n", pcs, pcs->handle, debugstr_w(name), addr);
1727 ml.macho_info.flags = MACHO_INFO_MODULE;
1728 ml.ret = FALSE;
1730 if (pcs->dbg_hdr_addr) /* we're debugging a live target */
1732 ml.pcs = pcs;
1733 /* do only the lookup from the filename, not the path (as we lookup module
1734 * name in the process' loaded module list)
1736 ml.name = strrchrW(name, '/');
1737 if (!ml.name++) ml.name = name;
1738 ml.ret = FALSE;
1740 if (!macho_enum_modules_internal(pcs, NULL, macho_load_cb, &ml))
1741 return NULL;
1743 else if (addr)
1745 ml.name = name;
1746 ml.ret = macho_search_and_load_file(pcs, ml.name, addr, &ml.macho_info);
1748 if (!ml.ret) return NULL;
1749 assert(ml.macho_info.module);
1750 return ml.macho_info.module;
1753 #else /* HAVE_MACH_O_LOADER_H */
1755 BOOL macho_find_section(struct image_file_map* ifm, const char* segname, const char* sectname, struct image_section_map* ism)
1757 return FALSE;
1760 const char* macho_map_section(struct image_section_map* ism)
1762 return NULL;
1765 void macho_unmap_section(struct image_section_map* ism)
1769 DWORD_PTR macho_get_map_rva(const struct image_section_map* ism)
1771 return 0;
1774 unsigned macho_get_map_size(const struct image_section_map* ism)
1776 return 0;
1779 BOOL macho_synchronize_module_list(struct process* pcs)
1781 return FALSE;
1784 BOOL macho_fetch_file_info(const WCHAR* name, DWORD_PTR* base,
1785 DWORD* size, DWORD* checksum)
1787 return FALSE;
1790 BOOL macho_read_wine_loader_dbg_info(struct process* pcs)
1792 return FALSE;
1795 BOOL macho_enum_modules(HANDLE hProc, enum_modules_cb cb, void* user)
1797 return FALSE;
1800 struct module* macho_load_module(struct process* pcs, const WCHAR* name, unsigned long addr)
1802 return NULL;
1805 BOOL macho_load_debug_info(struct module* module)
1807 return FALSE;
1809 #endif /* HAVE_MACH_O_LOADER_H */