1/*
2 * Copyright (c) 2013-2015 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24#include "trace_internal.h"
25#include <mach-o/loader.h>
26#include <string.h>
27
28static bool
29_os_trace_addr_in_text_segment_32(const void *dso, const void *addr)
30{
31 const struct mach_header *mhp = (const struct mach_header *) dso;
32 const struct segment_command *sgp = (const struct segment_command *)(const void *)((const char *)mhp + sizeof(struct mach_header));
33
34 for (uint32_t i = 0; i < mhp->ncmds; i++) {
35 if (sgp->cmd == LC_SEGMENT) {
36 if (strncmp(s1: sgp->segname, SEG_TEXT, n: sizeof(sgp->segname)) == 0) {
37 return (uintptr_t)addr >= (sgp->vmaddr) && (uintptr_t)addr < (sgp->vmaddr + sgp->vmsize);
38 }
39 }
40 sgp = (const struct segment_command *)(const void *)((const char *)sgp + sgp->cmdsize);
41 }
42
43 return false;
44}
45
46static bool
47_os_trace_addr_in_text_segment_64(const void *dso, const void *addr)
48{
49 const struct mach_header_64 *mhp = (const struct mach_header_64 *) dso;
50 const struct segment_command_64 *sgp = (const struct segment_command_64 *)(const void *)((const char *)mhp + sizeof(struct mach_header_64));
51
52 for (uint32_t i = 0; i < mhp->ncmds; i++) {
53 if (sgp->cmd == LC_SEGMENT_64) {
54 if (strncmp(s1: sgp->segname, SEG_TEXT, n: sizeof(sgp->segname)) == 0) {
55 return (uintptr_t)addr >= (sgp->vmaddr) && (uintptr_t)addr < (sgp->vmaddr + sgp->vmsize);
56 }
57 }
58 sgp = (const struct segment_command_64 *)(const void *)((const char *)sgp + sgp->cmdsize);
59 }
60
61 return false;
62}
63
64bool
65_os_trace_addr_in_text_segment(const void *dso, const void *addr)
66{
67 const struct mach_header *mhp = (const struct mach_header *) dso;
68 bool retval = false;
69
70 switch (mhp->magic) {
71 case MH_MAGIC:
72 retval = _os_trace_addr_in_text_segment_32(dso, addr);
73 break;
74
75 case MH_MAGIC_64:
76 retval = _os_trace_addr_in_text_segment_64(dso, addr);
77 break;
78
79 default:
80 retval = false;
81 break;
82 }
83
84 return retval;
85}
86