Loading...
  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
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/*
 * Copyright (c) 2000,2008-2009 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 * 
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */
/*
 * Copyright (c) 1997 Apple Inc.
 *
 */
#include <libkern/c++/OSMetaClass.h>
#include <libkern/c++/OSKext.h>
#include <libkern/c++/OSLib.h>
#include <libkern/c++/OSSymbol.h>
#include <IOKit/IOKitDebug.h>

#include <sys/cdefs.h>

__BEGIN_DECLS

#include <string.h>
#include <mach/mach_types.h>
#include <libkern/kernel_mach_header.h>
#include <stdarg.h>

#if PRAGMA_MARK
#pragma mark Constants &c.
#endif /* PRAGMA_MARK */
OSKextLogSpec kOSRuntimeLogSpec =
    kOSKextLogErrorLevel |
    kOSKextLogLoadFlag |
    kOSKextLogKextBookkeepingFlag;
    
#if PRAGMA_MARK
#pragma mark Logging Bootstrap
#endif /* PRAGMA_MARK */
/*********************************************************************
* kern_os Logging Bootstrap
*
* We can't call in to OSKext until the kernel's C++ environment is up
* and running, so let's mask those references with a check variable.
* We print unconditionally if C++ isn't up, but if that's the case
* we've generally hit a serious error in kernel init!
*********************************************************************/
static bool gKernelCPPInitialized = false;

#define OSRuntimeLog(kext, flags, format, args...)            \
    do {                                                      \
        if (gKernelCPPInitialized) {                          \
            OSKextLog((kext), (flags), (format), ## args);  \
        } else {                                              \
            printf((format), ## args);                        \
        }                                                     \
    } while (0)

#if PRAGMA_MARK
#pragma mark kern_os Allocator Package
#endif /* PRAGMA_MARK */
/*********************************************************************
* kern_os Allocator Package
*********************************************************************/

/*********************************************************************
*********************************************************************/
#if OSALLOCDEBUG
extern int debug_iomalloc_size;
#endif

struct _mhead {
    size_t  mlen;
    char    dat[0];
};

/*********************************************************************
*********************************************************************/
void *
kern_os_malloc(size_t size)
{
    struct _mhead * mem;
    size_t          memsize = sizeof (*mem) + size ;

    if (size == 0) {
        return (0);
    }

    mem = (struct _mhead *)kalloc_tag_bt(memsize, VM_KERN_MEMORY_LIBKERN);
    if (!mem) {
        return (0);
    }

#if OSALLOCDEBUG
    debug_iomalloc_size += memsize;
#endif

    mem->mlen = memsize;
    bzero(mem->dat, size);

    return mem->dat;
}

/*********************************************************************
*********************************************************************/
void
kern_os_free(void * addr)
{
    struct _mhead * hdr;

    if (!addr) {
        return;
    }

    hdr = (struct _mhead *)addr; 
    hdr--;

#if OSALLOCDEBUG
    debug_iomalloc_size -= hdr->mlen;
#endif

#if 0
    memset((vm_offset_t)hdr, 0xbb, hdr->mlen);
#else
    kfree(hdr, hdr->mlen);
#endif
}

/*********************************************************************
*********************************************************************/
void *
kern_os_realloc(
    void   * addr,
    size_t   nsize)
{
    struct _mhead * ohdr;
    struct _mhead * nmem;
    size_t          nmemsize, osize;

    if (!addr) {
        return (kern_os_malloc(nsize));
    }

    ohdr = (struct _mhead *)addr;
    ohdr--;
    osize = ohdr->mlen - sizeof(*ohdr);
    if (nsize == osize) {
        return (addr);
    }

    if (nsize == 0) {
        kern_os_free(addr);
        return (0);
    }

    nmemsize = sizeof (*nmem) + nsize ;
    nmem = (struct _mhead *) kalloc_tag_bt(nmemsize, VM_KERN_MEMORY_LIBKERN);
    if (!nmem){
        kern_os_free(addr);
        return (0);
    }

#if OSALLOCDEBUG
    debug_iomalloc_size += (nmemsize - ohdr->mlen);
#endif

    nmem->mlen = nmemsize;
    if (nsize > osize) {
        (void) memset(&nmem->dat[osize], 0, nsize - osize);
    }
    (void)memcpy(nmem->dat, ohdr->dat, (nsize > osize) ? osize : nsize);
    kfree(ohdr, ohdr->mlen);

    return (nmem->dat);
}

/*********************************************************************
*********************************************************************/
size_t
kern_os_malloc_size(void * addr)
{
    struct _mhead * hdr;

    if (!addr) {
        return(0);
    }

    hdr = (struct _mhead *) addr; hdr--;
    return hdr->mlen - sizeof (struct _mhead);
}

#if PRAGMA_MARK
#pragma mark C++ Runtime Load/Unload
#endif /* PRAGMA_MARK */
/*********************************************************************
* kern_os C++ Runtime Load/Unload
*********************************************************************/

/*********************************************************************
*********************************************************************/
#if __GNUC__ >= 3
void __cxa_pure_virtual( void )    { panic("%s", __FUNCTION__); }
#else
void __pure_virtual( void )        { panic("%s", __FUNCTION__); }
#endif

typedef void (*structor_t)(void);

/*********************************************************************
*********************************************************************/
static boolean_t
sectionIsDestructor(kernel_section_t * section)
{
    boolean_t result;

    result = !strncmp(section->sectname, SECT_MODTERMFUNC,
        sizeof(SECT_MODTERMFUNC) - 1);
#if !__LP64__
    result = result || !strncmp(section->sectname, SECT_DESTRUCTOR, 
        sizeof(SECT_DESTRUCTOR) - 1);
#endif

    return result;
}

/*********************************************************************
*********************************************************************/
static boolean_t
sectionIsConstructor(kernel_section_t * section)
{
    boolean_t result;

    result = !strncmp(section->sectname, SECT_MODINITFUNC,
        sizeof(SECT_MODINITFUNC) - 1);
#if !__LP64__
    result = result || !strncmp(section->sectname, SECT_CONSTRUCTOR, 
        sizeof(SECT_CONSTRUCTOR) - 1);
#endif

    return result;
}


/*********************************************************************
* OSRuntimeUnloadCPPForSegment()
*
* Given a pointer to a mach object segment, iterate the segment to
* obtain a destructor section for C++ objects, and call each of the
* destructors there.
*********************************************************************/

void
OSRuntimeUnloadCPPForSegmentInKmod(
    kernel_segment_command_t * segment,
    kmod_info_t              * kmodInfo)
{

    kernel_section_t * section = NULL;  // do not free
    OSKext           * theKext = NULL;  // must release

    if (gKernelCPPInitialized && kmodInfo) {
        theKext = OSKext::lookupKextWithIdentifier(kmodInfo->name);
    }

    for (section = firstsect(segment);
         section != 0;
         section = nextsect(segment, section)) {

        if (sectionIsDestructor(section)) {
            structor_t * destructors = (structor_t *)section->addr;

            if (destructors) {
                int num_destructors = section->size / sizeof(structor_t);
                int hit_null_destructor = 0;

                for (int i = 0; i < num_destructors; i++) {
                    if (destructors[i]) {
                        (*destructors[i])();
                    } else if (!hit_null_destructor) {
                        hit_null_destructor = 1;
                        OSRuntimeLog(theKext, kOSRuntimeLogSpec,
                            "Null destructor in kext %s segment %s!",
                            kmodInfo ? kmodInfo->name : "(unknown)",
                            section->segname);
                    }
                }
            } /* if (destructors) */
        } /* if (strncmp...) */
    } /* for (section...) */

    OSSafeRelease(theKext);
    return;
}

void
OSRuntimeUnloadCPPForSegment(kernel_segment_command_t * segment) {
    OSRuntimeUnloadCPPForSegmentInKmod(segment, NULL);
}

/*********************************************************************
*********************************************************************/
void
OSRuntimeUnloadCPP(
    kmod_info_t * kmodInfo,
    void        * data __unused)
{
    if (kmodInfo && kmodInfo->address) {

        kernel_segment_command_t * segment;
        kernel_mach_header_t * header;

        OSSymbol::checkForPageUnload((void *)kmodInfo->address,
            (void *)(kmodInfo->address + kmodInfo->size));

        header = (kernel_mach_header_t *)kmodInfo->address;
        segment = firstsegfromheader(header);

        for (segment = firstsegfromheader(header);
             segment != 0;
             segment = nextsegfromheader(header, segment)) {

            OSRuntimeUnloadCPPForSegmentInKmod(segment, kmodInfo);
        }
    }

    return;
}

/*********************************************************************
*********************************************************************/
kern_return_t
OSRuntimeFinalizeCPP(
    kmod_info_t * kmodInfo,
    void        * data __unused)
{
    kern_return_t   result = KMOD_RETURN_FAILURE;
    void          * metaHandle = NULL;  // do not free
    OSKext        * theKext    = NULL;  // must release

    if (gKernelCPPInitialized) {
        theKext = OSKext::lookupKextWithIdentifier(kmodInfo->name);
    }

    if (theKext && !theKext->isCPPInitialized()) {
        result = KMOD_RETURN_SUCCESS;
        goto finish;
    }

   /* OSKext checks for this condition now, but somebody might call
    * this function directly (the symbol is exported....).
    */
    if (OSMetaClass::modHasInstance(kmodInfo->name)) {
        // xxx - Don't log under errors? this is more of an info thing
        OSRuntimeLog(theKext, kOSRuntimeLogSpec,
            "Can't tear down kext %s C++; classes have instances:",
            kmodInfo->name);
        OSKext::reportOSMetaClassInstances(kmodInfo->name, kOSRuntimeLogSpec);
        result = kOSMetaClassHasInstances;
        goto finish;
    }

   /* Tell the meta class system that we are starting to unload.
    * metaHandle isn't actually needed on the finalize path,
    * so we don't check it here, even though OSMetaClass::postModLoad() will
    * return a failure (it only does actual work on the init path anyhow).
    */
    metaHandle = OSMetaClass::preModLoad(kmodInfo->name);
    OSRuntimeUnloadCPP(kmodInfo, 0);
    (void)OSMetaClass::postModLoad(metaHandle);

    if (theKext) {
        theKext->setCPPInitialized(false);
    }
    result = KMOD_RETURN_SUCCESS;
finish:
    OSSafeRelease(theKext);
    return result;
}

// Functions used by the extenTools/kmod library project

/*********************************************************************
*********************************************************************/
kern_return_t
OSRuntimeInitializeCPP(
    kmod_info_t * kmodInfo,
    void *        data __unused)
{
    kern_return_t              result          = KMOD_RETURN_FAILURE;
    OSKext                   * theKext         = NULL;  // must release
    kernel_mach_header_t     * header          = NULL;
    void                     * metaHandle      = NULL;  // do not free
    bool                       load_success    = true;
    kernel_segment_command_t * segment         = NULL;  // do not free
    kernel_segment_command_t * failure_segment = NULL;  // do not free

    if (!kmodInfo || !kmodInfo->address) {
        result = kOSKextReturnInvalidArgument;
        goto finish;
    }

    if (gKernelCPPInitialized) {
        theKext = OSKext::lookupKextWithIdentifier(kmodInfo->name);
    }

    if (theKext && theKext->isCPPInitialized()) {
        result = KMOD_RETURN_SUCCESS;
        goto finish;
    }

    header = (kernel_mach_header_t *)kmodInfo->address;

   /* Tell the meta class system that we are starting the load
    */
    metaHandle = OSMetaClass::preModLoad(kmodInfo->name);
    assert(metaHandle);
    if (!metaHandle) {
        goto finish;
    }

   /* NO GOTO PAST HERE. */

   /* Scan the header for all constructor sections, in any
    * segment, and invoke the constructors within those sections.
    */
    for (segment = firstsegfromheader(header);
         segment != NULL && load_success;
         segment = nextsegfromheader(header, segment)) {

        kernel_section_t * section;

       /* Record the current segment in the event of a failure.
        */
        failure_segment = segment;

        for (section = firstsect(segment);
             section != NULL;
             section = nextsect(segment, section)) {

            if (sectionIsConstructor(section)) {
                structor_t * constructors = (structor_t *)section->addr;

                if (constructors) {
                    int num_constructors = section->size / sizeof(structor_t);
                    int hit_null_constructor = 0;

                    for (int i = 0;
                         i < num_constructors &&
                         OSMetaClass::checkModLoad(metaHandle);
                         i++) {

                        if (constructors[i]) {
                            (*constructors[i])();
                        } else if (!hit_null_constructor) {
                            hit_null_constructor = 1;
                            OSRuntimeLog(theKext, kOSRuntimeLogSpec,
                                "Null constructor in kext %s segment %s!",
                                kmodInfo->name, section->segname);
                        }
                    }
                    load_success = OSMetaClass::checkModLoad(metaHandle);

                    break;
                } /* if (constructors) */
            } /* if (strncmp...) */
        } /* for (section...) */
    } /* for (segment...) */

   /* We failed so call all of the destructors. We must do this before
    * calling OSMetaClass::postModLoad() as the OSMetaClass destructors
    * will alter state (in the metaHandle) used by that function.
    */
    if (!load_success) {

       /* Scan the header for all destructor sections, in any
        * segment, and invoke the constructors within those sections.
        */
        for (segment = firstsegfromheader(header);
             segment != failure_segment && segment != 0;
             segment = nextsegfromheader(header, segment)) {

            OSRuntimeUnloadCPPForSegment(segment);

        } /* for (segment...) */
    }

   /* Now, regardless of success so far, do the post-init registration
    * and cleanup. If we had to call the unloadCPP function, static
    * destructors have removed classes from the stalled list so no
    * metaclasses will actually be registered.
    */
    result = OSMetaClass::postModLoad(metaHandle);

   /* If we've otherwise been fine up to now, but OSMetaClass::postModLoad()
    * fails (typically due to a duplicate class), tear down all the C++
    * stuff from the kext. This isn't necessary for libkern/OSMetaClass stuff,
    * but may be necessary for other C++ code. We ignore the return value
    * because it's only a fail when there are existing instances of libkern
    * classes, and there had better not be any created on the C++ init path.
    */
    if (load_success && result != KMOD_RETURN_SUCCESS) {
        (void)OSRuntimeFinalizeCPP(kmodInfo, NULL);
    }

    if (theKext && load_success && result == KMOD_RETURN_SUCCESS) {
        theKext->setCPPInitialized(true);
    }
finish:
    OSSafeRelease(theKext);
    return result;
}

#if PRAGMA_MARK
#pragma mark Libkern Init
#endif /* PRAGMA_MARK */
/*********************************************************************
* Libkern Init
*********************************************************************/

/*********************************************************************
*********************************************************************/
extern lck_grp_t * IOLockGroup;
extern kmod_info_t g_kernel_kmod_info;

void OSlibkernInit(void)
{
    // This must be called before calling OSRuntimeInitializeCPP.
    OSMetaClassBase::initialize();
    
    g_kernel_kmod_info.address = (vm_address_t) &_mh_execute_header;
    if (kOSReturnSuccess != OSRuntimeInitializeCPP(&g_kernel_kmod_info, 0)) {
        panic("OSRuntime: C++ runtime failed to initialize.");
    }
    
    gKernelCPPInitialized = true;

    return;
}

__END_DECLS

#if PRAGMA_MARK
#pragma mark C++ Allocators & Deallocators
#endif /* PRAGMA_MARK */
/*********************************************************************
* C++ Allocators & Deallocators
*********************************************************************/
void *
operator new(size_t size)
#if __cplusplus >= 201103L
								noexcept
#endif
{
    void * result;

    result = (void *) kern_os_malloc(size);
    return result;
}

void
operator delete(void * addr)
#if __cplusplus >= 201103L
								noexcept
#endif
{
    kern_os_free(addr);
    return;
}

void *
operator new[](unsigned long sz)
#if __cplusplus >= 201103L
								noexcept
#endif
{
    if (sz == 0) sz = 1;
    return kern_os_malloc(sz);
}

void
operator delete[](void * ptr)
#if __cplusplus >= 201103L
								noexcept
#endif
{
    if (ptr) {
        kern_os_free(ptr);
    }
    return;
}

/* PR-6481964 - The compiler is going to check for size overflows in calls to
 * new[], and if there is an overflow, it will call __throw_length_error.
 * This is an unrecoverable error by the C++ standard, so we must panic here.
 *
 * We have to put the function inside the std namespace because of how the
 * compiler expects the name to be mangled.
 */
namespace std {

void
__throw_length_error(const char *msg __unused)
{
    panic("Size of array created by new[] has overflowed");
}

};