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>
43 #include <mach/mach_types.h>
44 #include <libkern/kernel_mach_header.h>
45 #include <libkern/prelink.h>
49 #include <san/kasan.h>
53 #pragma mark Constants &c.
54 #endif /* PRAGMA_MARK */
55 OSKextLogSpec kOSRuntimeLogSpec
=
56 kOSKextLogErrorLevel
|
58 kOSKextLogKextBookkeepingFlag
;
61 #pragma mark Logging Bootstrap
62 #endif /* PRAGMA_MARK */
63 /*********************************************************************
64 * kern_os Logging Bootstrap
66 * We can't call in to OSKext until the kernel's C++ environment is up
67 * and running, so let's mask those references with a check variable.
68 * We print unconditionally if C++ isn't up, but if that's the case
69 * we've generally hit a serious error in kernel init!
70 *********************************************************************/
71 static bool gKernelCPPInitialized
= false;
73 #define OSRuntimeLog(kext, flags, format, args...) \
75 if (gKernelCPPInitialized) { \
76 OSKextLog((kext), (flags), (format), ## args); \
78 printf((format), ## args); \
83 #pragma mark kern_os Allocator Package
84 #endif /* PRAGMA_MARK */
85 /*********************************************************************
86 * kern_os Allocator Package
87 *********************************************************************/
89 /*********************************************************************
90 *********************************************************************/
92 extern int debug_iomalloc_size
;
95 /*********************************************************************
96 *********************************************************************/
98 kern_os_malloc(size_t size
)
105 mem
= kallocp_tag_bt((vm_size_t
*)&size
, VM_KERN_MEMORY_LIBKERN
);
111 OSAddAtomic(size
, &debug_iomalloc_size
);
119 /*********************************************************************
120 *********************************************************************/
122 kern_os_free(void * addr
)
125 size
= kalloc_size(addr
);
127 OSAddAtomic(-size
, &debug_iomalloc_size
);
133 /*********************************************************************
134 *********************************************************************/
144 return kern_os_malloc(nsize
);
147 osize
= kalloc_size(addr
);
148 if (nsize
== osize
) {
157 nmem
= kallocp_tag_bt((vm_size_t
*)&nsize
, VM_KERN_MEMORY_LIBKERN
);
164 OSAddAtomic((nsize
- osize
), &debug_iomalloc_size
);
168 (void)memset((char *)nmem
+ osize
, 0, nsize
- osize
);
170 (void)memcpy(nmem
, addr
, (nsize
> osize
) ? osize
: nsize
);
177 #pragma mark Libkern Init
178 #endif /* PRAGMA_MARK */
179 /*********************************************************************
181 *********************************************************************/
185 __cxa_pure_virtual( void )
187 panic("%s", __FUNCTION__
);
191 __pure_virtual( void )
193 panic("%s", __FUNCTION__
);
197 extern lck_grp_t
* IOLockGroup
;
198 extern kmod_info_t g_kernel_kmod_info
;
201 kOSSectionNamesDefault
= 0,
202 kOSSectionNamesBuiltinKext
= 1,
203 kOSSectionNamesCount
= 2,
206 kOSSectionNameInitializer
= 0,
207 kOSSectionNameFinalizer
= 1,
208 kOSSectionNameCount
= 2
212 gOSStructorSectionNames
[kOSSectionNamesCount
][kOSSectionNameCount
] = {
213 { SECT_MODINITFUNC
, SECT_MODTERMFUNC
},
214 { kBuiltinInitSection
, kBuiltinTermSection
}
220 // This must be called before calling OSRuntimeInitializeCPP.
221 OSMetaClassBase::initialize();
223 g_kernel_kmod_info
.address
= (vm_address_t
) &_mh_execute_header
;
224 if (kOSReturnSuccess
!= OSRuntimeInitializeCPP(NULL
)) {
225 // &g_kernel_kmod_info, gOSSectionNamesStandard, 0, 0)) {
226 panic("OSRuntime: C++ runtime failed to initialize.");
229 gKernelCPPInitialized
= true;
237 #pragma mark C++ Runtime Load/Unload
238 #endif /* PRAGMA_MARK */
239 /*********************************************************************
240 * kern_os C++ Runtime Load/Unload
241 *********************************************************************/
243 #if defined(HAS_APPLE_PAC)
245 #endif /* defined(HAS_APPLE_PAC) */
247 typedef void (*structor_t
)(void);
250 OSRuntimeCallStructorsInSection(
252 kmod_info_t
* kmodInfo
,
254 kernel_segment_command_t
* segment
,
255 const char * sectionName
,
259 kernel_section_t
* section
;
262 for (section
= firstsect(segment
);
264 section
= nextsect(segment
, section
)) {
265 if (strncmp(section
->sectname
, sectionName
, sizeof(section
->sectname
) - 1)) {
269 structor_t
* structors
= (structor_t
*)section
->addr
;
275 unsigned int num_structors
= section
->size
/ sizeof(structor_t
);
276 unsigned int hit_null_structor
= 0;
277 unsigned int firstIndex
= 0;
280 // bsearch for any in range
281 unsigned int baseIdx
;
284 firstIndex
= num_structors
;
285 for (lim
= num_structors
, baseIdx
= 0; lim
; lim
>>= 1) {
286 value
= (uintptr_t) structors
[baseIdx
+ (lim
>> 1)];
288 panic("%s: null structor", kmodInfo
->name
);
290 if ((value
>= textStart
) && (value
< textEnd
)) {
291 firstIndex
= (baseIdx
+ (lim
>> 1));
292 // scan back for the first in range
293 for (; firstIndex
; firstIndex
--) {
294 value
= (uintptr_t) structors
[firstIndex
- 1];
295 if ((value
< textStart
) || (value
>= textEnd
)) {
301 if (textStart
> value
) {
303 baseIdx
+= (lim
>> 1) + 1;
308 baseIdx
= (baseIdx
+ (lim
>> 1));
311 (firstIndex
< num_structors
)
312 && (!metaHandle
|| OSMetaClass::checkModLoad(metaHandle
));
314 if ((structor
= structors
[firstIndex
])) {
315 if ((textStart
&& ((uintptr_t) structor
< textStart
))
316 || (textEnd
&& ((uintptr_t) structor
>= textEnd
))) {
320 #if !defined(XXX) && defined(HAS_APPLE_PAC)
321 structor
= __builtin_ptrauth_strip(structor
, ptrauth_key_function_pointer
);
322 structor
= __builtin_ptrauth_sign_unauthenticated(structor
, ptrauth_key_function_pointer
, 0);
325 } else if (!hit_null_structor
) {
326 hit_null_structor
= 1;
327 OSRuntimeLog(theKext
, kOSRuntimeLogSpec
,
328 "Null structor in kext %s segment %s!",
329 kmodInfo
->name
, section
->segname
);
333 result
= OSMetaClass::checkModLoad(metaHandle
);
336 } /* for (section...) */
340 /*********************************************************************
341 *********************************************************************/
343 OSRuntimeFinalizeCPP(
346 kern_return_t result
= KMOD_RETURN_FAILURE
;
347 void * metaHandle
= NULL
;// do not free
348 kernel_mach_header_t
* header
;
349 kernel_segment_command_t
* segment
;
350 kmod_info_t
* kmodInfo
;
351 const char ** sectionNames
;
357 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesDefault
];
359 if (!theKext
->isCPPInitialized()) {
360 result
= KMOD_RETURN_SUCCESS
;
363 kmodInfo
= theKext
->kmod_info
;
364 if (!kmodInfo
|| !kmodInfo
->address
) {
365 result
= kOSKextReturnInvalidArgument
;
368 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
369 if (theKext
->flags
.builtin
) {
370 header
= (kernel_mach_header_t
*)g_kernel_kmod_info
.address
;
371 textStart
= kmodInfo
->address
;
372 textEnd
= textStart
+ kmodInfo
->size
;
373 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesBuiltinKext
];
376 kmodInfo
= &g_kernel_kmod_info
;
377 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
380 /* OSKext checks for this condition now, but somebody might call
381 * this function directly (the symbol is exported....).
383 if (OSMetaClass::modHasInstance(kmodInfo
->name
)) {
384 // xxx - Don't log under errors? this is more of an info thing
385 OSRuntimeLog(theKext
, kOSRuntimeLogSpec
,
386 "Can't tear down kext %s C++; classes have instances:",
388 OSKext::reportOSMetaClassInstances(kmodInfo
->name
, kOSRuntimeLogSpec
);
389 result
= kOSMetaClassHasInstances
;
393 /* Tell the meta class system that we are starting to unload.
394 * metaHandle isn't actually needed on the finalize path,
395 * so we don't check it here, even though OSMetaClass::postModLoad() will
396 * return a failure (it only does actual work on the init path anyhow).
398 metaHandle
= OSMetaClass::preModLoad(kmodInfo
->name
);
400 OSSymbol::checkForPageUnload((void *)kmodInfo
->address
,
401 (void *)(kmodInfo
->address
+ kmodInfo
->size
));
403 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
404 segment
= firstsegfromheader(header
);
406 for (segment
= firstsegfromheader(header
);
408 segment
= nextsegfromheader(header
, segment
)) {
409 OSRuntimeCallStructorsInSection(theKext
, kmodInfo
, NULL
, segment
,
410 sectionNames
[kOSSectionNameFinalizer
], textStart
, textEnd
);
413 (void)OSMetaClass::postModLoad(metaHandle
);
416 theKext
->setCPPInitialized(false);
418 result
= KMOD_RETURN_SUCCESS
;
423 /*********************************************************************
424 *********************************************************************/
426 OSRuntimeInitializeCPP(
429 kern_return_t result
= KMOD_RETURN_FAILURE
;
430 kernel_mach_header_t
* header
= NULL
;
431 void * metaHandle
= NULL
;// do not free
432 bool load_success
= true;
433 kernel_segment_command_t
* segment
= NULL
;// do not free
434 kernel_segment_command_t
* failure_segment
= NULL
; // do not free
435 kmod_info_t
* kmodInfo
;
436 const char ** sectionNames
;
442 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesDefault
];
444 if (theKext
->isCPPInitialized()) {
445 result
= KMOD_RETURN_SUCCESS
;
449 kmodInfo
= theKext
->kmod_info
;
450 if (!kmodInfo
|| !kmodInfo
->address
) {
451 result
= kOSKextReturnInvalidArgument
;
454 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
456 if (theKext
->flags
.builtin
) {
457 header
= (kernel_mach_header_t
*)g_kernel_kmod_info
.address
;
458 textStart
= kmodInfo
->address
;
459 textEnd
= textStart
+ kmodInfo
->size
;
460 sectionNames
= gOSStructorSectionNames
[kOSSectionNamesBuiltinKext
];
463 kmodInfo
= &g_kernel_kmod_info
;
464 header
= (kernel_mach_header_t
*)kmodInfo
->address
;
467 /* Tell the meta class system that we are starting the load
469 metaHandle
= OSMetaClass::preModLoad(kmodInfo
->name
);
475 /* NO GOTO PAST HERE. */
477 /* Scan the header for all constructor sections, in any
478 * segment, and invoke the constructors within those sections.
480 for (segment
= firstsegfromheader(header
);
481 segment
!= NULL
&& load_success
;
482 segment
= nextsegfromheader(header
, segment
)) {
483 /* Record the current segment in the event of a failure.
485 failure_segment
= segment
;
486 load_success
= OSRuntimeCallStructorsInSection(
487 theKext
, kmodInfo
, metaHandle
, segment
,
488 sectionNames
[kOSSectionNameInitializer
],
490 } /* for (segment...) */
492 /* We failed so call all of the destructors. We must do this before
493 * calling OSMetaClass::postModLoad() as the OSMetaClass destructors
494 * will alter state (in the metaHandle) used by that function.
497 /* Scan the header for all destructor sections, in any
498 * segment, and invoke the constructors within those sections.
500 for (segment
= firstsegfromheader(header
);
501 segment
!= failure_segment
&& segment
!= NULL
;
502 segment
= nextsegfromheader(header
, segment
)) {
503 OSRuntimeCallStructorsInSection(theKext
, kmodInfo
, NULL
, segment
,
504 sectionNames
[kOSSectionNameFinalizer
], textStart
, textEnd
);
505 } /* for (segment...) */
508 /* Now, regardless of success so far, do the post-init registration
509 * and cleanup. If we had to call the unloadCPP function, static
510 * destructors have removed classes from the stalled list so no
511 * metaclasses will actually be registered.
513 result
= OSMetaClass::postModLoad(metaHandle
);
515 /* If we've otherwise been fine up to now, but OSMetaClass::postModLoad()
516 * fails (typically due to a duplicate class), tear down all the C++
517 * stuff from the kext. This isn't necessary for libkern/OSMetaClass stuff,
518 * but may be necessary for other C++ code. We ignore the return value
519 * because it's only a fail when there are existing instances of libkern
520 * classes, and there had better not be any created on the C++ init path.
522 if (load_success
&& result
!= KMOD_RETURN_SUCCESS
) {
523 (void)OSRuntimeFinalizeCPP(theKext
); //kmodInfo, sectionNames, textStart, textEnd);
526 if (theKext
&& load_success
&& result
== KMOD_RETURN_SUCCESS
) {
527 theKext
->setCPPInitialized(true);
533 /*********************************************************************
534 * Unload a kernel segment.
535 *********************************************************************/
538 OSRuntimeUnloadCPPForSegment(
539 kernel_segment_command_t
* segment
)
541 OSRuntimeCallStructorsInSection(NULL
, &g_kernel_kmod_info
, NULL
, segment
,
542 gOSStructorSectionNames
[kOSSectionNamesDefault
][kOSSectionNameFinalizer
], 0, 0);
546 #pragma mark C++ Allocators & Deallocators
547 #endif /* PRAGMA_MARK */
548 /*********************************************************************
549 * C++ Allocators & Deallocators
550 *********************************************************************/
552 operator new(size_t size
)
556 result
= (void *) kern_os_malloc(size
);
561 operator delete(void * addr
)
562 #if __cplusplus >= 201103L
571 operator new[](unsigned long sz
)
576 return kern_os_malloc(sz
);
580 operator delete[](void * ptr
)
581 #if __cplusplus >= 201103L
588 * Unpoison the C++ array cookie inserted (but not removed) by the
591 kasan_unpoison_cxx_array_cookie(ptr
);
598 #if __cplusplus >= 201103L
601 operator delete(void * addr
, size_t sz
) noexcept
604 OSAddAtomic(-sz
, &debug_iomalloc_size
);
605 #endif /* OSALLOCDEBUG */
610 operator delete[](void * addr
, size_t sz
) noexcept
614 OSAddAtomic(-sz
, &debug_iomalloc_size
);
615 #endif /* OSALLOCDEBUG */
620 #endif /* __cplusplus >= 201103L */
622 /* PR-6481964 - The compiler is going to check for size overflows in calls to
623 * new[], and if there is an overflow, it will call __throw_length_error.
624 * This is an unrecoverable error by the C++ standard, so we must panic here.
626 * We have to put the function inside the std namespace because of how the
627 * compiler expects the name to be mangled.
631 __throw_length_error(const char *msg __unused
)
633 panic("Size of array created by new[] has overflowed");