2 * Copyright (c) 2000,2008-2009 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1997 Apple Inc.
32 #include <libkern/c++/OSMetaClass.h>
33 #include <libkern/c++/OSKext.h>
34 #include <libkern/c++/OSLib.h>
35 #include <libkern/c++/OSSymbol.h>
36 #include <IOKit/IOKitDebug.h>
38 #include <sys/cdefs.h>
39 #if defined(HAS_APPLE_PAC)
41 #define PTRAUTH_STRIP_STRUCTOR(x) ((uintptr_t) ptrauth_strip(ptrauth_nop_cast(void *, (x)), ptrauth_key_function_pointer))
42 #else /* defined(HAS_APPLE_PAC) */
43 #define PTRAUTH_STRIP_STRUCTOR(x) ((uintptr_t) (x))
44 #endif /* !defined(HAS_APPLE_PAC) */
49 #include <mach/mach_types.h>
50 #include <libkern/kernel_mach_header.h>
51 #include <libkern/prelink.h>
55 #include <san/kasan.h>
59 #pragma mark Constants &c.
60 #endif /* PRAGMA_MARK */
61 OSKextLogSpec kOSRuntimeLogSpec
=
62 kOSKextLogErrorLevel
|
64 kOSKextLogKextBookkeepingFlag
;
67 #pragma mark Logging Bootstrap
68 #endif /* PRAGMA_MARK */
69 /*********************************************************************
70 * kern_os Logging Bootstrap
72 * We can't call in to OSKext until the kernel's C++ environment is up
73 * and running, so let's mask those references with a check variable.
74 * We print unconditionally if C++ isn't up, but if that's the case
75 * we've generally hit a serious error in kernel init!
76 *********************************************************************/
77 static bool gKernelCPPInitialized
= false;
79 #define OSRuntimeLog(kext, flags, format, args ...) \
81 if (gKernelCPPInitialized) { \
82 OSKextLog((kext), (flags), (format), ## args); \
84 printf((format), ## args); \
89 #pragma mark Libkern Init
90 #endif /* PRAGMA_MARK */
91 /*********************************************************************
93 *********************************************************************/
97 __cxa_pure_virtual( void )
99 panic("%s", __FUNCTION__
);
103 __pure_virtual( void )
105 panic("%s", __FUNCTION__
);
109 extern lck_grp_t
* IOLockGroup
;
110 extern kmod_info_t g_kernel_kmod_info
;
113 kOSSectionNamesDefault
= 0,
114 kOSSectionNamesBuiltinKext
= 1,
115 kOSSectionNamesCount
= 2,
118 kOSSectionNameInitializer
= 0,
119 kOSSectionNameFinalizer
= 1,
120 kOSSectionNameCount
= 2
124 gOSStructorSectionNames
[kOSSectionNamesCount
][kOSSectionNameCount
] = {
125 { SECT_MODINITFUNC
, SECT_MODTERMFUNC
},
126 { kBuiltinInitSection
, kBuiltinTermSection
}
132 // This must be called before calling OSRuntimeInitializeCPP.
133 OSMetaClassBase::initialize();
135 g_kernel_kmod_info
.address
= (vm_address_t
) &_mh_execute_header
;
136 if (kOSReturnSuccess
!= OSRuntimeInitializeCPP(NULL
)) {
137 // &g_kernel_kmod_info, gOSSectionNamesStandard, 0, 0)) {
138 panic("OSRuntime: C++ runtime failed to initialize.");
141 gKernelCPPInitialized
= true;
149 #pragma mark C++ Runtime Load/Unload
150 #endif /* PRAGMA_MARK */
151 /*********************************************************************
152 * kern_os C++ Runtime Load/Unload
153 *********************************************************************/
155 typedef void (*structor_t
)(void);
158 OSRuntimeCallStructorsInSection(
160 kmod_info_t
* kmodInfo
,
162 kernel_segment_command_t
* segment
,
163 const char * sectionName
,
167 kernel_section_t
* section
;
170 for (section
= firstsect(segment
);
172 section
= nextsect(segment
, section
)) {
173 if (strncmp(section
->sectname
, sectionName
, sizeof(section
->sectname
) - 1)) {
176 if (section
->size
== 0) {
180 structor_t
* structors
= (structor_t
*)section
->addr
;
187 unsigned long num_structors
= section
->size
/ sizeof(structor_t
);
188 unsigned int hit_null_structor
= 0;
189 unsigned long firstIndex
= 0;
192 // bsearch for any in range
193 unsigned long baseIdx
;
195 firstIndex
= num_structors
;
196 for (lim
= num_structors
, baseIdx
= 0; lim
; lim
>>= 1) {
197 structor
= structors
[baseIdx
+ (lim
>> 1)];
199 panic("%s: null structor", kmodInfo
->name
);
201 value
= PTRAUTH_STRIP_STRUCTOR(structor
);
202 if ((value
>= textStart
) && (value
< textEnd
)) {
203 firstIndex
= (baseIdx
+ (lim
>> 1));
204 // scan back for the first in range
205 for (; firstIndex
; firstIndex
--) {
206 structor
= structors
[firstIndex
- 1];
207 value
= PTRAUTH_STRIP_STRUCTOR(structor
);
208 if ((value
< textStart
) || (value
>= textEnd
)) {
214 if (textStart
> value
) {
216 baseIdx
+= (lim
>> 1) + 1;
221 baseIdx
= (baseIdx
+ (lim
>> 1));
224 (firstIndex
< num_structors
)
225 && (!metaHandle
|| OSMetaClass::checkModLoad(metaHandle
));
227 if ((structor
= structors
[firstIndex
])) {
228 value
= PTRAUTH_STRIP_STRUCTOR(structor
);
229 if ((textStart
&& (value
< textStart
))
230 || (textEnd
&& (value
>= textEnd
))) {
234 } else if (!hit_null_structor
) {
235 hit_null_structor
= 1;
236 OSRuntimeLog(theKext
, kOSRuntimeLogSpec
,
237 "Null structor in kext %s segment %s!",
238 kmodInfo
->name
, section
->segname
);
242 result
= OSMetaClass::checkModLoad(metaHandle
);
245 } /* for (section...) */
249 /*********************************************************************
250 *********************************************************************/
252 OSRuntimeFinalizeCPP(
255 kern_return_t result
= KMOD_RETURN_FAILURE
;
256 void * metaHandle
= NULL
;// do not free
257 kernel_mach_header_t
* header
;
258 kernel_segment_command_t
* segment
;
259 kmod_info_t
* kmodInfo
;
260 const char ** sectionNames
;
266 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesDefault
];
268 if (!theKext
->isCPPInitialized()) {
269 result
= KMOD_RETURN_SUCCESS
;
272 kmodInfo
= theKext
->kmod_info
;
273 if (!kmodInfo
|| !kmodInfo
->address
) {
274 result
= kOSKextReturnInvalidArgument
;
277 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
278 if (theKext
->flags
.builtin
) {
279 header
= (kernel_mach_header_t
*)g_kernel_kmod_info
.address
;
280 textStart
= kmodInfo
->address
;
281 textEnd
= textStart
+ kmodInfo
->size
;
282 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesBuiltinKext
];
285 kmodInfo
= &g_kernel_kmod_info
;
286 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
289 /* OSKext checks for this condition now, but somebody might call
290 * this function directly (the symbol is exported....).
292 if (OSMetaClass::modHasInstance(kmodInfo
->name
)) {
293 // xxx - Don't log under errors? this is more of an info thing
294 OSRuntimeLog(theKext
, kOSRuntimeLogSpec
,
295 "Can't tear down kext %s C++; classes have instances:",
297 OSKext::reportOSMetaClassInstances(kmodInfo
->name
, kOSRuntimeLogSpec
);
298 result
= kOSMetaClassHasInstances
;
302 /* Tell the meta class system that we are starting to unload.
303 * metaHandle isn't actually needed on the finalize path,
304 * so we don't check it here, even though OSMetaClass::postModLoad() will
305 * return a failure (it only does actual work on the init path anyhow).
307 metaHandle
= OSMetaClass::preModLoad(kmodInfo
->name
);
309 OSSymbol::checkForPageUnload((void *)kmodInfo
->address
,
310 (void *)(kmodInfo
->address
+ kmodInfo
->size
));
312 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
313 segment
= firstsegfromheader(header
);
315 for (segment
= firstsegfromheader(header
);
317 segment
= nextsegfromheader(header
, segment
)) {
318 OSRuntimeCallStructorsInSection(theKext
, kmodInfo
, NULL
, segment
,
319 sectionNames
[kOSSectionNameFinalizer
], textStart
, textEnd
);
322 (void)OSMetaClass::postModLoad(metaHandle
);
325 theKext
->setCPPInitialized(false);
327 result
= KMOD_RETURN_SUCCESS
;
332 #if defined(HAS_APPLE_PAC)
335 * Place this function in __KLD,__text on non-kasan builds so it gets unmapped
336 * after CTRR lockdown.
338 __attribute__((noinline
, section("__KLD,__text")))
341 OSRuntimeSignStructorsInSegment(kernel_segment_command_t
*segment
)
343 kernel_section_t
* section
;
344 structor_t
* structors
;
345 volatile structor_t structor
;
346 size_t idx
, num_structors
;
348 for (section
= firstsect(segment
);
350 section
= nextsect(segment
, section
)) {
351 if ((S_MOD_INIT_FUNC_POINTERS
!= (SECTION_TYPE
& section
->flags
))
352 && (S_MOD_TERM_FUNC_POINTERS
!= (SECTION_TYPE
& section
->flags
))) {
355 structors
= (structor_t
*)section
->addr
;
359 num_structors
= section
->size
/ sizeof(structor_t
);
360 for (idx
= 0; idx
< num_structors
; idx
++) {
361 structor
= structors
[idx
];
362 if (NULL
== structor
) {
365 structor
= ptrauth_strip(structor
, ptrauth_key_function_pointer
);
366 structor
= ptrauth_sign_unauthenticated(structor
, ptrauth_key_function_pointer
, ptrauth_function_pointer_type_discriminator(void (*)(void)));
367 structors
[idx
] = structor
;
369 } /* for (section...) */
373 /*********************************************************************
374 *********************************************************************/
376 OSRuntimeSignStructors(
377 kernel_mach_header_t
* header __unused
)
379 #if defined(HAS_APPLE_PAC)
381 kernel_segment_command_t
* segment
;
383 for (segment
= firstsegfromheader(header
);
385 segment
= nextsegfromheader(header
, segment
)) {
386 OSRuntimeSignStructorsInSegment(segment
);
387 } /* for (segment...) */
388 #endif /* !defined(XXX) && defined(HAS_APPLE_PAC) */
391 /*********************************************************************
392 *********************************************************************/
394 OSRuntimeSignStructorsInFileset(
395 kernel_mach_header_t
* fileset_header __unused
)
397 #if defined(HAS_APPLE_PAC)
398 struct load_command
*lc
;
400 lc
= (struct load_command
*)((uintptr_t)fileset_header
+ sizeof(*fileset_header
));
401 for (uint32_t i
= 0; i
< fileset_header
->ncmds
; i
++,
402 lc
= (struct load_command
*)((uintptr_t)lc
+ lc
->cmdsize
)) {
403 if (lc
->cmd
== LC_FILESET_ENTRY
) {
404 struct fileset_entry_command
*fse
;
405 kernel_mach_header_t
*mh
;
407 fse
= (struct fileset_entry_command
*)(uintptr_t)lc
;
408 mh
= (kernel_mach_header_t
*)((uintptr_t)fse
->vmaddr
);
409 OSRuntimeSignStructors(mh
);
410 } else if (lc
->cmd
== LC_SEGMENT_64
) {
412 * Slide/adjust all LC_SEGMENT_64 commands in the fileset
413 * (and any sections in those segments)
415 kernel_segment_command_t
*seg
;
416 seg
= (kernel_segment_command_t
*)(uintptr_t)lc
;
417 OSRuntimeSignStructorsInSegment(seg
);
421 #endif /* defined(HAS_APPLE_PAC) */
424 /*********************************************************************
425 *********************************************************************/
427 OSRuntimeInitializeCPP(
430 kern_return_t result
= KMOD_RETURN_FAILURE
;
431 kernel_mach_header_t
* header
= NULL
;
432 void * metaHandle
= NULL
;// do not free
433 bool load_success
= true;
434 kernel_segment_command_t
* segment
= NULL
;// do not free
435 kernel_segment_command_t
* failure_segment
= NULL
; // do not free
436 kmod_info_t
* kmodInfo
;
437 const char ** sectionNames
;
443 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesDefault
];
445 if (theKext
->isCPPInitialized()) {
446 result
= KMOD_RETURN_SUCCESS
;
450 kmodInfo
= theKext
->kmod_info
;
451 if (!kmodInfo
|| !kmodInfo
->address
) {
452 result
= kOSKextReturnInvalidArgument
;
455 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
457 if (theKext
->flags
.builtin
) {
458 header
= (kernel_mach_header_t
*)g_kernel_kmod_info
.address
;
459 textStart
= kmodInfo
->address
;
460 textEnd
= textStart
+ kmodInfo
->size
;
461 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesBuiltinKext
];
464 kmodInfo
= &g_kernel_kmod_info
;
465 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
468 /* Tell the meta class system that we are starting the load
470 metaHandle
= OSMetaClass::preModLoad(kmodInfo
->name
);
476 /* NO GOTO PAST HERE. */
478 /* Scan the header for all constructor sections, in any
479 * segment, and invoke the constructors within those sections.
481 for (segment
= firstsegfromheader(header
);
482 segment
!= NULL
&& load_success
;
483 segment
= nextsegfromheader(header
, segment
)) {
484 /* Record the current segment in the event of a failure.
486 failure_segment
= segment
;
487 load_success
= OSRuntimeCallStructorsInSection(
488 theKext
, kmodInfo
, metaHandle
, segment
,
489 sectionNames
[kOSSectionNameInitializer
],
491 } /* for (segment...) */
493 /* We failed so call all of the destructors. We must do this before
494 * calling OSMetaClass::postModLoad() as the OSMetaClass destructors
495 * will alter state (in the metaHandle) used by that function.
498 /* Scan the header for all destructor sections, in any
499 * segment, and invoke the constructors within those sections.
501 for (segment
= firstsegfromheader(header
);
502 segment
!= failure_segment
&& segment
!= NULL
;
503 segment
= nextsegfromheader(header
, segment
)) {
504 OSRuntimeCallStructorsInSection(theKext
, kmodInfo
, NULL
, segment
,
505 sectionNames
[kOSSectionNameFinalizer
], textStart
, textEnd
);
506 } /* for (segment...) */
509 /* Now, regardless of success so far, do the post-init registration
510 * and cleanup. If we had to call the unloadCPP function, static
511 * destructors have removed classes from the stalled list so no
512 * metaclasses will actually be registered.
514 result
= OSMetaClass::postModLoad(metaHandle
);
516 /* If we've otherwise been fine up to now, but OSMetaClass::postModLoad()
517 * fails (typically due to a duplicate class), tear down all the C++
518 * stuff from the kext. This isn't necessary for libkern/OSMetaClass stuff,
519 * but may be necessary for other C++ code. We ignore the return value
520 * because it's only a fail when there are existing instances of libkern
521 * classes, and there had better not be any created on the C++ init path.
523 if (load_success
&& result
!= KMOD_RETURN_SUCCESS
) {
524 (void)OSRuntimeFinalizeCPP(theKext
); //kmodInfo, sectionNames, textStart, textEnd);
527 if (theKext
&& load_success
&& result
== KMOD_RETURN_SUCCESS
) {
528 theKext
->setCPPInitialized(true);
534 /*********************************************************************
535 * Unload a kernel segment.
536 *********************************************************************/
539 OSRuntimeUnloadCPPForSegment(
540 kernel_segment_command_t
* segment
)
542 OSRuntimeCallStructorsInSection(NULL
, &g_kernel_kmod_info
, NULL
, segment
,
543 gOSStructorSectionNames
[kOSSectionNamesDefault
][kOSSectionNameFinalizer
], 0, 0);
547 #pragma mark C++ Allocators & Deallocators
548 #endif /* PRAGMA_MARK */
549 /*********************************************************************
550 * C++ Allocators & Deallocators
551 *********************************************************************/
553 operator new(size_t size
)
556 return kheap_alloc_tag_bt(KERN_OS_MALLOC
, size
,
557 (zalloc_flags_t
) (Z_WAITOK
| Z_ZERO
), VM_KERN_MEMORY_LIBKERN
);
561 operator delete(void * addr
)
562 #if __cplusplus >= 201103L
566 kheap_free_addr(KERN_OS_MALLOC
, addr
);
571 operator new[](unsigned long sz
)
573 return kheap_alloc_tag_bt(KERN_OS_MALLOC
, sz
,
574 (zalloc_flags_t
) (Z_WAITOK
| Z_ZERO
), VM_KERN_MEMORY_LIBKERN
);
578 operator delete[](void * ptr
)
579 #if __cplusplus >= 201103L
586 * Unpoison the C++ array cookie inserted (but not removed) by the
589 kasan_unpoison_cxx_array_cookie(ptr
);
591 kheap_free_addr(KERN_OS_MALLOC
, ptr
);
596 #if __cplusplus >= 201103L
599 operator delete(void * addr
, size_t sz
) noexcept
601 kheap_free(KERN_OS_MALLOC
, addr
, sz
);
605 operator delete[](void * addr
, size_t sz
) noexcept
608 kheap_free(KERN_OS_MALLOC
, addr
, sz
);
612 #endif /* __cplusplus >= 201103L */
614 /* PR-6481964 - The compiler is going to check for size overflows in calls to
615 * new[], and if there is an overflow, it will call __throw_length_error.
616 * This is an unrecoverable error by the C++ standard, so we must panic here.
618 * We have to put the function inside the std namespace because of how the
619 * compiler expects the name to be mangled.
623 __throw_length_error(const char *msg __unused
)
625 panic("Size of array created by new[] has overflowed");