macho_module.c 68.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * File macho_module.c - processing of Mach-O files
 *      Originally based on elf_module.c
 *
 * Copyright (C) 1996, Eric Youngdale.
 *               1999-2007 Eric Pouech
 *               2009 Ken Thomases, CodeWeavers Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "config.h"
#include "wine/port.h"

27 28 29 30 31 32 33 34 35 36 37
#ifdef HAVE_MACH_O_LOADER_H
#include <CoreFoundation/CFString.h>
#define LoadResource mac_LoadResource
#define GetCurrentThread mac_GetCurrentThread
#include <CoreServices/CoreServices.h>
#undef LoadResource
#undef GetCurrentThread
#undef DPRINTF
#endif

#include <stdio.h>
38 39
#include <assert.h>
#include <stdarg.h>
40
#include <errno.h>
41 42 43 44 45 46 47
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef HAVE_SYS_MMAN_H
# include <sys/mman.h>
#endif

48 49 50 51 52 53
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "dbghelp_private.h"
#include "winternl.h"
#include "wine/library.h"
#include "wine/debug.h"
54
#include "wine/heap.h"
55 56 57 58
#include "image_private.h"

#ifdef HAVE_MACH_O_LOADER_H

59 60 61
#include <mach-o/fat.h>
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
62
#include <mach-o/dyld.h>
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

#ifdef HAVE_MACH_O_DYLD_IMAGES_H
#include <mach-o/dyld_images.h>
#else
struct dyld_image_info {
    const struct mach_header *imageLoadAddress;
    const char               *imageFilePath;
    uintptr_t                 imageFileModDate;
};

struct dyld_all_image_infos {
    uint32_t                      version;
    uint32_t                      infoArrayCount;
    const struct dyld_image_info *infoArray;
    void*                         notification;
    int                           processDetachedFromSharedRegion;
};
#endif

#ifdef WORDS_BIGENDIAN
#define swap_ulong_be_to_host(n) (n)
#else
#define swap_ulong_be_to_host(n) (RtlUlongByteSwap(n))
#endif

WINE_DEFAULT_DEBUG_CHANNEL(dbghelp_macho);


91 92 93 94 95 96 97 98 99 100
/* Bitmask for Mach-O image header flags indicating that the image is in dyld's
   shared cached.  That implies that its segments are mapped non-contiguously.
   This value isn't defined anywhere in headers.  It's used in dyld and in
   debuggers which support OS X as a magic number.

   The flag also isn't set in the on-disk image file.  It's only set in
   memory by dyld. */
#define MACHO_DYLD_IN_SHARED_CACHE 0x80000000


101 102 103
#define UUID_STRING_LEN 37 /* 16 bytes at 2 hex digits apiece, 4 dashes, and the null terminator */


104 105
struct macho_module_info
{
106
    struct image_file_map       file_map;
107 108 109 110 111
    unsigned long               load_addr;
    unsigned short              in_use : 1,
                                is_loader : 1;
};

112 113 114 115 116 117
struct section_info
{
    BOOL            split_segs;
    unsigned int    section_index;
};

118 119 120 121 122 123 124 125 126 127 128 129
#define MACHO_INFO_DEBUG_HEADER   0x0001
#define MACHO_INFO_MODULE         0x0002
#define MACHO_INFO_NAME           0x0004

struct macho_info
{
    unsigned                    flags;          /* IN  one (or several) of the MACHO_INFO constants */
    unsigned long               dbg_hdr_addr;   /* OUT address of debug header (if MACHO_INFO_DEBUG_HEADER is set) */
    struct module*              module;         /* OUT loaded module (if MACHO_INFO_MODULE is set) */
    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);
131

132 133 134 135 136 137 138 139
static char* format_uuid(const uint8_t uuid[16], char out[UUID_STRING_LEN])
{
    sprintf(out, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
            uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
            uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
    return out;
}

140 141 142 143 144 145 146 147
/******************************************************************
 *              macho_calc_range
 *
 * For a range (offset & length) of a single architecture within
 * a Mach-O file, calculate the page-aligned range of the whole file
 * that encompasses it.  For a fat binary, the architecture will
 * itself be offset within the file, so take that into account.
 */
148 149 150 151
static void macho_calc_range(const struct macho_file_map* fmap, unsigned long offset,
                             unsigned long len, unsigned long* out_aligned_offset,
                             unsigned long* out_aligned_end, unsigned long* out_aligned_len,
                             unsigned long* out_misalign)
152
{
153 154
    unsigned long pagemask = sysconf( _SC_PAGESIZE ) - 1;
    unsigned long file_offset, misalign;
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

    file_offset = fmap->arch_offset + offset;
    misalign = file_offset & pagemask;
    *out_aligned_offset = file_offset - misalign;
    *out_aligned_end = (file_offset + len + pagemask) & ~pagemask;
    if (out_aligned_len)
        *out_aligned_len = *out_aligned_end - *out_aligned_offset;
    if (out_misalign)
        *out_misalign = misalign;
}

/******************************************************************
 *              macho_map_range
 *
 * Maps a range (offset, length in bytes) from a Mach-O file into memory
 */
171 172
static const char* macho_map_range(const struct macho_file_map* fmap, unsigned long offset, unsigned long len,
                                   const char** base)
173
{
174 175
    unsigned long   misalign, aligned_offset, aligned_map_end, map_size;
    const void*     aligned_ptr;
176

177
    TRACE("(%p/%d, 0x%08lx, 0x%08lx)\n", fmap, fmap->fd, offset, len);
178 179 180 181 182 183

    macho_calc_range(fmap, offset, len, &aligned_offset, &aligned_map_end,
                     &map_size, &misalign);

    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);
185

186
    if (aligned_ptr == MAP_FAILED) return IMAGE_NO_MAP;
187 188
    if (base)
        *base = aligned_ptr;
189 190 191 192 193 194 195 196
    return (const char*)aligned_ptr + misalign;
}

/******************************************************************
 *              macho_unmap_range
 *
 * 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)
199
{
200
    TRACE("(%p, %p, %p/%d, 0x%08lx, 0x%08lx)\n", base, mapped, fmap, fmap->fd, offset, len);
201

202
    if ((mapped && *mapped != IMAGE_NO_MAP) || (base && *base != IMAGE_NO_MAP))
203
    {
204 205
        unsigned long   misalign, aligned_offset, aligned_map_end, map_size;
        void*           aligned_ptr;
206 207 208 209

        macho_calc_range(fmap, offset, len, &aligned_offset, &aligned_map_end,
                         &map_size, &misalign);

210 211 212 213
        if (mapped)
            aligned_ptr = (char*)*mapped - misalign;
        else
            aligned_ptr = (void*)*base;
214 215
        if (munmap(aligned_ptr, map_size) < 0)
            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 218 219 220
        if (mapped)
            *mapped = IMAGE_NO_MAP;
        if (base)
            *base = IMAGE_NO_MAP;
221 222 223 224 225 226 227 228 229 230 231
    }
}

/******************************************************************
 *              macho_map_ranges
 *
 * Maps two ranges (offset, length in bytes) from a Mach-O file
 * into memory.  If the two ranges overlap, use one mmap so that
 * the munmap doesn't fragment the mapping.
 */
static BOOL macho_map_ranges(const struct macho_file_map* fmap,
232 233
                             unsigned long offset1, unsigned long len1,
                             unsigned long offset2, unsigned long len2,
234 235
                             const void** mapped1, const void** mapped2)
{
236 237
    unsigned long aligned_offset1, aligned_map_end1;
    unsigned long aligned_offset2, aligned_map_end2;
238

239
    TRACE("(%p/%d, 0x%08lx, 0x%08lx, 0x%08lx, 0x%08lx, %p, %p)\n", fmap, fmap->fd,
240 241 242 243 244 245 246
            offset1, len1, offset2, len2, mapped1, mapped2);

    macho_calc_range(fmap, offset1, len1, &aligned_offset1, &aligned_map_end1, NULL, NULL);
    macho_calc_range(fmap, offset2, len2, &aligned_offset2, &aligned_map_end2, NULL, NULL);

    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)
249
        {
250
            *mapped2 = macho_map_range(fmap, offset2, len2, NULL);
251
            if (*mapped2 == IMAGE_NO_MAP)
252
                macho_unmap_range(NULL, mapped1, fmap, offset1, len1);
253 254 255 256 257 258
        }
    }
    else
    {
        if (offset1 < offset2)
        {
259
            *mapped1 = macho_map_range(fmap, offset1, offset2 + len2 - offset1, NULL);
260
            if (*mapped1 != IMAGE_NO_MAP)
261 262 263 264
                *mapped2 = (const char*)*mapped1 + offset2 - offset1;
        }
        else
        {
265
            *mapped2 = macho_map_range(fmap, offset2, offset1 + len1 - offset2, NULL);
266
            if (*mapped2 != IMAGE_NO_MAP)
267 268 269 270 271 272
                *mapped1 = (const char*)*mapped2 + offset1 - offset2;
        }
    }

    TRACE(" => %p, %p\n", *mapped1, *mapped2);

273
    return (*mapped1 != IMAGE_NO_MAP) && (*mapped2 != IMAGE_NO_MAP);
274 275 276 277 278 279 280 281 282 283
}

/******************************************************************
 *              macho_unmap_ranges
 *
 * Unmaps two ranges (offset, length in bytes) of a Mach-O file
 * from memory.  Use for ranges which were mapped by
 * macho_map_ranges.
 */
static void macho_unmap_ranges(const struct macho_file_map* fmap,
284 285
                               unsigned long offset1, unsigned long len1,
                               unsigned long offset2, unsigned long len2,
286 287
                               const void** mapped1, const void** mapped2)
{
288 289
    unsigned long   aligned_offset1, aligned_map_end1;
    unsigned long   aligned_offset2, aligned_map_end2;
290

291
    TRACE("(%p/%d, 0x%08lx, 0x%08lx, 0x%08lx, 0x%08lx, %p/%p, %p/%p)\n", fmap, fmap->fd,
292 293 294 295 296 297 298
            offset1, len1, offset2, len2, mapped1, *mapped1, mapped2, *mapped2);

    macho_calc_range(fmap, offset1, len1, &aligned_offset1, &aligned_map_end1, NULL, NULL);
    macho_calc_range(fmap, offset2, len2, &aligned_offset2, &aligned_map_end2, NULL, NULL);

    if (aligned_map_end1 < aligned_offset2 || aligned_map_end2 < aligned_offset1)
    {
299 300
        macho_unmap_range(NULL, mapped1, fmap, offset1, len1);
        macho_unmap_range(NULL, mapped2, fmap, offset2, len2);
301 302 303 304 305
    }
    else
    {
        if (offset1 < offset2)
        {
306
            macho_unmap_range(NULL, mapped1, fmap, offset1, offset2 + len2 - offset1);
307
            *mapped2 = IMAGE_NO_MAP;
308 309 310
        }
        else
        {
311
            macho_unmap_range(NULL, mapped2, fmap, offset2, offset1 + len1 - offset2);
312
            *mapped1 = IMAGE_NO_MAP;
313 314 315 316
        }
    }
}

317 318 319 320 321 322 323
/******************************************************************
 *              macho_find_section
 */
BOOL macho_find_section(struct image_file_map* ifm, const char* segname, const char* sectname, struct image_section_map* ism)
{
    struct macho_file_map* fmap;
    unsigned i;
324
    char tmp[sizeof(fmap->sect[0].section.sectname)];
325 326 327 328 329 330 331 332 333 334

    /* Other parts of dbghelp use section names like ".eh_frame".  Mach-O uses
       names like "__eh_frame".  Convert those. */
    if (sectname[0] == '.')
    {
        lstrcpynA(tmp, "__", sizeof(tmp));
        lstrcpynA(tmp + 2, sectname + 1, sizeof(tmp) - 2);
        sectname = tmp;
    }

335
    while (ifm)
336
    {
337 338
        fmap = &ifm->u.macho;
        for (i = 0; i < fmap->num_sections; i++)
339
        {
340
            if (!fmap->sect[i].ignored &&
341 342
                strcmp(fmap->sect[i].section.sectname, sectname) == 0 &&
                (!segname || strcmp(fmap->sect[i].section.segname, segname) == 0))
343 344 345 346 347
            {
                ism->fmap = ifm;
                ism->sidx = i;
                return TRUE;
            }
348
        }
349
        ifm = fmap->dsym;
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    }

    ism->fmap = NULL;
    ism->sidx = -1;
    return FALSE;
}

/******************************************************************
 *              macho_map_section
 */
const char* macho_map_section(struct image_section_map* ism)
{
    struct macho_file_map* fmap = &ism->fmap->u.macho;

    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 367
        return IMAGE_NO_MAP;

368
    return macho_map_range(fmap, fmap->sect[ism->sidx].section.offset, fmap->sect[ism->sidx].section.size,
369 370 371 372 373 374 375 376 377 378 379 380
                           &fmap->sect[ism->sidx].mapped);
}

/******************************************************************
 *              macho_unmap_section
 */
void macho_unmap_section(struct image_section_map* ism)
{
    struct macho_file_map* fmap = &ism->fmap->u.macho;

    if (ism->sidx >= 0 && ism->sidx < fmap->num_sections && fmap->sect[ism->sidx].mapped != IMAGE_NO_MAP)
    {
381 382
        macho_unmap_range(&fmap->sect[ism->sidx].mapped, NULL, fmap, fmap->sect[ism->sidx].section.offset,
                          fmap->sect[ism->sidx].section.size);
383 384 385 386 387 388 389 390
    }
}

/******************************************************************
 *              macho_get_map_rva
 */
DWORD_PTR macho_get_map_rva(const struct image_section_map* ism)
{
391 392
    if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.macho.num_sections ||
        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;
395 396 397 398 399 400 401
}

/******************************************************************
 *              macho_get_map_size
 */
unsigned macho_get_map_size(const struct image_section_map* ism)
{
402 403
    if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.macho.num_sections ||
        ism->fmap->u.macho.sect[ism->sidx].ignored)
404
        return 0;
405
    return ism->fmap->u.macho.sect[ism->sidx].section.size;
406 407
}

408 409 410 411 412 413 414
/******************************************************************
 *              macho_map_load_commands
 *
 * Maps the load commands from a Mach-O file into memory
 */
static const struct load_command* macho_map_load_commands(struct macho_file_map* fmap)
{
415
    if (fmap->load_commands == IMAGE_NO_MAP)
416 417
    {
        fmap->load_commands = (const struct load_command*) macho_map_range(
418
                fmap, fmap->header_size, fmap->mach_header.sizeofcmds, NULL);
419 420 421 422 423 424 425 426 427 428 429 430 431
        TRACE("Mapped load commands: %p\n", fmap->load_commands);
    }

    return fmap->load_commands;
}

/******************************************************************
 *              macho_unmap_load_commands
 *
 * Unmaps the load commands of a Mach-O file from memory
 */
static void macho_unmap_load_commands(struct macho_file_map* fmap)
{
432
    if (fmap->load_commands != IMAGE_NO_MAP)
433 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);
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    }
}

/******************************************************************
 *              macho_next_load_command
 *
 * Advance to the next load command
 */
static const struct load_command* macho_next_load_command(const struct load_command* lc)
{
    return (const struct load_command*)((const char*)lc + lc->cmdsize);
}

/******************************************************************
 *              macho_enum_load_commands
 *
 * Enumerates the load commands for a Mach-O file, selecting by
 * the command type, calling a callback for each.  If the callback
 * returns <0, that indicates an error.  If it returns >0, that means
 * it's not interested in getting any more load commands.
 * If this function returns <0, that's an error produced by the
 * callback.  If >=0, that's the count of load commands successfully
 * processed.
 */
461 462
static int macho_enum_load_commands(struct image_file_map *ifm, unsigned cmd,
                                    int (*cb)(struct image_file_map*, const struct load_command*, void*),
463 464
                                    void* user)
{
465
    struct macho_file_map* fmap = &ifm->u.macho;
466 467 468 469 470 471
    const struct load_command* lc;
    int i;
    int count = 0;

    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;
473 474 475 476 477 478 479 480 481 482

    TRACE("%d total commands\n", fmap->mach_header.ncmds);

    for (i = 0; i < fmap->mach_header.ncmds; i++, lc = macho_next_load_command(lc))
    {
        int result;

        if (cmd && cmd != lc->cmd) continue;
        count++;

483
        result = cb(ifm, lc, user);
484 485 486 487 488 489 490 491
        TRACE("load_command[%d] (%p), cmd %u; callback => %d\n", i, lc, lc->cmd, result);
        if (result) return (result < 0) ? result : count;
    }

    return count;
}

/******************************************************************
492 493 494 495 496 497
 *              macho_count_sections
 *
 * Callback for macho_enum_load_commands.  Counts the number of
 * significant sections in a Mach-O file.  All commands are
 * 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)
499
{
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    char segname[16];
    uint32_t nsects;

    if (ifm->addr_size == 32)
    {
        const struct segment_command *sc = (const struct segment_command *)lc;
        memcpy(segname, sc->segname, sizeof(segname));
        nsects = sc->nsects;
    }
    else
    {
        const struct segment_command_64 *sc = (const struct segment_command_64 *)lc;
        memcpy(segname, sc->segname, sizeof(segname));
        nsects = sc->nsects;
    }
515

516
    TRACE("(%p/%d, %p, %p) segment %s\n", ifm, ifm->u.macho.fd, lc, user,
517
        debugstr_an(segname, sizeof(segname)));
518

519
    ifm->u.macho.num_sections += nsects;
520 521 522 523 524
    return 0;
}

/******************************************************************
 *              macho_load_section_info
525 526
 *
 * Callback for macho_enum_load_commands.  Accumulates the address
527 528
 * range covered by the segments of a Mach-O file and builds the
 * section map.  All commands are expected to be of LC_SEGMENT[_64] type.
529
 */
530
static int macho_load_section_info(struct image_file_map* ifm, const struct load_command* lc, void* user)
531
{
532
    struct macho_file_map*          fmap = &ifm->u.macho;
533 534
    struct section_info*            info = user;
    BOOL                            ignore;
535
    int                             i;
536
    unsigned long                   tmp, page_mask = sysconf( _SC_PAGESIZE ) - 1;
537 538 539
    uint64_t vmaddr, vmsize;
    char segname[16];
    uint32_t nsects;
540
    const void *sections;
541 542 543 544 545 546 547 548

    if (ifm->addr_size == 32)
    {
        const struct segment_command *sc = (const struct segment_command *)lc;
        vmaddr = sc->vmaddr;
        vmsize = sc->vmsize;
        memcpy(segname, sc->segname, sizeof(segname));
        nsects = sc->nsects;
549
        sections = (const void *)(sc + 1);
550 551 552 553 554 555 556 557
    }
    else
    {
        const struct segment_command_64 *sc = (const struct segment_command_64 *)lc;
        vmaddr = sc->vmaddr;
        vmsize = sc->vmsize;
        memcpy(segname, sc->segname, sizeof(segname));
        nsects = sc->nsects;
558
        sections = (const void *)(sc + 1);
559
    }
560

561 562
    TRACE("(%p/%d, %p, %p) before: 0x%08lx - 0x%08lx\n", fmap, fmap->fd, lc, user,
            (unsigned long)fmap->segs_start, (unsigned long)fmap->segs_size);
563 564
    TRACE("Segment command vm: 0x%08lx - 0x%08lx\n", (unsigned long)vmaddr,
            (unsigned long)(vmaddr + vmsize));
565

566 567 568
    /* Images in the dyld shared cache have their segments mapped non-contiguously.
       We don't know how to properly locate any of the segments other than __TEXT,
       so ignore them. */
569
    ignore = (info->split_segs && strcmp(segname, SEG_TEXT));
570

571 572 573
    if (!strncmp(segname, "WINE_", 5))
        TRACE("Ignoring special Wine segment %s\n", debugstr_an(segname, sizeof(segname)));
    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 578 579
    else
    {
        /* If this segment starts before previously-known earliest, record new earliest. */
580 581
        if (vmaddr < fmap->segs_start)
            fmap->segs_start = vmaddr;
582

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;
586

587 588
        TRACE("after: 0x%08lx - 0x%08lx\n", (unsigned long)fmap->segs_start, (unsigned long)fmap->segs_size);
    }
589

590
    for (i = 0; i < nsects; i++)
591
    {
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
        if (ifm->addr_size == 32)
        {
            const struct section *section = &((const struct section *)sections)[i];
            memcpy(fmap->sect[info->section_index].section.sectname, section->sectname, sizeof(section->sectname));
            memcpy(fmap->sect[info->section_index].section.segname,  section->segname,  sizeof(section->segname));
            fmap->sect[info->section_index].section.addr      = section->addr;
            fmap->sect[info->section_index].section.size      = section->size;
            fmap->sect[info->section_index].section.offset    = section->offset;
            fmap->sect[info->section_index].section.align     = section->align;
            fmap->sect[info->section_index].section.reloff    = section->reloff;
            fmap->sect[info->section_index].section.nreloc    = section->nreloc;
            fmap->sect[info->section_index].section.flags     = section->flags;
        }
        else
            fmap->sect[info->section_index].section = ((const struct section_64 *)sections)[i];

608 609 610
        fmap->sect[info->section_index].mapped = IMAGE_NO_MAP;
        fmap->sect[info->section_index].ignored = ignore;
        info->section_index++;
611
    }
612 613 614 615

    return 0;
}

616 617 618 619 620 621
/******************************************************************
 *              find_uuid
 *
 * Callback for macho_enum_load_commands.  Records the UUID load
 * command of a Mach-O file.
 */
622
static int find_uuid(struct image_file_map* ifm, const struct load_command* lc, void* user)
623
{
624
    ifm->u.macho.uuid = (const struct uuid_command*)lc;
625 626 627
    return 1;
}

628 629 630 631 632 633 634 635
/******************************************************************
 *              reset_file_map
 */
static inline void reset_file_map(struct image_file_map* ifm)
{
    struct macho_file_map* fmap = &ifm->u.macho;

    fmap->fd = -1;
636
    fmap->dsym = NULL;
637
    fmap->load_commands = IMAGE_NO_MAP;
638
    fmap->uuid = NULL;
639 640 641 642
    fmap->num_sections = 0;
    fmap->sect = NULL;
}

643 644 645 646 647
/******************************************************************
 *              macho_map_file
 *
 * Maps a Mach-O file into memory (and checks it's a real Mach-O file)
 */
648 649
static BOOL macho_map_file(struct process *pcs, const WCHAR *filenameW,
    BOOL split_segs, struct image_file_map* ifm)
650
{
651
    struct macho_file_map* fmap = &ifm->u.macho;
652 653 654 655 656
    struct fat_header   fat_header;
    struct stat         statbuf;
    int                 i;
    char*               filename;
    unsigned            len;
657
    struct section_info info;
658
    BOOL                ret = FALSE;
659 660 661
    cpu_type_t target_cpu = (pcs->is_64bit) ? CPU_TYPE_X86_64 : CPU_TYPE_X86;
    uint32_t target_magic = (pcs->is_64bit) ? MH_MAGIC_64 : MH_MAGIC;
    uint32_t target_cmd   = (pcs->is_64bit) ? LC_SEGMENT_64 : LC_SEGMENT;
662 663 664

    TRACE("(%s, %p)\n", debugstr_w(filenameW), fmap);

665
    reset_file_map(ifm);
666 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);
670 671

    len = WideCharToMultiByte(CP_UNIXCP, 0, filenameW, -1, NULL, 0, NULL, NULL);
672 673 674 675 676
    if (!(filename = HeapAlloc(GetProcessHeap(), 0, len)))
    {
        WARN("failed to allocate filename buffer\n");
        return FALSE;
    }
677 678 679
    WideCharToMultiByte(CP_UNIXCP, 0, filenameW, -1, filename, len, NULL, NULL);

    /* check that the file exists */
680 681 682 683 684
    if (stat(filename, &statbuf) == -1 || S_ISDIR(statbuf.st_mode))
    {
        TRACE("stat() failed or %s is directory: %s\n", debugstr_a(filename), strerror(errno));
        goto done;
    }
685 686

    /* Now open the file, so that we can mmap() it. */
687 688 689 690 691
    if ((fmap->fd = open(filename, O_RDONLY)) == -1)
    {
        TRACE("failed to open file %s: %d\n", debugstr_a(filename), errno);
        goto done;
    }
692 693

    if (read(fmap->fd, &fat_header, sizeof(fat_header)) != sizeof(fat_header))
694 695
    {
        TRACE("failed to read fat header: %d\n", errno);
696
        goto done;
697
    }
698 699 700 701 702 703 704 705 706 707 708
    TRACE("... got possible fat header\n");

    /* Fat header is always in big-endian order. */
    if (swap_ulong_be_to_host(fat_header.magic) == FAT_MAGIC)
    {
        int narch = swap_ulong_be_to_host(fat_header.nfat_arch);
        for (i = 0; i < narch; i++)
        {
            struct fat_arch fat_arch;
            if (read(fmap->fd, &fat_arch, sizeof(fat_arch)) != sizeof(fat_arch))
                goto done;
709
            if (swap_ulong_be_to_host(fat_arch.cputype) == target_cpu)
710 711 712 713 714 715
            {
                fmap->arch_offset = swap_ulong_be_to_host(fat_arch.offset);
                break;
            }
        }
        if (i >= narch) goto done;
716
        TRACE("... found target arch (%d)\n", target_cpu);
717 718 719 720 721 722 723 724 725 726 727 728 729
    }
    else
    {
        fmap->arch_offset = 0;
        TRACE("... not a fat header\n");
    }

    /* Individual architecture (standalone or within a fat file) is in its native byte order. */
    lseek(fmap->fd, fmap->arch_offset, SEEK_SET);
    if (read(fmap->fd, &fmap->mach_header, sizeof(fmap->mach_header)) != sizeof(fmap->mach_header))
        goto done;
    TRACE("... got possible Mach header\n");
    /* and check for a Mach-O header */
730 731
    if (fmap->mach_header.magic != target_magic ||
        fmap->mach_header.cputype != target_cpu) goto done;
732 733 734 735 736 737 738
    /* Make sure the file type is one of the ones we expect. */
    switch (fmap->mach_header.filetype)
    {
        case MH_EXECUTE:
        case MH_DYLIB:
        case MH_DYLINKER:
        case MH_BUNDLE:
739
        case MH_DSYM:
740 741 742 743
            break;
        default:
            goto done;
    }
744
    TRACE("... verified Mach header\n");
745

746
    fmap->num_sections = 0;
747
    if (macho_enum_load_commands(ifm, target_cmd, macho_count_sections, NULL) < 0)
748 749 750 751 752 753 754
        goto done;
    TRACE("%d sections\n", fmap->num_sections);

    fmap->sect = HeapAlloc(GetProcessHeap(), 0, fmap->num_sections * sizeof(fmap->sect[0]));
    if (!fmap->sect)
        goto done;

755 756 757
    fmap->segs_size = 0;
    fmap->segs_start = ~0L;

758 759
    info.split_segs = split_segs;
    info.section_index = 0;
760
    if (macho_enum_load_commands(ifm, target_cmd, macho_load_section_info, &info) < 0)
761 762
    {
        fmap->num_sections = 0;
763
        goto done;
764
    }
765 766

    fmap->segs_size -= fmap->segs_start;
767 768
    TRACE("segs_start: 0x%08lx, segs_size: 0x%08lx\n", (unsigned long)fmap->segs_start,
            (unsigned long)fmap->segs_size);
769

770
    if (macho_enum_load_commands(ifm, LC_UUID, find_uuid, NULL) < 0)
771 772 773 774 775 776 777 778 779
        goto done;
    if (fmap->uuid)
    {
        char uuid_string[UUID_STRING_LEN];
        TRACE("UUID %s\n", format_uuid(fmap->uuid->uuid, uuid_string));
    }
    else
        TRACE("no UUID found\n");

780 781 782
    ret = TRUE;
done:
    if (!ret)
783
        macho_unmap_file(ifm);
784 785 786 787 788 789 790 791 792
    HeapFree(GetProcessHeap(), 0, filename);
    return ret;
}

/******************************************************************
 *              macho_unmap_file
 *
 * Unmaps a Mach-O file from memory (previously mapped with macho_map_file)
 */
793
static void macho_unmap_file(struct image_file_map* ifm)
794
{
795 796
    struct image_file_map* cursor;

797
    TRACE("(%p/%d)\n", ifm, ifm->u.macho.fd);
798 799 800

    cursor = ifm;
    while (cursor)
801
    {
802
        struct image_file_map* next;
803

804 805 806 807 808 809 810
        if (ifm->u.macho.fd != -1)
        {
            struct image_section_map ism;

            ism.fmap = ifm;
            for (ism.sidx = 0; ism.sidx < ifm->u.macho.num_sections; ism.sidx++)
                macho_unmap_section(&ism);
811

812 813 814 815 816 817 818 819 820 821
            HeapFree(GetProcessHeap(), 0, ifm->u.macho.sect);
            macho_unmap_load_commands(&ifm->u.macho);
            close(ifm->u.macho.fd);
            ifm->u.macho.fd = -1;
        }

        next = cursor->u.macho.dsym;
        if (cursor != ifm)
            HeapFree(GetProcessHeap(), 0, cursor);
        cursor = next;
822 823 824 825 826 827 828 829 830 831 832 833
    }
}

/******************************************************************
 *              macho_sect_is_code
 *
 * Checks if a section, identified by sectidx which is a 1-based
 * index into the sections of all segments, in order of load
 * commands, contains code.
 */
static BOOL macho_sect_is_code(struct macho_file_map* fmap, unsigned char sectidx)
{
834 835
    BOOL ret;

836 837
    TRACE("(%p/%d, %u)\n", fmap, fmap->fd, sectidx);

838 839 840
    if (!sectidx) return FALSE;

    sectidx--; /* convert from 1-based to 0-based */
841
    if (sectidx >= fmap->num_sections || fmap->sect[sectidx].ignored) return FALSE;
842

843 844
    ret = (!(fmap->sect[sectidx].section.flags & SECTION_TYPE) &&
           (fmap->sect[sectidx].section.flags & (S_ATTR_PURE_INSTRUCTIONS|S_ATTR_SOME_INSTRUCTIONS)));
845 846
    TRACE("-> %d\n", ret);
    return ret;
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
}

struct symtab_elt
{
    struct hash_table_elt       ht_elt;
    struct symt_compiland*      compiland;
    unsigned long               addr;
    unsigned char               is_code:1,
                                is_public:1,
                                is_global:1,
                                used:1;
};

struct macho_debug_info
{
    struct macho_file_map*      fmap;
    struct module*              module;
    struct pool                 pool;
    struct hash_table           ht_symtab;
};

/******************************************************************
 *              macho_stabs_def_cb
 *
 * Callback for stabs_parse.  Collect symbol definitions.
 */
static void macho_stabs_def_cb(struct module* module, unsigned long load_offset,
                               const char* name, unsigned long offset,
                               BOOL is_public, BOOL is_global, unsigned char sectidx,
                               struct symt_compiland* compiland, void* user)
{
    struct macho_debug_info*    mdi = user;
    struct symtab_elt*          ste;

    TRACE("(%p, 0x%08lx, %s, 0x%08lx, %d, %d, %u, %p, %p/%p/%d)\n", module, load_offset,
            debugstr_a(name), offset, is_public, is_global, sectidx,
            compiland, mdi, mdi->fmap, mdi->fmap->fd);

    /* Defer the creation of new non-debugging symbols until after we've
     * finished parsing the stabs. */
    ste                 = pool_alloc(&mdi->pool, sizeof(*ste));
    ste->ht_elt.name    = pool_strdup(&mdi->pool, name);
    ste->compiland      = compiland;
    ste->addr           = load_offset + offset;
    ste->is_code        = !!macho_sect_is_code(mdi->fmap, sectidx);
    ste->is_public      = !!is_public;
    ste->is_global      = !!is_global;
    ste->used           = 0;
    hash_table_add(&mdi->ht_symtab, &ste->ht_elt);
}

/******************************************************************
 *              macho_parse_symtab
 *
 * Callback for macho_enum_load_commands.  Processes the LC_SYMTAB
 * load commands from the Mach-O file.
 */
904
static int macho_parse_symtab(struct image_file_map* ifm,
905 906
                              const struct load_command* lc, void* user)
{
907
    struct macho_file_map* fmap = &ifm->u.macho;
908 909 910 911
    const struct symtab_command*    sc = (const struct symtab_command*)lc;
    struct macho_debug_info*        mdi = user;
    const char*                     stabstr;
    int                             ret = 0;
912 913
    size_t stabsize = (ifm->addr_size == 32) ? sizeof(struct nlist) : sizeof(struct nlist_64);
    const char *stab;
914 915 916 917

    TRACE("(%p/%d, %p, %p) %u syms at 0x%08x, strings 0x%08x - 0x%08x\n", fmap, fmap->fd, lc,
            user, sc->nsyms, sc->symoff, sc->stroff, sc->stroff + sc->strsize);

918
    if (!macho_map_ranges(fmap, sc->symoff, sc->nsyms * stabsize,
919 920 921
            sc->stroff, sc->strsize, (const void**)&stab, (const void**)&stabstr))
        return 0;

922 923
    if (!stabs_parse(mdi->module,
                     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 927
        ret = -1;

928
    macho_unmap_ranges(fmap, sc->symoff, sc->nsyms * stabsize,
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
            sc->stroff, sc->strsize, (const void**)&stab, (const void**)&stabstr);

    return ret;
}

/******************************************************************
 *              macho_finish_stabs
 *
 * Integrate the non-debugging symbols we've gathered into the
 * symbols that were generated during stabs parsing.
 */
static void macho_finish_stabs(struct module* module, struct hash_table* ht_symtab)
{
    struct hash_table_iter      hti_ours;
    struct symtab_elt*          ste;
    BOOL                        adjusted = FALSE;

    TRACE("(%p, %p)\n", module, ht_symtab);

    /* For each of our non-debugging symbols, see if it can provide some
     * missing details to one of the module's known symbols. */
    hash_table_iter_init(ht_symtab, &hti_ours, NULL);
    while ((ste = hash_table_iter_up(&hti_ours)))
    {
        struct hash_table_iter  hti_modules;
        void*                   ptr;
        struct symt_ht*         sym;
        struct symt_function*   func;
        struct symt_data*       data;

        hash_table_iter_init(&module->ht_symbols, &hti_modules, ste->ht_elt.name);
        while ((ptr = hash_table_iter_up(&hti_modules)))
        {
962
            sym = CONTAINING_RECORD(ptr, struct symt_ht, hash_elt);
963 964 965 966 967 968 969 970

            if (strcmp(sym->hash_elt.name, ste->ht_elt.name))
                continue;

            switch (sym->symt.tag)
            {
            case SymTagFunction:
                func = (struct symt_function*)sym;
971
                if (func->address == module->format_info[DFI_MACHO]->u.macho_info->load_addr)
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
                {
                    TRACE("Adjusting function %p/%s!%s from 0x%08lx to 0x%08lx\n", func,
                          debugstr_w(module->module.ModuleName), sym->hash_elt.name,
                          func->address, ste->addr);
                    func->address = ste->addr;
                    adjusted = TRUE;
                }
                if (func->address == ste->addr)
                    ste->used = 1;
                break;
            case SymTagData:
                data = (struct symt_data*)sym;
                switch (data->kind)
                {
                case DataIsGlobal:
                case DataIsFileStatic:
988
                    if (data->u.var.offset == module->format_info[DFI_MACHO]->u.macho_info->load_addr)
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
                    {
                        TRACE("Adjusting data symbol %p/%s!%s from 0x%08lx to 0x%08lx\n",
                              data, debugstr_w(module->module.ModuleName), sym->hash_elt.name,
                              data->u.var.offset, ste->addr);
                        data->u.var.offset = ste->addr;
                        adjusted = TRUE;
                    }
                    if (data->u.var.offset == ste->addr)
                    {
                        enum DataKind new_kind;

                        new_kind = ste->is_global ? DataIsGlobal : DataIsFileStatic;
                        if (data->kind != new_kind)
                        {
                            WARN("Changing kind for %p/%s!%s from %d to %d\n", sym,
                                 debugstr_w(module->module.ModuleName), sym->hash_elt.name,
                                 (int)data->kind, (int)new_kind);
                            data->kind = new_kind;
                            adjusted = TRUE;
                        }
                        ste->used = 1;
                    }
                    break;
                default:;
                }
                break;
            default:
                TRACE("Ignoring tag %u\n", sym->symt.tag);
                break;
            }
        }
    }

    if (adjusted)
    {
        /* since we may have changed some addresses, mark the module to be resorted */
        module->sortlist_valid = FALSE;
    }

    /* Mark any of our non-debugging symbols which fall on an already-used
     * address as "used".  This allows us to skip them in the next loop,
     * below.  We do this in separate loops because symt_new_* marks the
     * list as needing sorting and symt_find_nearest sorts if needed,
     * causing thrashing. */
    if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
    {
        hash_table_iter_init(ht_symtab, &hti_ours, NULL);
        while ((ste = hash_table_iter_up(&hti_ours)))
        {
            struct symt_ht* sym;
            ULONG64         addr;

            if (ste->used) continue;

            sym = symt_find_nearest(module, ste->addr);
            if (sym)
1045
                symt_get_address(&sym->symt, &addr);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
            if (sym && ste->addr == addr)
            {
                ULONG64 size = 0;
                DWORD   kind = -1;

                ste->used = 1;

                /* If neither symbol has a correct size (ours never does), we
                 * consider them both to be markers.  No warning is needed in
                 * that case.
                 * Also, we check that we don't have two symbols, one local, the other
                 * global, which is legal.
                 */
1059 1060
                symt_get_info(module, &sym->symt, TI_GET_LENGTH,   &size);
                symt_get_info(module, &sym->symt, TI_GET_DATAKIND, &kind);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
                if (size && kind == (ste->is_global ? DataIsGlobal : DataIsFileStatic))
                    FIXME("Duplicate in %s: %s<%08lx> %s<%s-%s>\n",
                          debugstr_w(module->module.ModuleName),
                          ste->ht_elt.name, ste->addr,
                          sym->hash_elt.name,
                          wine_dbgstr_longlong(addr), wine_dbgstr_longlong(size));
            }
        }
    }

    /* For any of our remaining non-debugging symbols which have no match
     * among the module's known symbols, add them as new symbols. */
    hash_table_iter_init(ht_symtab, &hti_ours, NULL);
    while ((ste = hash_table_iter_up(&hti_ours)))
    {
        if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY) && !ste->used)
        {
            if (ste->is_code)
            {
                symt_new_function(module, ste->compiland, ste->ht_elt.name,
                    ste->addr, 0, NULL);
            }
            else
            {
1085 1086 1087 1088 1089
                struct location loc;

                loc.kind = loc_absolute;
                loc.reg = 0;
                loc.offset = ste->addr;
1090
                symt_new_global_variable(module, ste->compiland, ste->ht_elt.name,
1091
                                         !ste->is_global, loc, 0, NULL);
1092 1093 1094 1095 1096 1097 1098
            }

            ste->used = 1;
        }

        if (ste->is_public && !(dbghelp_options & SYMOPT_NO_PUBLICS))
        {
1099
            symt_new_public(module, ste->compiland, ste->ht_elt.name, ste->addr, 0);
1100 1101 1102 1103
        }
    }
}

1104 1105 1106 1107 1108 1109 1110 1111 1112
/******************************************************************
 *              try_dsym
 *
 * Try to load a debug symbol file from the given path and check
 * if its UUID matches the UUID of an already-mapped file.  If so,
 * stash the file map in the "dsym" field of the file and return
 * TRUE.  If it can't be mapped or its UUID doesn't match, return
 * FALSE.
 */
1113
static BOOL try_dsym(struct process *pcs, const WCHAR* path, struct macho_file_map* fmap)
1114 1115 1116
{
    struct image_file_map dsym_ifm;

1117
    if (macho_map_file(pcs, path, FALSE, &dsym_ifm))
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    {
        char uuid_string[UUID_STRING_LEN];

        if (dsym_ifm.u.macho.uuid && !memcmp(dsym_ifm.u.macho.uuid->uuid, fmap->uuid->uuid, sizeof(fmap->uuid->uuid)))
        {
            TRACE("found matching debug symbol file at %s\n", debugstr_w(path));
            fmap->dsym = HeapAlloc(GetProcessHeap(), 0, sizeof(dsym_ifm));
            *fmap->dsym = dsym_ifm;
            return TRUE;
        }

        TRACE("candidate debug symbol file at %s has wrong UUID %s; ignoring\n", debugstr_w(path),
              format_uuid(dsym_ifm.u.macho.uuid->uuid, uuid_string));

        macho_unmap_file(&dsym_ifm);
    }
    else
        TRACE("couldn't map file at %s\n", debugstr_w(path));

    return FALSE;
}

/******************************************************************
 *              find_and_map_dsym
 *
 * Search for a debugging symbols file associated with a module and
 * map it.  First look for a .dSYM bundle next to the module file
 * (e.g. <path>.dSYM/Contents/Resources/DWARF/<basename of path>)
 * as produced by dsymutil.  Next, look for a .dwarf file next to
 * the module file (e.g. <path>.dwarf) as produced by
 * "dsymutil --flat".  Finally, use Spotlight to search for a
 * .dSYM bundle with the same UUID as the module file.
 */
1151
static void find_and_map_dsym(struct process *pcs, struct module* module)
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
{
    static const WCHAR dot_dsym[] = {'.','d','S','Y','M',0};
    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};
    static const WCHAR dot_dwarf[] = {'.','d','w','a','r','f',0};
    struct macho_file_map* fmap = &module->format_info[DFI_MACHO]->u.macho_info->file_map.u.macho;
    const WCHAR* p;
    size_t len;
    WCHAR* path = NULL;
    char uuid_string[UUID_STRING_LEN];
    CFStringRef uuid_cfstring;
    CFStringRef query_string;
    MDQueryRef query = NULL;

    /* Without a UUID, we can't verify that any debug info file we find corresponds
       to this file.  Better to have no debug info than incorrect debug info. */
    if (!fmap->uuid)
        return;

    if ((p = strrchrW(module->module.LoadedImageName, '/')))
        p++;
    else
        p = module->module.LoadedImageName;
    len = strlenW(module->module.LoadedImageName) + strlenW(dot_dsym) + strlenW(dsym_subpath) + strlenW(p) + 1;
    path = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
    if (!path)
        return;
    strcpyW(path, module->module.LoadedImageName);
    strcatW(path, dot_dsym);
    strcatW(path, dsym_subpath);
    strcatW(path, p);

1183
    if (try_dsym(pcs, path, fmap))
1184 1185 1186 1187
        goto found;

    strcpyW(path + strlenW(module->module.LoadedImageName), dot_dwarf);

1188
    if (try_dsym(pcs, path, fmap))
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
        goto found;

    format_uuid(fmap->uuid->uuid, uuid_string);
    uuid_cfstring = CFStringCreateWithCString(NULL, uuid_string, kCFStringEncodingASCII);
    query_string = CFStringCreateWithFormat(NULL, NULL, CFSTR("com_apple_xcode_dsym_uuids == \"%@\""), uuid_cfstring);
    CFRelease(uuid_cfstring);
    query = MDQueryCreate(NULL, query_string, NULL, NULL);
    CFRelease(query_string);
    MDQuerySetMaxCount(query, 1);
    if (MDQueryExecute(query, kMDQuerySynchronous) && MDQueryGetResultCount(query) >= 1)
    {
        MDItemRef item = (MDItemRef)MDQueryGetResultAtIndex(query, 0);
        CFStringRef item_path = MDItemCopyAttribute(item, kMDItemPath);
        if (item_path)
        {
            CFIndex item_path_len = CFStringGetLength(item_path);
            if (item_path_len + strlenW(dsym_subpath) + strlenW(p) >= len)
            {
                HeapFree(GetProcessHeap(), 0, path);
                len = item_path_len + strlenW(dsym_subpath) + strlenW(p) + 1;
                path = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
            }
            CFStringGetCharacters(item_path, CFRangeMake(0, item_path_len), (UniChar*)path);
            strcpyW(path + item_path_len, dsym_subpath);
            strcatW(path, p);
            CFRelease(item_path);

1216
            if (try_dsym(pcs, path, fmap))
1217 1218 1219 1220 1221 1222 1223 1224 1225
                goto found;
        }
    }

found:
    HeapFree(GetProcessHeap(), 0, path);
    if (query) CFRelease(query);
}

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
/******************************************************************
 *              image_uses_split_segs
 *
 * Determine if the Mach-O image loaded at a particular address in
 * the given process is in the dyld shared cache and therefore has
 * its segments mapped non-contiguously.
 *
 * The image header has to be loaded from the process's memory
 * because the relevant flag is only set in memory, not in the file.
 */
static BOOL image_uses_split_segs(HANDLE process, unsigned long load_addr)
{
    BOOL split_segs = FALSE;

    if (process && load_addr)
    {
1242 1243 1244
        struct process *pcs = process_find_by_handle(process);
        cpu_type_t target_cpu = (pcs->is_64bit) ? CPU_TYPE_X86_64 : CPU_TYPE_X86;
        uint32_t target_magic = (pcs->is_64bit) ? MH_MAGIC_64 : MH_MAGIC;
1245
        struct mach_header header;
1246

1247
        if (ReadProcessMemory(process, (void*)load_addr, &header, sizeof(header), NULL) &&
1248
            header.magic == target_magic && header.cputype == target_cpu &&
1249 1250 1251 1252 1253 1254 1255 1256 1257
            header.flags & MACHO_DYLD_IN_SHARED_CACHE)
        {
            split_segs = TRUE;
        }
    }

    return split_segs;
}

1258
/******************************************************************
1259
 *              macho_load_debug_info
1260
 *
1261
 * Loads Mach-O debugging information from the module image file.
1262
 */
1263
BOOL macho_load_debug_info(struct process *pcs, struct module* module)
1264 1265 1266 1267
{
    BOOL                    ret = FALSE;
    struct macho_debug_info mdi;
    int                     result;
1268
    struct image_file_map  *ifm;
1269 1270 1271 1272 1273 1274 1275 1276
    struct macho_file_map  *fmap;

    if (module->type != DMT_MACHO || !module->format_info[DFI_MACHO]->u.macho_info)
    {
        ERR("Bad Mach-O module '%s'\n", debugstr_w(module->module.LoadedImageName));
        return FALSE;
    }

1277 1278
    ifm = &module->format_info[DFI_MACHO]->u.macho_info->file_map;
    fmap = &ifm->u.macho;
1279 1280 1281 1282 1283

    TRACE("(%p, %p/%d)\n", module, fmap, fmap->fd);

    module->module.SymType = SymExport;

1284 1285
    if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
    {
1286
        find_and_map_dsym(pcs, module);
1287 1288 1289 1290 1291 1292

        if (dwarf2_parse(module, module->reloc_delta, NULL /* FIXME: some thunks to deal with ? */,
                         &module->format_info[DFI_MACHO]->u.macho_info->file_map))
            ret = TRUE;
    }

1293 1294 1295 1296
    mdi.fmap = fmap;
    mdi.module = module;
    pool_init(&mdi.pool, 65536);
    hash_table_init(&mdi.pool, &mdi.ht_symtab, 256);
1297
    result = macho_enum_load_commands(ifm, LC_SYMTAB, macho_parse_symtab, &mdi);
1298 1299 1300 1301 1302
    if (result > 0)
        ret = TRUE;
    else if (result < 0)
        WARN("Couldn't correctly read stabs\n");

1303
    if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY) && fmap->dsym)
1304
    {
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 1310
        else if (result < 0)
            WARN("Couldn't correctly read stabs\n");
1311
    }
1312

1313 1314
    macho_finish_stabs(module, &mdi.ht_symtab);

1315 1316 1317 1318 1319 1320 1321 1322 1323
    pool_destroy(&mdi.pool);
    return ret;
}

/******************************************************************
 *              macho_fetch_file_info
 *
 * 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 1326
                           DWORD* size, DWORD* checksum)
{
1327
    struct image_file_map fmap;
1328
    struct process *pcs;
1329
    BOOL split_segs;
1330 1331 1332

    TRACE("(%s, %p, %p, %p)\n", debugstr_w(name), base, size, checksum);

1333 1334 1335
    pcs = process_find_by_handle(process);
    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 1339 1340
    if (base) *base = fmap.u.macho.segs_start;
    *size = fmap.u.macho.segs_size;
    *checksum = calc_crc32(fmap.u.macho.fd);
1341 1342 1343 1344
    macho_unmap_file(&fmap);
    return TRUE;
}

1345 1346 1347 1348 1349
/******************************************************************
 *              macho_module_remove
 */
static void macho_module_remove(struct process* pcs, struct module_format* modfmt)
{
1350
    macho_unmap_file(&modfmt->u.macho_info->file_map);
1351 1352 1353
    HeapFree(GetProcessHeap(), 0, modfmt);
}

1354 1355 1356 1357 1358 1359 1360 1361 1362

/******************************************************************
 *              get_dyld_image_info_address
 */
static ULONG_PTR get_dyld_image_info_address(struct process* pcs)
{
    NTSTATUS status;
    PROCESS_BASIC_INFORMATION pbi;
    ULONG_PTR dyld_image_info_address = 0;
1363
    BOOL ret;
1364 1365 1366 1367 1368 1369

    /* Get address of PEB */
    status = NtQueryInformationProcess(pcs->handle, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
    if (status == STATUS_SUCCESS)
    {
        /* Read dyld image info address from PEB */
1370 1371 1372 1373
        if (!pcs->is_64bit)
            ret = ReadProcessMemory(pcs->handle, &pbi.PebBaseAddress->Reserved[0],
                &dyld_image_info_address, sizeof(dyld_image_info_address), NULL);
        else
1374
        {
1375 1376 1377 1378 1379
            PEB32 *peb32 = (PEB32 *)pbi.PebBaseAddress;
            ULONG addr32;
            ret = ReadProcessMemory(pcs->handle, &peb32->Reserved[0], &addr32,
                sizeof(addr32), NULL);
            dyld_image_info_address = addr32;
1380
        }
1381 1382 1383 1384

        if (ret)
            TRACE("got dyld_image_info_address %#lx from PEB %p\n",
                dyld_image_info_address, pbi.PebBaseAddress);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
    }

#ifndef __LP64__ /* No reading the symtab with nlist(3) in LP64 */
    if (!dyld_image_info_address)
    {
        static void* dyld_all_image_infos_addr;

        /* Our next best guess is that dyld was loaded at its base address
           and we can find the dyld image infos address by looking up its symbol. */
        if (!dyld_all_image_infos_addr)
        {
            struct nlist nl[2];
            memset(nl, 0, sizeof(nl));
            nl[0].n_un.n_name = (char*)"_dyld_all_image_infos";
            if (!nlist("/usr/lib/dyld", nl))
                dyld_all_image_infos_addr = (void*)nl[0].n_value;
        }

        if (dyld_all_image_infos_addr)
        {
            TRACE("got dyld_image_info_address %p from /usr/lib/dyld symbol table\n",
                  dyld_all_image_infos_addr);
            dyld_image_info_address = (ULONG_PTR)dyld_all_image_infos_addr;
        }
    }
#endif

    return dyld_image_info_address;
}

1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
/******************************************************************
 *              macho_load_file
 *
 * Loads the information for Mach-O module stored in 'filename'.
 * The module has been loaded at 'load_addr' address.
 * returns
 *      FALSE if the file cannot be found/opened or if the file doesn't
 *              contain symbolic info (or this info cannot be read or parsed)
 *      TRUE on success
 */
static BOOL macho_load_file(struct process* pcs, const WCHAR* filename,
                            unsigned long load_addr, struct macho_info* macho_info)
{
    BOOL                    ret = TRUE;
1429
    BOOL                    split_segs;
1430
    struct image_file_map   fmap;
1431 1432 1433 1434

    TRACE("(%p/%p, %s, 0x%08lx, %p/0x%08x)\n", pcs, pcs->handle, debugstr_w(filename),
            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;
1437 1438 1439 1440 1441

    /* Find the dynamic loader's table of images loaded into the process.
     */
    if (macho_info->flags & MACHO_INFO_DEBUG_HEADER)
    {
1442 1443
        macho_info->dbg_hdr_addr = (unsigned long)get_dyld_image_info_address(pcs);
        ret = TRUE;
1444 1445 1446 1447
    }

    if (macho_info->flags & MACHO_INFO_MODULE)
    {
1448 1449 1450 1451
        struct macho_module_info *macho_module_info;
        struct module_format*   modfmt =
            HeapAlloc(GetProcessHeap(), 0, sizeof(struct module_format) + sizeof(struct macho_module_info));
        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 1457
        if (!macho_info->module)
        {
1458
            HeapFree(GetProcessHeap(), 0, modfmt);
1459 1460
            goto leave;
        }
1461
        macho_info->module->reloc_delta = macho_info->module->module.BaseOfImage - fmap.u.macho.segs_start;
1462 1463 1464 1465
        macho_module_info = (void*)(modfmt + 1);
        macho_info->module->format_info[DFI_MACHO] = modfmt;

        modfmt->module       = macho_info->module;
1466
        modfmt->remove       = macho_module_remove;
1467 1468 1469 1470
        modfmt->loc_compute  = NULL;
        modfmt->u.macho_info = macho_module_info;

        macho_module_info->load_addr = load_addr;
1471

1472 1473
        macho_module_info->file_map = fmap;
        reset_file_map(&fmap);
1474 1475
        if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
            macho_info->module->module.SymType = SymDeferred;
1476
        else if (!macho_load_debug_info(pcs, macho_info->module))
1477 1478
            ret = FALSE;

1479 1480
        macho_info->module->format_info[DFI_MACHO]->u.macho_info->in_use = 1;
        macho_info->module->format_info[DFI_MACHO]->u.macho_info->is_loader = 0;
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
        TRACE("module = %p\n", macho_info->module);
    }

    if (macho_info->flags & MACHO_INFO_NAME)
    {
        WCHAR*  ptr;
        ptr = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(filename) + 1) * sizeof(WCHAR));
        if (ptr)
        {
            strcpyW(ptr, filename);
            macho_info->module_name = ptr;
        }
        else ret = FALSE;
        TRACE("module_name = %p %s\n", macho_info->module_name, debugstr_w(macho_info->module_name));
    }
leave:
    macho_unmap_file(&fmap);

    TRACE(" => %d\n", ret);
    return ret;
}

/******************************************************************
 *              macho_load_file_from_path
 * 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 1509 1510 1511 1512 1513 1514 1515 1516 1517
                                      const WCHAR* filename,
                                      unsigned long load_addr,
                                      const char* path,
                                      struct macho_info* macho_info)
{
    BOOL                ret = FALSE;
    WCHAR               *s, *t, *fn;
    WCHAR*              pathW = NULL;
    unsigned            len;

1518
    TRACE("(%p/%p, %s, 0x%08lx, %s, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
            debugstr_a(path), macho_info);

    if (!path) return FALSE;

    len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
    pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
    if (!pathW) return FALSE;
    MultiByteToWideChar(CP_UNIXCP, 0, path, -1, pathW, len);

    for (s = pathW; s && *s; s = (t) ? (t+1) : NULL)
    {
        t = strchrW(s, ':');
        if (t) *t = '\0';
        fn = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(filename) + 1 + lstrlenW(s) + 1) * sizeof(WCHAR));
        if (!fn) break;
        strcpyW(fn, s);
        strcatW(fn, S_SlashW);
        strcatW(fn, filename);
1537
        ret = macho_load_file(pcs, fn, load_addr, macho_info);
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
        HeapFree(GetProcessHeap(), 0, fn);
        if (ret) break;
        s = (t) ? (t+1) : NULL;
    }

    TRACE(" => %d\n", ret);
    HeapFree(GetProcessHeap(), 0, pathW);
    return ret;
}

/******************************************************************
 *              macho_load_file_from_dll_path
 *
 * Tries to load a Mach-O file from the dll path
 */
1553
static BOOL macho_load_file_from_dll_path(struct process* pcs,
1554 1555 1556 1557 1558 1559 1560 1561
                                          const WCHAR* filename,
                                          unsigned long load_addr,
                                          struct macho_info* macho_info)
{
    BOOL ret = FALSE;
    unsigned int index = 0;
    const char *path;

1562
    TRACE("(%p/%p, %s, 0x%08lx, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
            macho_info);

    while (!ret && (path = wine_dll_enum_load_path( index++ )))
    {
        WCHAR *name;
        unsigned len;

        len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);

        name = HeapAlloc( GetProcessHeap(), 0,
                          (len + lstrlenW(filename) + 2) * sizeof(WCHAR) );

        if (!name) break;
        MultiByteToWideChar(CP_UNIXCP, 0, path, -1, name, len);
        strcatW( name, S_SlashW );
        strcatW( name, filename );
1579
        ret = macho_load_file(pcs, name, load_addr, macho_info);
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
        HeapFree( GetProcessHeap(), 0, name );
    }
    TRACE(" => %d\n", ret);
    return ret;
}

/******************************************************************
 *              macho_search_and_load_file
 *
 * Lookup a file in standard Mach-O locations, and if found, load it
 */
static BOOL macho_search_and_load_file(struct process* pcs, const WCHAR* filename,
                                       unsigned long load_addr,
                                       struct macho_info* macho_info)
{
    BOOL                ret = FALSE;
    struct module*      module;
1597
    static const WCHAR  S_libstdcPPW[] = {'l','i','b','s','t','d','c','+','+','\0'};
1598 1599 1600 1601 1602 1603 1604 1605 1606
    const WCHAR*        p;

    TRACE("(%p/%p, %s, 0x%08lx, %p)\n", pcs, pcs->handle, debugstr_w(filename), load_addr,
            macho_info);

    if (filename == NULL || *filename == '\0') return FALSE;
    if ((module = module_is_already_loaded(pcs, filename)))
    {
        macho_info->module = module;
1607
        module->format_info[DFI_MACHO]->u.macho_info->in_use = 1;
1608 1609 1610 1611 1612
        return module->module.SymType;
    }

    if (strstrW(filename, S_libstdcPPW)) return FALSE; /* We know we can't do it */

1613
    /* If has no directories, try PATH first. */
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
    if (!strchrW(filename, '/'))
    {
        ret = macho_load_file_from_path(pcs, filename, load_addr,
                                      getenv("PATH"), macho_info);
    }
    /* Try DYLD_LIBRARY_PATH, with just the filename (no directories). */
    if (!ret)
    {
        if ((p = strrchrW(filename, '/'))) p++;
        else p = filename;
        ret = macho_load_file_from_path(pcs, p, load_addr,
                                      getenv("DYLD_LIBRARY_PATH"), macho_info);
    }
    /* Try the path as given. */
    if (!ret)
        ret = macho_load_file(pcs, filename, load_addr, macho_info);
    /* Try DYLD_FALLBACK_LIBRARY_PATH, with just the filename (no directories). */
    if (!ret)
    {
1633 1634 1635 1636
        const char* fallback = getenv("DYLD_FALLBACK_LIBRARY_PATH");
        if (!fallback)
            fallback = "/usr/local/lib:/lib:/usr/lib";
        ret = macho_load_file_from_path(pcs, p, load_addr, fallback, macho_info);
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
    }
    if (!ret && !strchrW(filename, '/'))
        ret = macho_load_file_from_dll_path(pcs, filename, load_addr, macho_info);

    return ret;
}

/******************************************************************
 *              macho_enum_modules_internal
 *
 * Enumerate Mach-O modules from a running process
 */
static BOOL macho_enum_modules_internal(const struct process* pcs,
                                        const WCHAR* main_name,
                                        enum_modules_cb cb, void* user)
{
    struct dyld_all_image_infos image_infos;
    struct dyld_image_info*     info_array = NULL;
    unsigned long               len;
    int                         i;
    char                        bufstr[256];
    WCHAR                       bufstrW[MAX_PATH];
    BOOL                        ret = FALSE;

    TRACE("(%p/%p, %s, %p, %p)\n", pcs, pcs->handle, debugstr_w(main_name), cb,
            user);

    if (!pcs->dbg_hdr_addr ||
        !ReadProcessMemory(pcs->handle, (void*)pcs->dbg_hdr_addr,
                           &image_infos, sizeof(image_infos), NULL) ||
        !image_infos.infoArray)
        goto done;
    TRACE("Process has %u image infos at %p\n", image_infos.infoArrayCount, image_infos.infoArray);

    len = image_infos.infoArrayCount * sizeof(info_array[0]);
    info_array = HeapAlloc(GetProcessHeap(), 0, len);
    if (!info_array ||
        !ReadProcessMemory(pcs->handle, image_infos.infoArray,
                           info_array, len, NULL))
        goto done;
    TRACE("... read image infos\n");

    for (i = 0; i < image_infos.infoArrayCount; i++)
    {
        if (info_array[i].imageFilePath != NULL &&
            ReadProcessMemory(pcs->handle, info_array[i].imageFilePath, bufstr, sizeof(bufstr), NULL))
        {
            bufstr[sizeof(bufstr) - 1] = '\0';
            TRACE("[%d] image file %s\n", i, debugstr_a(bufstr));
1686
            MultiByteToWideChar(CP_UNIXCP, 0, bufstr, -1, bufstrW, ARRAY_SIZE(bufstrW));
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
            if (main_name && !bufstrW[0]) strcpyW(bufstrW, main_name);
            if (!cb(bufstrW, (unsigned long)info_array[i].imageLoadAddress, user)) break;
        }
    }

    ret = TRUE;
done:
    HeapFree(GetProcessHeap(), 0, info_array);
    return ret;
}

struct macho_sync
{
    struct process*     pcs;
    struct macho_info   macho_info;
};

static BOOL macho_enum_sync_cb(const WCHAR* name, unsigned long addr, void* user)
{
    struct macho_sync*  ms = user;

    TRACE("(%s, 0x%08lx, %p)\n", debugstr_w(name), addr, user);
    macho_search_and_load_file(ms->pcs, name, addr, &ms->macho_info);
    return TRUE;
}

/******************************************************************
 *              macho_synchronize_module_list
 *
 * Rescans the debuggee's modules list and synchronizes it with
 * the one from 'pcs', ie:
 * - if a module is in debuggee and not in pcs, it's loaded into pcs
 * - if a module is in pcs and not in debuggee, it's unloaded from pcs
 */
BOOL    macho_synchronize_module_list(struct process* pcs)
{
    struct module*      module;
    struct macho_sync     ms;

    TRACE("(%p/%p)\n", pcs, pcs->handle);

    for (module = pcs->lmodules; module; module = module->next)
    {
        if (module->type == DMT_MACHO && !module->is_virtual)
1731
            module->format_info[DFI_MACHO]->u.macho_info->in_use = 0;
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
    }

    ms.pcs = pcs;
    ms.macho_info.flags = MACHO_INFO_MODULE;
    if (!macho_enum_modules_internal(pcs, NULL, macho_enum_sync_cb, &ms))
        return FALSE;

    module = pcs->lmodules;
    while (module)
    {
        if (module->type == DMT_MACHO && !module->is_virtual &&
1743 1744
            !module->format_info[DFI_MACHO]->u.macho_info->in_use &&
            !module->format_info[DFI_MACHO]->u.macho_info->is_loader)
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
        {
            module_remove(pcs, module);
            /* restart all over */
            module = pcs->lmodules;
        }
        else module = module->next;
    }
    return TRUE;
}

/******************************************************************
 *              macho_search_loader
 *
 * Lookup in a running Mach-O process the loader, and sets its Mach-O link
 * address (for accessing the list of loaded images) in pcs.
 * If flags is MACHO_INFO_MODULE, the module for the loader is also
 * added as a module into pcs.
 */
static BOOL macho_search_loader(struct process* pcs, struct macho_info* macho_info)
{
1765
    WCHAR *loader = get_wine_loader_name(pcs);
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
    BOOL ret = FALSE;
    ULONG_PTR dyld_image_info_address;
    struct dyld_all_image_infos image_infos;
    struct dyld_image_info image_info;
    uint32_t len;
    char path[PATH_MAX];
    BOOL got_path = FALSE;

    dyld_image_info_address = get_dyld_image_info_address(pcs);
    if (dyld_image_info_address &&
        ReadProcessMemory(pcs->handle, (void*)dyld_image_info_address, &image_infos, sizeof(image_infos), NULL) &&
        image_infos.infoArray && image_infos.infoArrayCount &&
        ReadProcessMemory(pcs->handle, image_infos.infoArray, &image_info, sizeof(image_info), NULL) &&
        image_info.imageFilePath)
    {
        for (len = sizeof(path); len > 0; len /= 2)
        {
            if (ReadProcessMemory(pcs->handle, image_info.imageFilePath, path, len, NULL))
            {
                path[len - 1] = 0;
                got_path = TRUE;
                TRACE("got executable path from target's dyld image info: %s\n", debugstr_a(path));
                break;
            }
        }
    }

    /* If we couldn't get the executable path from the target process, try our
       own.  It will almost always be the same. */
    if (!got_path)
    {
        len = sizeof(path);
        if (!_NSGetExecutablePath(path, &len))
        {
            got_path = TRUE;
            TRACE("using own executable path: %s\n", debugstr_a(path));
        }
    }

    if (got_path)
    {
        WCHAR* pathW;

        len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
        pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        if (pathW)
        {
            MultiByteToWideChar(CP_UNIXCP, 0, path, -1, pathW, len);
            ret = macho_load_file(pcs, pathW, 0, macho_info);
            HeapFree(GetProcessHeap(), 0, pathW);
        }
    }

    if (!ret)
1820 1821
        ret = macho_search_and_load_file(pcs, loader, 0, macho_info);
    heap_free(loader);
1822
    return ret;
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
}

/******************************************************************
 *              macho_read_wine_loader_dbg_info
 *
 * Try to find a decent wine executable which could have loaded the debuggee
 */
BOOL macho_read_wine_loader_dbg_info(struct process* pcs)
{
    struct macho_info     macho_info;

    TRACE("(%p/%p)\n", pcs, pcs->handle);
    macho_info.flags = MACHO_INFO_DEBUG_HEADER | MACHO_INFO_MODULE;
    if (!macho_search_loader(pcs, &macho_info)) return FALSE;
1837
    macho_info.module->format_info[DFI_MACHO]->u.macho_info->is_loader = 1;
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
    module_set_module(macho_info.module, S_WineLoaderW);
    return (pcs->dbg_hdr_addr = macho_info.dbg_hdr_addr) != 0;
}

/******************************************************************
 *              macho_enum_modules
 *
 * Enumerates the Mach-O loaded modules from a running target (hProc)
 * This function doesn't require that someone has called SymInitialize
 * on this very process.
 */
BOOL macho_enum_modules(HANDLE hProc, enum_modules_cb cb, void* user)
{
    struct process      pcs;
    struct macho_info   macho_info;
    BOOL                ret;

    TRACE("(%p, %p, %p)\n", hProc, cb, user);
    memset(&pcs, 0, sizeof(pcs));
    pcs.handle = hProc;
    macho_info.flags = MACHO_INFO_DEBUG_HEADER | MACHO_INFO_NAME;
    if (!macho_search_loader(&pcs, &macho_info)) return FALSE;
    pcs.dbg_hdr_addr = macho_info.dbg_hdr_addr;
    ret = macho_enum_modules_internal(&pcs, macho_info.module_name, cb, user);
    HeapFree(GetProcessHeap(), 0, (char*)macho_info.module_name);
    return ret;
}

struct macho_load
{
    struct process*     pcs;
    struct macho_info   macho_info;
    const WCHAR*        name;
    BOOL                ret;
};

/******************************************************************
 *              macho_load_cb
 *
 * Callback for macho_load_module, used to walk the list of loaded
 * modules.
 */
static BOOL macho_load_cb(const WCHAR* name, unsigned long addr, void* user)
{
    struct macho_load*  ml = user;
    const WCHAR*        p;

    TRACE("(%s, 0x%08lx, %p)\n", debugstr_w(name), addr, user);

    /* memcmp is needed for matches when bufstr contains also version information
     * ml->name: libc.so, name: libc.so.6.0
     */
    p = strrchrW(name, '/');
    if (!p++) p = name;
    if (!memcmp(p, ml->name, lstrlenW(ml->name) * sizeof(WCHAR)))
    {
        ml->ret = macho_search_and_load_file(ml->pcs, name, addr, &ml->macho_info);
        return FALSE;
    }
    return TRUE;
}

/******************************************************************
 *              macho_load_module
 *
 * Loads a Mach-O module and stores it in process' module list.
 * Also, find module real name and load address from
 * the real loaded modules list in pcs address space.
 */
struct module*  macho_load_module(struct process* pcs, const WCHAR* name, unsigned long addr)
{
    struct macho_load   ml;

    TRACE("(%p/%p, %s, 0x%08lx)\n", pcs, pcs->handle, debugstr_w(name), addr);

    ml.macho_info.flags = MACHO_INFO_MODULE;
    ml.ret = FALSE;

    if (pcs->dbg_hdr_addr) /* we're debugging a live target */
    {
        ml.pcs = pcs;
        /* do only the lookup from the filename, not the path (as we lookup module
         * name in the process' loaded module list)
         */
        ml.name = strrchrW(name, '/');
        if (!ml.name++) ml.name = name;
        ml.ret = FALSE;

        if (!macho_enum_modules_internal(pcs, NULL, macho_load_cb, &ml))
            return NULL;
    }
    else if (addr)
    {
        ml.name = name;
        ml.ret = macho_search_and_load_file(pcs, ml.name, addr, &ml.macho_info);
    }
    if (!ml.ret) return NULL;
    assert(ml.macho_info.module);
    return ml.macho_info.module;
}

1939
#else  /* HAVE_MACH_O_LOADER_H */
1940

1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
BOOL macho_find_section(struct image_file_map* ifm, const char* segname, const char* sectname, struct image_section_map* ism)
{
    return FALSE;
}

const char* macho_map_section(struct image_section_map* ism)
{
    return NULL;
}

void macho_unmap_section(struct image_section_map* ism)
{
}

DWORD_PTR macho_get_map_rva(const struct image_section_map* ism)
{
    return 0;
}

unsigned macho_get_map_size(const struct image_section_map* ism)
{
    return 0;
}

1965 1966 1967 1968 1969
BOOL    macho_synchronize_module_list(struct process* pcs)
{
    return FALSE;
}

1970
BOOL macho_fetch_file_info(HANDLE process, const WCHAR* name, unsigned long load_addr, DWORD_PTR* base,
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
                           DWORD* size, DWORD* checksum)
{
    return FALSE;
}

BOOL macho_read_wine_loader_dbg_info(struct process* pcs)
{
    return FALSE;
}

BOOL macho_enum_modules(HANDLE hProc, enum_modules_cb cb, void* user)
{
    return FALSE;
}

struct module*  macho_load_module(struct process* pcs, const WCHAR* name, unsigned long addr)
{
    return NULL;
}

1991
BOOL macho_load_debug_info(struct process *pcs, struct module* module)
1992 1993 1994
{
    return FALSE;
}
1995
#endif  /* HAVE_MACH_O_LOADER_H */