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)
334 OSRuntimeSignStructorsInSegment(kernel_segment_command_t
*segment
)
336 kernel_section_t
* section
;
337 structor_t
* structors
;
338 volatile structor_t structor
;
339 size_t idx
, num_structors
;
341 for (section
= firstsect(segment
);
343 section
= nextsect(segment
, section
)) {
344 if ((S_MOD_INIT_FUNC_POINTERS
!= (SECTION_TYPE
& section
->flags
))
345 && (S_MOD_TERM_FUNC_POINTERS
!= (SECTION_TYPE
& section
->flags
))) {
348 structors
= (structor_t
*)section
->addr
;
352 num_structors
= section
->size
/ sizeof(structor_t
);
353 for (idx
= 0; idx
< num_structors
; idx
++) {
354 structor
= structors
[idx
];
355 if (NULL
== structor
) {
358 structor
= ptrauth_strip(structor
, ptrauth_key_function_pointer
);
359 structor
= ptrauth_sign_unauthenticated(structor
, ptrauth_key_function_pointer
, ptrauth_function_pointer_type_discriminator(void (*)(void)));
360 structors
[idx
] = structor
;
362 } /* for (section...) */
366 /*********************************************************************
367 *********************************************************************/
369 OSRuntimeSignStructors(
370 kernel_mach_header_t
* header __unused
)
372 #if defined(HAS_APPLE_PAC)
374 kernel_segment_command_t
* segment
;
376 for (segment
= firstsegfromheader(header
);
378 segment
= nextsegfromheader(header
, segment
)) {
379 OSRuntimeSignStructorsInSegment(segment
);
380 } /* for (segment...) */
381 #endif /* !defined(XXX) && defined(HAS_APPLE_PAC) */
384 /*********************************************************************
385 *********************************************************************/
387 OSRuntimeSignStructorsInFileset(
388 kernel_mach_header_t
* fileset_header __unused
)
390 #if defined(HAS_APPLE_PAC)
391 struct load_command
*lc
;
393 lc
= (struct load_command
*)((uintptr_t)fileset_header
+ sizeof(*fileset_header
));
394 for (uint32_t i
= 0; i
< fileset_header
->ncmds
; i
++,
395 lc
= (struct load_command
*)((uintptr_t)lc
+ lc
->cmdsize
)) {
396 if (lc
->cmd
== LC_FILESET_ENTRY
) {
397 struct fileset_entry_command
*fse
;
398 kernel_mach_header_t
*mh
;
400 fse
= (struct fileset_entry_command
*)(uintptr_t)lc
;
401 mh
= (kernel_mach_header_t
*)((uintptr_t)fse
->vmaddr
);
402 OSRuntimeSignStructors(mh
);
403 } else if (lc
->cmd
== LC_SEGMENT_64
) {
405 * Slide/adjust all LC_SEGMENT_64 commands in the fileset
406 * (and any sections in those segments)
408 kernel_segment_command_t
*seg
;
409 seg
= (kernel_segment_command_t
*)(uintptr_t)lc
;
410 OSRuntimeSignStructorsInSegment(seg
);
414 #endif /* defined(HAS_APPLE_PAC) */
417 /*********************************************************************
418 *********************************************************************/
420 OSRuntimeInitializeCPP(
423 kern_return_t result
= KMOD_RETURN_FAILURE
;
424 kernel_mach_header_t
* header
= NULL
;
425 void * metaHandle
= NULL
;// do not free
426 bool load_success
= true;
427 kernel_segment_command_t
* segment
= NULL
;// do not free
428 kernel_segment_command_t
* failure_segment
= NULL
; // do not free
429 kmod_info_t
* kmodInfo
;
430 const char ** sectionNames
;
436 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesDefault
];
438 if (theKext
->isCPPInitialized()) {
439 result
= KMOD_RETURN_SUCCESS
;
443 kmodInfo
= theKext
->kmod_info
;
444 if (!kmodInfo
|| !kmodInfo
->address
) {
445 result
= kOSKextReturnInvalidArgument
;
448 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
450 if (theKext
->flags
.builtin
) {
451 header
= (kernel_mach_header_t
*)g_kernel_kmod_info
.address
;
452 textStart
= kmodInfo
->address
;
453 textEnd
= textStart
+ kmodInfo
->size
;
454 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesBuiltinKext
];
457 kmodInfo
= &g_kernel_kmod_info
;
458 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
461 /* Tell the meta class system that we are starting the load
463 metaHandle
= OSMetaClass::preModLoad(kmodInfo
->name
);
469 /* NO GOTO PAST HERE. */
471 /* Scan the header for all constructor sections, in any
472 * segment, and invoke the constructors within those sections.
474 for (segment
= firstsegfromheader(header
);
475 segment
!= NULL
&& load_success
;
476 segment
= nextsegfromheader(header
, segment
)) {
477 /* Record the current segment in the event of a failure.
479 failure_segment
= segment
;
480 load_success
= OSRuntimeCallStructorsInSection(
481 theKext
, kmodInfo
, metaHandle
, segment
,
482 sectionNames
[kOSSectionNameInitializer
],
484 } /* for (segment...) */
486 /* We failed so call all of the destructors. We must do this before
487 * calling OSMetaClass::postModLoad() as the OSMetaClass destructors
488 * will alter state (in the metaHandle) used by that function.
491 /* Scan the header for all destructor sections, in any
492 * segment, and invoke the constructors within those sections.
494 for (segment
= firstsegfromheader(header
);
495 segment
!= failure_segment
&& segment
!= NULL
;
496 segment
= nextsegfromheader(header
, segment
)) {
497 OSRuntimeCallStructorsInSection(theKext
, kmodInfo
, NULL
, segment
,
498 sectionNames
[kOSSectionNameFinalizer
], textStart
, textEnd
);
499 } /* for (segment...) */
502 /* Now, regardless of success so far, do the post-init registration
503 * and cleanup. If we had to call the unloadCPP function, static
504 * destructors have removed classes from the stalled list so no
505 * metaclasses will actually be registered.
507 result
= OSMetaClass::postModLoad(metaHandle
);
509 /* If we've otherwise been fine up to now, but OSMetaClass::postModLoad()
510 * fails (typically due to a duplicate class), tear down all the C++
511 * stuff from the kext. This isn't necessary for libkern/OSMetaClass stuff,
512 * but may be necessary for other C++ code. We ignore the return value
513 * because it's only a fail when there are existing instances of libkern
514 * classes, and there had better not be any created on the C++ init path.
516 if (load_success
&& result
!= KMOD_RETURN_SUCCESS
) {
517 (void)OSRuntimeFinalizeCPP(theKext
); //kmodInfo, sectionNames, textStart, textEnd);
520 if (theKext
&& load_success
&& result
== KMOD_RETURN_SUCCESS
) {
521 theKext
->setCPPInitialized(true);
527 /*********************************************************************
528 * Unload a kernel segment.
529 *********************************************************************/
532 OSRuntimeUnloadCPPForSegment(
533 kernel_segment_command_t
* segment
)
535 OSRuntimeCallStructorsInSection(NULL
, &g_kernel_kmod_info
, NULL
, segment
,
536 gOSStructorSectionNames
[kOSSectionNamesDefault
][kOSSectionNameFinalizer
], 0, 0);
540 #pragma mark C++ Allocators & Deallocators
541 #endif /* PRAGMA_MARK */
542 /*********************************************************************
543 * C++ Allocators & Deallocators
544 *********************************************************************/
546 operator new(size_t size
)
549 return kheap_alloc_tag_bt(KERN_OS_MALLOC
, size
,
550 (zalloc_flags_t
) (Z_WAITOK
| Z_ZERO
), VM_KERN_MEMORY_LIBKERN
);
554 operator delete(void * addr
)
555 #if __cplusplus >= 201103L
559 kheap_free_addr(KERN_OS_MALLOC
, addr
);
564 operator new[](unsigned long sz
)
566 return kheap_alloc_tag_bt(KERN_OS_MALLOC
, sz
,
567 (zalloc_flags_t
) (Z_WAITOK
| Z_ZERO
), VM_KERN_MEMORY_LIBKERN
);
571 operator delete[](void * ptr
)
572 #if __cplusplus >= 201103L
579 * Unpoison the C++ array cookie inserted (but not removed) by the
582 kasan_unpoison_cxx_array_cookie(ptr
);
584 kheap_free_addr(KERN_OS_MALLOC
, ptr
);
589 #if __cplusplus >= 201103L
592 operator delete(void * addr
, size_t sz
) noexcept
594 kheap_free(KERN_OS_MALLOC
, addr
, sz
);
598 operator delete[](void * addr
, size_t sz
) noexcept
601 kheap_free(KERN_OS_MALLOC
, addr
, sz
);
605 #endif /* __cplusplus >= 201103L */
607 /* PR-6481964 - The compiler is going to check for size overflows in calls to
608 * new[], and if there is an overflow, it will call __throw_length_error.
609 * This is an unrecoverable error by the C++ standard, so we must panic here.
611 * We have to put the function inside the std namespace because of how the
612 * compiler expects the name to be mangled.
616 __throw_length_error(const char *msg __unused
)
618 panic("Size of array created by new[] has overflowed");