2 * Copyright (c) 2001 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
7 * Reserved. This file contains Original Code and/or Modifications of
8 * Original Code as defined in and that are subject to the Apple Public
9 * Source License Version 1.0 (the 'License'). You may not use this file
10 * except in compliance with the License. Please obtain a copy of the
11 * License at http://www.apple.com/publicsource and read it before using
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
19 * License for the specific language governing rights and limitations
22 * @APPLE_LICENSE_HEADER_END@
26 * 2001-05-30 gvdl Initial implementation of the vtable patcher.
28 // 45678901234567890123456789012345678901234567890123456789012345678901234567890
30 #include <mach-o/fat.h>
31 #include <mach-o/loader.h>
32 #include <mach-o/nlist.h>
33 #include <mach-o/reloc.h>
35 #include <mach-o/swap.h>
36 #include <libkern/OSByteOrder.h>
44 #include <sys/systm.h>
46 #include <libkern/OSTypes.h>
48 #include <libsa/stdlib.h>
49 #include <libsa/mach/mach.h>
51 #include "mach_loader.h"
53 #include <vm/vm_kern.h>
55 enum { false = 0, true = 1 };
57 #define vm_page_size page_size
59 extern void kld_error_vprintf(const char *format
, va_list ap
);
61 __private_extern__
char *strstr(const char *in
, const char *str
);
62 extern struct mach_header _mh_execute_header
;
63 extern struct segment_command
*getsegbyname(char *seg_name
); // 32 bit only
73 #include <sys/errno.h>
74 #include <sys/fcntl.h>
79 #include <mach/mach.h>
80 #include <mach/mach_error.h>
82 #include <mach-o/arch.h>
84 #include <CoreFoundation/CoreFoundation.h>
86 #define PAGE_SIZE vm_page_size
87 #define PAGE_MASK (PAGE_SIZE - 1)
91 #include "kld_patch.h"
95 #define DIE() do { for (;;) ; } while(0)
98 # define LOG_DELAY() /* IODelay(200000) */
99 # define DEBUG_LOG(x) do { IOLog x; LOG_DELAY(); } while(0)
102 # define DEBUG_LOG(x) do { printf x; } while(0)
113 // OSObject symbol prefixes and suffixes
114 #define kCPPSymbolPrefix "_Z"
115 #define kVTablePrefix "_" kCPPSymbolPrefix "TV"
116 #define kOSObjPrefix "_" kCPPSymbolPrefix "N"
117 #define kReservedNamePrefix "_RESERVED"
118 #define k29SuperClassSuffix "superClass"
119 #define k31SuperClassSuffix "10superClassE"
120 #define kGMetaSuffix "10gMetaClassE"
121 #define kLinkEditSegName SEG_LINKEDIT
123 // GCC 2.95 drops 2 leading constants in the vtable
124 #define kVTablePreambleLen 2
126 // Last address that I'm willing to try find vm in
127 #define kTopAddr ((unsigned char *) (1024 * 1024 * 1024))
129 // Size in bytes that Data Ref object's get increased in size
130 // Must be a power of 2
131 #define kDataCapacityIncrement 128
133 // My usual set of helper macros. I personally find these macros
134 // easier to read in the code rather than an explicit error condition
135 // check. If I don't make it easy then I may get lazy ond not check
136 // everything. I'm sorry if you find this code harder to read.
138 // break_if will evaluate the expression and if it is true
139 // then it will print the msg, which is enclosed in parens
140 // and then break. Usually used in loops are do { } while (0)
141 #define break_if(expr, msg) \
147 // return_if will evaluate expr and if true it will log the
148 // msg, which is enclosed in parens, and then it will return
149 // with the return code of ret.
150 #define return_if(expr, ret, msg) do { \
158 #define MIN(a,b) (((a)<(b))?(a):(b))
161 #define MAX(a,b) (((a)>(b))?(a):(b))
164 typedef struct Data
{
165 unsigned long fLength
, fCapacity
;
166 unsigned char *fData
;
169 struct sectionRecord
{
170 const struct section
*fSection
; // 32 bit mach object section
183 struct nlist
*fSymbol
;
184 const struct fileRecord
*fFile
;
185 enum patchState fType
;
190 const struct nlist
*fSymbol
;
191 struct relocation_info
*fRInfo
;
195 struct metaClassRecord
{
197 struct fileRecord
*fFile
;
198 const struct nlist
*fVTableSym
;
199 struct patchRecord
*fPatchedVTable
;
204 size_t fMapSize
, fMachOSize
;
205 unsigned char *fMap
, *fMachO
, *fPadEnd
;
208 DataRef fNewSymbols
, fNewStringBlocks
;
209 DataRef fSym2Strings
;
210 struct symtab_command
*fSymtab
;
211 struct sectionRecord
*fSections
;
212 vm_offset_t fVMAddr
, fVMEnd
;
213 struct segment_command
*fLinkEditSeg
;
214 const char **fSymbToStringTable
;
216 struct nlist
*fSymbolBase
;
217 const struct nlist
*fLocalSyms
;
218 unsigned int fNSects
;
220 Boolean fIsKernel
, fIsReloc
, fIsIncrLink
, fNoKernelExecutable
, fIsKmem
;
221 Boolean fImageDirty
, fSymbolsDirty
;
222 Boolean fRemangled
, fFoundOSObject
;
230 static DataRef sFilesTable
;
231 static struct fileRecord
*sKernelFile
;
233 static DataRef sMergedFiles
;
234 static DataRef sMergeMetaClasses
;
235 static Boolean sMergedKernel
;
237 static const NXArchInfo
* sPreferArchInfo
;
239 static const struct nlist
*
240 findSymbolByName(struct fileRecord
*file
, const char *symname
);
242 static void errprintf(const char *fmt
, ...)
247 kld_error_vprintf(fmt
, ap
);
253 static __inline__
unsigned long DataGetLength(DataRef data
)
255 return data
->fLength
;
258 static __inline__
unsigned char *DataGetPtr(DataRef data
)
263 static __inline__
unsigned char *DataGetEndPtr(DataRef data
)
265 return data
->fData
+ data
->fLength
;
268 static __inline__
unsigned long DataRemaining(DataRef data
)
270 return data
->fCapacity
- data
->fLength
;
273 static __inline__ Boolean
DataContainsAddr(DataRef data
, void *vAddr
)
275 vm_offset_t offset
= (vm_address_t
) vAddr
;
280 offset
= (vm_address_t
) vAddr
- (vm_address_t
) data
->fData
;
281 return (offset
< data
->fLength
);
284 static Boolean
DataEnsureCapacity(DataRef data
, unsigned long capacity
)
286 // Don't bother to ever shrink a data object.
287 if (capacity
> data
->fCapacity
) {
288 unsigned char *newData
;
290 capacity
+= kDataCapacityIncrement
- 1;
291 capacity
&= ~(kDataCapacityIncrement
- 1);
292 newData
= (unsigned char *) realloc(data
->fData
, capacity
);
296 bzero(newData
+ data
->fCapacity
, capacity
- data
->fCapacity
);
297 data
->fData
= newData
;
298 data
->fCapacity
= capacity
;
304 static __inline__ Boolean
DataSetLength(DataRef data
, unsigned long length
)
306 if (DataEnsureCapacity(data
, length
)) {
307 data
->fLength
= length
;
314 static __inline__ Boolean
DataAddLength(DataRef data
, unsigned long length
)
316 return DataSetLength(data
, data
->fLength
+ length
);
319 static __inline__ Boolean
320 DataAppendBytes(DataRef data
, const void *addr
, unsigned int len
)
322 unsigned long size
= DataGetLength(data
);
324 if (!DataAddLength(data
, len
))
327 bcopy(addr
, DataGetPtr(data
) + size
, len
);
331 static __inline__ Boolean
DataAppendData(DataRef dst
, DataRef src
)
333 return DataAppendBytes(dst
, DataGetPtr(src
), DataGetLength(src
));
336 static DataRef
DataCreate(unsigned long capacity
)
338 DataRef data
= (DataRef
) malloc(sizeof(Data
));
342 data
->fCapacity
= kDataCapacityIncrement
;
344 data
->fCapacity
= capacity
+ kDataCapacityIncrement
- 1;
345 data
->fCapacity
&= ~(kDataCapacityIncrement
- 1);
348 data
->fData
= (unsigned char *) malloc(data
->fCapacity
);
354 bzero(data
->fData
, data
->fCapacity
);
360 static void DataRelease(DataRef data
)
370 static __inline__
const char *
371 symNameByIndex(const struct fileRecord
*file
, unsigned int symInd
)
373 return file
->fSymbToStringTable
[symInd
];
376 static __inline__
const char *
377 symbolname(const struct fileRecord
*file
, const struct nlist
*sym
)
381 index
= sym
- file
->fSymbolBase
;
383 if (index
&& !sym
->n_un
.n_strx
)
384 return file
->fStringBase
+ sym
->n_value
;
386 if (index
< file
->fSymtab
->nsyms
)
387 return symNameByIndex(file
, index
);
389 if (-1 == sym
->n_un
.n_strx
)
390 return (const char *) sym
->n_value
;
392 // If the preceding tests fail then we have a getNewSymbol patch and
393 // the file it refers to has already been patched as the n_strx is set
394 // to -1 temporarily while we are still processing a file.
395 // Once we have finished with a file then we repair the 'strx' offset
396 // to be valid for the repaired file's string table.
397 return file
->fStringBase
+ sym
->n_un
.n_strx
;
400 static struct fileRecord
*
401 getFile(const char *path
)
405 struct fileRecord
**files
;
407 // Check to see if we have already merged this file
408 nfiles
= DataGetLength(sFilesTable
) / sizeof(struct fileRecord
*);
409 files
= (struct fileRecord
**) DataGetPtr(sFilesTable
);
410 for (i
= 0; i
< nfiles
; i
++) {
411 if (!strcmp(path
, files
[i
]->fPath
))
419 static struct fileRecord
*
420 addFile(struct fileRecord
*file
, const char *path
)
422 struct fileRecord
*newFile
;
425 sFilesTable
= DataCreate(0);
430 newFile
= (struct fileRecord
*)
431 malloc(sizeof(struct fileRecord
) + strlen(path
));
435 if (!DataAppendBytes(sFilesTable
, &newFile
, sizeof(newFile
))) {
440 bcopy(file
, newFile
, sizeof(struct fileRecord
) - 1);
441 strcpy((char *) newFile
->fPath
, path
);
446 // @@@ gvdl: need to clean up the sMergeMetaClasses
447 // @@@ gvdl: I had better fix the object file up again
448 static void unmapFile(struct fileRecord
*file
)
450 if (file
->fSectData
) {
451 struct sectionRecord
*section
;
452 unsigned int i
, nsect
;
454 nsect
= file
->fNSects
;
455 section
= file
->fSections
;
456 for (i
= 0; i
< nsect
; i
++, section
++) {
457 if (section
->fRelocCache
) {
458 DataRelease(section
->fRelocCache
);
459 section
->fRelocCache
= 0;
463 DataRelease(file
->fSectData
);
469 if (file
->fSym2Strings
) {
470 DataRelease(file
->fSym2Strings
);
471 file
->fSym2Strings
= 0;
477 kmem_free(kernel_map
, (vm_address_t
) file
->fMap
, file
->fMapSize
);
483 padVM
= round_page((vm_address_t
) file
->fMap
+ file
->fMapSize
);
484 padSize
= (vm_size_t
) ((vm_address_t
) file
->fPadEnd
- padVM
);
485 (void) vm_deallocate(mach_task_self(), padVM
, padSize
);
489 (void) munmap((caddr_t
) file
->fMap
, file
->fMapSize
);
495 static void removeFile(struct fileRecord
*file
)
497 if (file
->fClassList
) {
498 DataRelease(file
->fClassList
);
499 file
->fClassList
= 0;
509 mapObjectFile(struct fileRecord
*file
, const char *pathName
)
511 Boolean result
= false;
512 static unsigned char *sFileMapBaseAddr
= 0;
516 if (!sFileMapBaseAddr
) {
518 vm_address_t probeAddr
;
520 // If we don't already have a base addr find any random chunk
521 // of 32 meg of VM and to use the 16 meg boundrary as a base.
522 ret
= vm_allocate(mach_task_self(), &probeAddr
,
523 32 * 1024 * 1024, VM_FLAGS_ANYWHERE
);
524 return_if(KERN_SUCCESS
!= ret
, false,
525 ("Unable to allocate base memory %s\n", mach_error_string(ret
)));
526 (void) vm_deallocate(mach_task_self(), probeAddr
, 32 * 1024 * 1024);
528 // Now round to the next 16 Meg boundrary
529 probeAddr
= (probeAddr
+ (16 * 1024 * 1024 - 1))
530 & ~(16 * 1024 * 1024 - 1);
531 sFileMapBaseAddr
= (unsigned char *) probeAddr
;
534 fd
= open(pathName
, O_RDONLY
, 0);
535 return_if(fd
== -1, false, ("Can't open %s for reading - %s\n",
536 pathName
, strerror(errno
)));
543 break_if(fstat(fd
, &sb
) == -1,
544 ("Can't stat %s - %s\n", file
->fPath
, strerror(errno
)));
546 file
->fMapSize
= sb
.st_size
;
547 file
->fMap
= sFileMapBaseAddr
;
549 while (file
->fMap
< kTopAddr
) {
551 vm_address_t padVMEnd
;
554 padVM
= round_page((vm_address_t
) file
->fMap
+ file
->fMapSize
);
555 retaddr
= (int) mmap(file
->fMap
, file
->fMapSize
,
556 PROT_READ
|PROT_WRITE
,
557 MAP_FIXED
|MAP_FILE
|MAP_PRIVATE
,
560 break_if(ENOMEM
!= errno
,
561 ("mmap failed %d - %s\n", errno
, strerror(errno
)));
563 file
->fMap
= (unsigned char *) padVM
;
568 // Round up padVM to the next page after the file and assign at
569 // least another fMapSize more room rounded up to the next page
571 padVMEnd
= round_page(padVM
+ file
->fMapSize
);
572 padSize
= padVMEnd
- padVM
;
574 mach_task_self(), &padVM
, padSize
, VM_FLAGS_FIXED
);
575 if (KERN_SUCCESS
== ret
) {
576 file
->fPadEnd
= (unsigned char *) padVMEnd
;
580 munmap(file
->fMap
, file
->fMapSize
);
581 break_if(KERN_INVALID_ADDRESS
!= ret
,
582 ("Unable to allocate pad vm for %s - %s\n",
583 pathName
, mach_error_string(ret
)));
585 file
->fMap
= (unsigned char *) padVMEnd
;
586 continue; // try again wherever the vm system wants
590 if (-1 == retaddr
|| KERN_SUCCESS
!= ret
)
593 break_if(file
->fMap
>= kTopAddr
,
594 ("Unable to map memory %s\n", file
->fPath
));
596 sFileMapBaseAddr
= file
->fPadEnd
;
605 kld_set_architecture(const NXArchInfo
* arch
)
607 sPreferArchInfo
= arch
;
610 // This function can only operate on 32 bit mach-o files
612 kld_macho_swap(struct mach_header
* mh
)
614 struct segment_command
* seg
;
615 struct section
* section
;
616 CFIndex ncmds
, cmd
, sect
;
617 enum NXByteOrder hostOrder
= NXHostByteOrder();
619 if (MH_CIGAM
!= mh
->magic
)
622 swap_mach_header(mh
, hostOrder
);
625 seg
= (struct segment_command
*)(mh
+ 1);
628 cmd
++, seg
= (struct segment_command
*)(((vm_offset_t
)seg
) + seg
->cmdsize
))
630 if (OSSwapConstInt32(LC_SYMTAB
) == seg
->cmd
) {
631 swap_symtab_command((struct symtab_command
*) seg
, hostOrder
);
632 swap_nlist((struct nlist
*) (((vm_offset_t
) mh
) + ((struct symtab_command
*) seg
)->symoff
),
633 ((struct symtab_command
*) seg
)->nsyms
, hostOrder
);
636 if (OSSwapConstInt32(LC_SEGMENT
) != seg
->cmd
) {
637 swap_load_command((struct load_command
*) seg
, hostOrder
);
640 swap_segment_command(seg
, hostOrder
);
641 swap_section((struct section
*) (seg
+ 1), seg
->nsects
, hostOrder
);
643 section
= (struct section
*) (seg
+ 1);
644 for (sect
= 0; sect
< seg
->nsects
; sect
++, section
++) {
646 swap_relocation_info((struct relocation_info
*) (((vm_offset_t
) mh
) + section
->reloff
),
647 section
->nreloc
, hostOrder
);
654 // This function can only operate on 32 bit mach-o files
656 kld_macho_unswap(struct mach_header
* mh
, Boolean didSwap
, int symbols
)
658 // symbols == 0 => everything
659 // symbols == 1 => just nlists
660 // symbols == -1 => everything but nlists
662 struct segment_command
* seg
;
663 struct section
* section
;
664 unsigned long cmdsize
;
665 CFIndex ncmds
, cmd
, sect
;
666 enum NXByteOrder hostOrder
= (NXHostByteOrder() == NX_LittleEndian
)
667 ? NX_BigEndian
: NX_LittleEndian
;
672 seg
= (struct segment_command
*)(mh
+ 1);
675 cmd
++, seg
= (struct segment_command
*)(((vm_offset_t
)seg
) + cmdsize
))
677 cmdsize
= seg
->cmdsize
;
678 if (LC_SYMTAB
== seg
->cmd
) {
680 swap_nlist((struct nlist
*) (((vm_offset_t
) mh
) + ((struct symtab_command
*) seg
)->symoff
),
681 ((struct symtab_command
*) seg
)->nsyms
, hostOrder
);
684 swap_symtab_command((struct symtab_command
*) seg
, hostOrder
);
689 if (LC_SEGMENT
!= seg
->cmd
) {
690 swap_load_command((struct load_command
*) seg
, hostOrder
);
694 section
= (struct section
*) (seg
+ 1);
695 for (sect
= 0; sect
< seg
->nsects
; sect
++, section
++) {
697 swap_relocation_info((struct relocation_info
*) (((vm_offset_t
) mh
) + section
->reloff
),
698 section
->nreloc
, hostOrder
);
700 swap_section((struct section
*) (seg
+ 1), seg
->nsects
, hostOrder
);
701 swap_segment_command(seg
, hostOrder
);
704 swap_mach_header(mh
, hostOrder
);
709 // Note: This functions is only called from kld_file_map()
710 // This function can only operate on 32 bit mach-o files
711 static Boolean
findBestArch(struct fileRecord
*file
, const char *pathName
)
714 struct fat_header
*fat
;
717 file
->fMachOSize
= file
->fMapSize
;
718 file
->fMachO
= file
->fMap
;
719 magic
= ((const struct mach_header
*) file
->fMachO
)->magic
;
720 fat
= (struct fat_header
*) file
->fMachO
;
722 // Try to figure out what type of file this is
723 return_if(file
->fMapSize
< sizeof(unsigned long), false,
724 ("%s isn't a valid object file - no magic\n", pathName
));
728 // CIGAM is byte-swapped MAGIC
729 if (magic
== FAT_MAGIC
|| magic
== FAT_CIGAM
) {
731 load_return_t load_return
;
732 struct fat_arch fatinfo
;
734 load_return
= fatfile_getarch(NULL
, (vm_address_t
) fat
, &fatinfo
);
735 return_if(load_return
!= LOAD_SUCCESS
, false,
736 ("Extension \"%s\": has no code for this computer\n", pathName
));
738 file
->fMachO
= file
->fMap
+ fatinfo
.offset
;
739 file
->fMachOSize
= fatinfo
.size
;
740 magic
= ((const struct mach_header
*) file
->fMachO
)->magic
;
745 // Do we need to in-place swap the endianness of the fat header?
746 if (magic
== FAT_CIGAM
) {
748 struct fat_arch
*arch
;
750 fat
->nfat_arch
= OSSwapBigToHostInt32(fat
->nfat_arch
);
751 return_if(file
->fMapSize
< sizeof(struct fat_header
)
752 + fat
->nfat_arch
* sizeof(struct fat_arch
),
753 false, ("%s is too fat\n", file
->fPath
));
755 arch
= (struct fat_arch
*) &fat
[1];
756 for (i
= 0; i
< fat
->nfat_arch
; i
++) {
757 arch
[i
].cputype
= OSSwapBigToHostInt32(arch
[i
].cputype
);
758 arch
[i
].cpusubtype
= OSSwapBigToHostInt32(arch
[i
].cpusubtype
);
759 arch
[i
].offset
= OSSwapBigToHostInt32(arch
[i
].offset
);
760 arch
[i
].size
= OSSwapBigToHostInt32(arch
[i
].size
);
761 arch
[i
].align
= OSSwapBigToHostInt32(arch
[i
].align
);
764 magic
= OSSwapBigToHostInt32(fat
->magic
);
767 // Now see if we can find any valid architectures
768 if (magic
== FAT_MAGIC
) {
769 const NXArchInfo
*myArch
;
770 unsigned long fatsize
;
771 struct fat_arch
*arch
;
773 fatsize
= sizeof(struct fat_header
)
774 + fat
->nfat_arch
* sizeof(struct fat_arch
);
775 return_if(file
->fMapSize
< fatsize
,
776 false, ("%s isn't a valid fat file\n", pathName
));
779 myArch
= sPreferArchInfo
;
781 myArch
= NXGetLocalArchInfo();
783 arch
= NXFindBestFatArch(myArch
->cputype
, myArch
->cpusubtype
,
784 (struct fat_arch
*) &fat
[1], fat
->nfat_arch
);
786 false, ("%s hasn't got arch for %s\n", pathName
, myArch
->name
));
787 return_if(arch
->offset
+ arch
->size
> file
->fMapSize
,
788 false, ("%s's %s arch is incomplete\n", pathName
, myArch
->name
));
789 file
->fMachO
= file
->fMap
+ arch
->offset
;
790 file
->fMachOSize
= arch
->size
;
791 magic
= ((const struct mach_header
*) file
->fMachO
)->magic
;
794 file
->fSwapped
= kld_macho_swap((struct mach_header
*) file
->fMachO
);
796 magic
= ((const struct mach_header
*) file
->fMachO
)->magic
;
800 return_if(magic
!= MH_MAGIC
,
801 false, ("%s isn't a valid mach-o\n", pathName
));
806 // This function can only operate on segments from 32 bit mach-o files
808 parseSegments(struct fileRecord
*file
, struct segment_command
*seg
)
810 struct sectionRecord
*sections
;
811 int i
, nsects
= seg
->nsects
;
812 const struct segmentMap
{
813 struct segment_command seg
;
814 const struct section sect
[1];
817 if (!file
->fSectData
) {
818 file
->fSectData
= DataCreate(0);
819 if (!file
->fSectData
)
823 // Increase length of section DataRef and cache data pointer
824 if (!DataAddLength(file
->fSectData
, nsects
* sizeof(struct sectionRecord
)))
826 file
->fSections
= (struct sectionRecord
*) DataGetPtr(file
->fSectData
);
828 // Initialise the new sections
829 sections
= &file
->fSections
[file
->fNSects
];
830 file
->fNSects
+= nsects
;
831 for (i
= 0, segMap
= (struct segmentMap
*) seg
; i
< nsects
; i
++)
833 sections
[i
].fSection
= &segMap
->sect
[i
];
834 file
->fIsReloc
|= (0 != segMap
->sect
[i
].nreloc
);
841 remangleExternSymbols(struct fileRecord
*file
, const char *pathName
)
843 const struct nlist
*sym
;
845 DataRef strings
= NULL
;
847 DEBUG_LOG(("Remangling %s\n", pathName
));
849 file
->fNewStringBlocks
= DataCreate(0);
850 return_if(!file
->fNewStringBlocks
, false,
851 ("Unable to allocate new string table for %s\n", pathName
));
853 nsyms
= file
->fSymtab
->nsyms
;
854 for (i
= 0, sym
= file
->fSymbolBase
; i
< nsyms
; i
++, sym
++) {
858 unsigned char n_type
= sym
->n_type
;
860 // Not an external symbol or it is a stab in any case don't bother
861 if ((n_type
^ N_EXT
) & (N_STAB
| N_EXT
))
864 symname
= symNameByIndex(file
, i
);
868 strings
= DataCreate(16 * 1024); // Arbitrary block size
869 return_if(!strings
, false,
870 ("Unable to allocate new string block for %s\n", pathName
));
873 len
= DataRemaining(strings
);
874 newname
= DataGetEndPtr(strings
);
875 ret
= rem3_remangle_name(newname
, &len
, symname
);
877 case kR3InternalNotRemangled
:
878 errprintf("Remangler fails on %s in %s\n", symname
, pathName
);
880 case kR3NotRemangled
:
884 file
->fSymbToStringTable
[i
] = newname
;
885 file
->fRemangled
= file
->fSymbolsDirty
= true;
886 DataAddLength(strings
, len
+ 1); // returns strlen
889 case kR3BufferTooSmallRemangled
:
890 return_if(!DataAppendBytes
891 (file
->fNewStringBlocks
, &strings
, sizeof(strings
)),
892 false, ("Unable to allocate string table for %s\n", pathName
));
894 goto tryRemangleAgain
;
898 return_if(true, false,
899 ("Internal error - remangle of %s\n", pathName
));
904 return_if(!DataAppendBytes
905 (file
->fNewStringBlocks
, &strings
, sizeof(strings
)),
906 false, ("Unable to allocate string table for %s\n", pathName
));
912 // This function can only operate on symbol table files from 32 bit
914 static Boolean
parseSymtab(struct fileRecord
*file
, const char *pathName
)
916 const struct nlist
*sym
;
917 unsigned int i
, firstlocal
, nsyms
;
918 unsigned long strsize
;
920 Boolean foundOSObject
, found295CPP
, havelocal
;
922 // we found a link edit segment so recompute the bases
923 if (file
->fLinkEditSeg
) {
924 struct segment_command
*link
= file
->fLinkEditSeg
;
926 file
->fSymbolBase
= (struct nlist
*)
927 (link
->vmaddr
+ (file
->fSymtab
->symoff
- link
->fileoff
));
928 file
->fStringBase
= (char *)
929 (link
->vmaddr
+ (file
->fSymtab
->stroff
- link
->fileoff
));
930 return_if( ( (caddr_t
) file
->fStringBase
+ file
->fSymtab
->strsize
931 > (caddr_t
) link
->vmaddr
+ link
->vmsize
), false,
932 ("%s isn't a valid mach-o le, bad symbols\n", pathName
));
935 file
->fSymbolBase
= (struct nlist
*)
936 (file
->fMachO
+ file
->fSymtab
->symoff
);
937 file
->fStringBase
= (char *)
938 (file
->fMachO
+ file
->fSymtab
->stroff
);
939 return_if( ( file
->fSymtab
->stroff
+ file
->fSymtab
->strsize
940 > file
->fMachOSize
), false,
941 ("%s isn't a valid mach-o, bad symbols\n", pathName
));
944 nsyms
= file
->fSymtab
->nsyms
;
946 // If this file the kernel and do we have an executable image
947 file
->fNoKernelExecutable
= (vm_page_size
== file
->fSymtab
->symoff
)
948 && (file
->fSections
[0].fSection
->size
== 0);
950 // Generate a table of pointers to strings indexed by the symbol number
952 file
->fSym2Strings
= DataCreate(nsyms
* sizeof(const char *));
953 DataSetLength(file
->fSym2Strings
, nsyms
* sizeof(const char *));
954 return_if(!file
->fSym2Strings
, false,
955 ("Unable to allocate memory - symbol string trans\n", pathName
));
956 file
->fSymbToStringTable
= (const char **) DataGetPtr(file
->fSym2Strings
);
958 // Search for the first non-stab symbol in table
959 strsize
= file
->fSymtab
->strsize
;
960 strbase
= file
->fStringBase
;
963 found295CPP
= foundOSObject
= false;
964 for (i
= 0, sym
= file
->fSymbolBase
; i
< nsyms
; i
++, sym
++) {
965 long strx
= sym
->n_un
.n_strx
;
966 const char *symname
= strbase
+ strx
;
967 unsigned char n_type
;
969 return_if(((unsigned long) strx
> strsize
), false,
970 ("%s has an illegal string offset in symbol %d\n", pathName
, i
));
973 if (file
->fIsIncrLink
) {
974 if ( (sym
->n_type
& N_TYPE
) == N_SECT
) {
975 sym
->n_sect
= NO_SECT
;
976 sym
->n_type
= (sym
->n_type
& ~N_TYPE
) | N_ABS
;
981 if (file
->fIsIncrLink
&& !file
->fNSects
)
984 struct nlist
*patchsym
= (struct nlist
*) sym
;
985 const char * lookname
;
986 const struct nlist
* realsym
;
988 if ( (patchsym
->n_type
& N_TYPE
) == N_INDR
)
989 lookname
= strbase
+ patchsym
->n_value
;
992 realsym
= findSymbolByName(sKernelFile
, lookname
);
994 patchsym
->n_sect
= NO_SECT
;
997 patchsym
->n_type
= realsym
->n_type
;
998 patchsym
->n_desc
= realsym
->n_desc
;
999 patchsym
->n_value
= realsym
->n_value
;
1000 if ((patchsym
->n_type
& N_TYPE
) == N_SECT
)
1001 patchsym
->n_type
= (patchsym
->n_type
& ~N_TYPE
) | N_ABS
;
1005 errprintf("%s: Undefined in symbol set: %s\n", pathName
, symname
);
1006 patchsym
->n_type
= N_ABS
;
1007 patchsym
->n_desc
= 0;
1008 patchsym
->n_value
= patchsym
->n_un
.n_strx
;
1009 patchsym
->n_un
.n_strx
= 0;
1012 if (!havelocal
&& (patchsym
->n_type
& N_EXT
)) {
1015 file
->fLocalSyms
= patchsym
;
1020 // Load up lookup symbol look table with sym names
1021 file
->fSymbToStringTable
[i
] = symname
;
1023 n_type
= sym
->n_type
& (N_TYPE
| N_EXT
);
1025 // Find the first exported symbol
1026 if ( !firstlocal
&& (n_type
& N_EXT
) ) {
1029 file
->fLocalSyms
= sym
;
1032 // Find the a OSObject based subclass by searching for symbols
1033 // that have a suffix of '10superClassE'
1034 symname
++; // Skip leading '_'
1037 && (n_type
== (N_SECT
| N_EXT
) || n_type
== (N_ABS
| N_EXT
))
1039 const char *suffix
, *endSym
;
1041 endSym
= symname
+ strlen(symname
);
1043 // Find out if this symbol has the superclass suffix.
1044 if (symname
[0] == kCPPSymbolPrefix
[0]
1045 && symname
[1] == kCPPSymbolPrefix
[1]) {
1047 suffix
= endSym
- sizeof(k31SuperClassSuffix
) + 1;
1049 // Check for a gcc3 OSObject subclass
1050 if (suffix
> symname
1051 && !strcmp(suffix
, k31SuperClassSuffix
))
1052 foundOSObject
= true;
1055 suffix
= endSym
- sizeof(k29SuperClassSuffix
);
1057 // Check for a gcc295 OSObject subclass
1058 if (suffix
> symname
1059 && ('.' == *suffix
|| '$' == *suffix
)
1060 && !strcmp(suffix
+1, k29SuperClassSuffix
)) {
1061 found295CPP
= foundOSObject
= true;
1063 else if (!found295CPP
) {
1064 // Finally just check if we need to remangle
1065 symname
++; // skip leading '__'
1067 if ('_' == symname
[0] && '_' == symname
[1]) {
1076 else if (sym
->n_type
== (N_EXT
| N_UNDF
)) {
1077 if ( !file
->fNLocal
) // Find the last local symbol
1078 file
->fNLocal
= i
- firstlocal
;
1080 symname
++; // Skip possible second '_' at start.
1082 if ('_' == symname
[0] && '_' == symname
[1]) {
1090 // Note symname is trashed at this point
1092 return_if(i
< nsyms
, false,
1093 ("%s isn't a valid mach-o, bad symbol strings\n", pathName
));
1095 return_if(!file
->fLocalSyms
, false, ("%s has no symbols?\n", pathName
));
1097 // If we don't have any undefined symbols then all symbols
1098 // must be local so just compute it now if necessary.
1099 if ( !file
->fNLocal
)
1100 file
->fNLocal
= i
- firstlocal
;
1102 file
->fFoundOSObject
= foundOSObject
;
1104 if (found295CPP
&& !remangleExternSymbols(file
, pathName
))
1110 // @@@ gvdl: These functions need to be hashed they are
1111 // going to be way too slow for production code.
1112 static const struct nlist
*
1113 findSymbolByAddress(const struct fileRecord
*file
, void *entry
)
1115 // not quite so dumb linear search of all symbols
1116 const struct nlist
*sym
;
1119 // First try to find the symbol in the most likely place which is the
1121 sym
= file
->fLocalSyms
;
1122 for (i
= 0, nsyms
= file
->fNLocal
; i
< nsyms
; i
++, sym
++) {
1123 if (sym
->n_value
== (unsigned long) entry
&& !(sym
->n_type
& N_STAB
) )
1127 // Didn't find it in the external symbols so try to local symbols before
1129 sym
= file
->fSymbolBase
;
1130 for (i
= 0, nsyms
= file
->fSymtab
->nsyms
; i
< nsyms
; i
++, sym
++) {
1131 if ( (sym
->n_type
& N_EXT
) )
1133 if ( sym
->n_value
== (unsigned long) entry
&& !(sym
->n_type
& N_STAB
) )
1140 static const struct nlist
*
1141 findSymbolByAddressInAllFiles(__unused
const struct fileRecord
* fromFile
,
1142 void *entry
, const struct fileRecord
**resultFile
)
1145 struct fileRecord
**files
;
1149 // Check to see if we have already merged this file
1150 nfiles
= DataGetLength(sFilesTable
) / sizeof(struct fileRecord
*);
1151 files
= (struct fileRecord
**) DataGetPtr(sFilesTable
);
1152 for (i
= 0; i
< nfiles
; i
++) {
1153 if ((((vm_offset_t
)entry
) >= files
[i
]->fVMAddr
)
1154 && (((vm_offset_t
)entry
) < files
[i
]->fVMEnd
))
1156 const struct nlist
* result
;
1158 *resultFile
= files
[i
];
1159 result
= findSymbolByAddress(files
[i
], entry
);
1168 struct searchContext
{
1169 const char *fSymname
;
1170 const struct fileRecord
*fFile
;
1173 static int symbolSearch(const void *vKey
, const void *vSym
)
1175 const struct searchContext
*key
= (const struct searchContext
*) vKey
;
1176 const struct nlist
*sym
= (const struct nlist
*) vSym
;
1178 return strcmp(key
->fSymname
, symbolname(key
->fFile
, sym
));
1181 static const struct nlist
*
1182 findSymbolByName(struct fileRecord
*file
, const char *symname
)
1184 if (file
->fRemangled
) {
1185 // @@@ gvdl: Performance problem
1186 // Linear search as we don't sort after remangling
1187 const struct nlist
*sym
;
1188 int i
= file
->fLocalSyms
- file
->fSymbolBase
;
1189 int nLocal
= file
->fNLocal
+ i
;
1191 for (sym
= file
->fLocalSyms
; i
< nLocal
; i
++, sym
++)
1192 if (!strcmp(symNameByIndex(file
, i
), symname
))
1197 struct searchContext context
;
1199 context
.fSymname
= symname
;
1200 context
.fFile
= file
;
1201 return (struct nlist
*)
1203 file
->fLocalSyms
, file
->fNLocal
, sizeof(struct nlist
),
1209 relocateSection(const struct fileRecord
*file
, struct sectionRecord
*sectionRec
)
1211 const struct nlist
*symbol
;
1212 const struct section
*section
;
1213 struct relocRecord
*rec
;
1214 struct relocation_info
*rinfo
;
1216 unsigned long r_address
, r_symbolnum
, r_length
;
1217 enum reloc_type_generic r_type
;
1221 sectionRec
->fRelocCache
= DataCreate(
1222 sectionRec
->fSection
->nreloc
* sizeof(struct relocRecord
));
1223 if (!sectionRec
->fRelocCache
)
1226 section
= sectionRec
->fSection
;
1227 sectionBase
= file
->fMachO
+ section
->offset
;
1229 rec
= (struct relocRecord
*) DataGetPtr(sectionRec
->fRelocCache
);
1230 rinfo
= (struct relocation_info
*) (file
->fMachO
+ section
->reloff
);
1231 for (i
= 0; i
< section
->nreloc
; i
++, rec
++, rinfo
++) {
1233 // Totally uninterested in scattered relocation entries
1234 if ( (rinfo
->r_address
& R_SCATTERED
) )
1237 r_address
= rinfo
->r_address
;
1238 entry
= (void **) (sectionBase
+ r_address
);
1241 * The r_address field is really an offset into the contents of the
1242 * section and must reference something inside the section (Note
1243 * that this is not the case for PPC_RELOC_PAIR entries but this
1244 * can't be one with the above checks).
1246 return_if(r_address
>= section
->size
, false,
1247 ("Invalid relocation entry in %s - not in section\n", file
->fPath
));
1249 // If we don't have a VANILLA entry or the Vanilla entry isn't
1250 // a 'long' then ignore the entry and try the next.
1251 r_type
= (enum reloc_type_generic
) rinfo
->r_type
;
1252 r_length
= rinfo
->r_length
;
1253 if (r_type
!= GENERIC_RELOC_VANILLA
|| r_length
!= 2)
1256 r_symbolnum
= rinfo
->r_symbolnum
;
1259 * If rinfo->r_extern is set this relocation entry is an external entry
1260 * else it is a local entry.
1262 if (rinfo
->r_extern
) {
1264 * This is an external relocation entry.
1265 * r_symbolnum is an index into the input file's symbol table
1266 * of the symbol being refered to. The symbol must be
1267 * undefined to be used in an external relocation entry.
1269 return_if(r_symbolnum
>= file
->fSymtab
->nsyms
, false,
1270 ("Invalid relocation entry in %s - no symbol\n", file
->fPath
));
1273 * If this is an indirect symbol resolve indirection (all chains
1274 * of indirect symbols have been resolved so that they point at
1275 * a symbol that is not an indirect symbol).
1277 symbol
= file
->fSymbolBase
;
1278 if ((symbol
[r_symbolnum
].n_type
& N_TYPE
) == N_INDR
)
1279 r_symbolnum
= symbol
[r_symbolnum
].n_value
;
1280 symbol
= &symbol
[r_symbolnum
];
1282 return_if(symbol
->n_type
!= (N_EXT
| N_UNDF
), false,
1283 ("Invalid relocation entry in %s - extern\n", file
->fPath
));
1287 * If the symbol is not in any section then it can't be a
1288 * pointer to a local segment and I don't care about it.
1290 if (r_symbolnum
== R_ABS
)
1293 // Note segment references are offset by 1 from 0.
1294 return_if(r_symbolnum
> file
->fNSects
, false,
1295 ("Invalid relocation entry in %s - local\n", file
->fPath
));
1297 // Find the symbol, if any, that backs this entry
1298 void * addr
= *entry
;
1301 addr
= (void *) OSSwapInt32((uint32_t) addr
);
1303 symbol
= findSymbolByAddress(file
, addr
);
1306 rec
->fValue
= *entry
; // Save the previous value
1307 rec
->fRInfo
= rinfo
; // Save a pointer to the reloc
1308 rec
->fSymbol
= symbol
; // Record the current symbol
1310 *entry
= (void *) rec
; // Save pointer to record in object image
1313 DataSetLength(sectionRec
->fRelocCache
, i
* sizeof(struct relocRecord
));
1314 ((struct fileRecord
*) file
)->fImageDirty
= true;
1319 static const struct nlist
*
1320 findSymbolRefAtLocation(const struct fileRecord
*file
,
1321 struct sectionRecord
*sctn
, void **loc
, const struct fileRecord
**foundInFile
)
1323 const struct nlist
* result
;
1325 *foundInFile
= file
;
1327 if (!file
->fIsReloc
) {
1332 addr
= (void *) OSSwapInt32((uint32_t) addr
);
1334 result
= findSymbolByAddress(file
, addr
);
1336 result
= findSymbolByAddressInAllFiles(file
, addr
, foundInFile
);
1340 else if (sctn
->fRelocCache
|| relocateSection(file
, sctn
)) {
1341 struct relocRecord
*reloc
= (struct relocRecord
*) *loc
;
1343 if (DataContainsAddr(sctn
->fRelocCache
, reloc
))
1344 return reloc
->fSymbol
;
1351 addClass(struct fileRecord
*file
,
1352 struct metaClassRecord
*inClass
,
1355 Boolean result
= false;
1356 struct metaClassRecord
*newClass
= NULL
;
1357 struct metaClassRecord
**fileClasses
= NULL
;
1360 if (!file
->fClassList
) {
1361 file
->fClassList
= DataCreate(0);
1362 if (!file
->fClassList
)
1367 // Attempt to allocate all necessary resource first
1368 len
= strlen(cname
) + 1
1369 + (int) (&((struct metaClassRecord
*) 0)->fClassName
);
1370 newClass
= (struct metaClassRecord
*) malloc(len
);
1374 if (!DataAddLength(file
->fClassList
, sizeof(struct metaClassRecord
*)))
1376 fileClasses
= (struct metaClassRecord
**)
1377 (DataGetPtr(file
->fClassList
) + DataGetLength(file
->fClassList
));
1379 // Copy the meta Class structure and string name into newClass and
1380 // insert object at end of the file->fClassList and sMergeMetaClasses
1381 *newClass
= *inClass
;
1382 strcpy(newClass
->fClassName
, cname
);
1383 fileClasses
[-1] = newClass
;
1389 DataAddLength(file
->fClassList
, -sizeof(struct metaClassRecord
*));
1397 static struct metaClassRecord
*getClass(DataRef classList
, const char *cname
)
1401 struct metaClassRecord
**classes
, *thisClass
;
1403 nclass
= DataGetLength(classList
) / sizeof(struct metaClassRecord
*);
1404 classes
= (struct metaClassRecord
**) DataGetPtr(classList
);
1405 for (i
= 0; i
< nclass
; i
++) {
1406 thisClass
= classes
[i
];
1407 if (!strcmp(thisClass
->fClassName
, cname
))
1415 // Add the class 'cname' to the list of known OSObject based classes
1416 // Note 'sym' is the <cname>10superClassE symbol.
1418 recordClass(struct fileRecord
*file
, const char *cname
, const struct nlist
*sym
)
1420 Boolean result
= false;
1421 char *supername
= NULL
;
1422 const char *classname
= NULL
;
1423 struct metaClassRecord newClass
;
1424 char strbuffer
[1024];
1426 // Only do the work to find the super class if we are
1427 // not currently working on the kernel. The kernel is the end
1428 // of all superclass chains by definition as the kernel must be binary
1429 // compatible with itself.
1430 if (file
->fIsReloc
) {
1432 const struct fileRecord
*superfile
;
1433 const struct nlist
*supersym
;
1434 const struct section
*section
;
1435 struct sectionRecord
*sectionRec
;
1436 unsigned char sectind
= sym
->n_sect
;
1437 const char *superstr
;
1441 // We can't resolve anything that isn't in a real section
1442 // Note that the sectind is starts at one to make room for the
1443 // NO_SECT flag but the fNSects field isn't offset so we have a
1444 // '>' test. Which means this isn't an OSObject based class
1445 if (sectind
== NO_SECT
|| sectind
> file
->fNSects
) {
1449 sectionRec
= file
->fSections
+ sectind
- 1;
1450 section
= sectionRec
->fSection
;
1451 location
= (void **) ( file
->fMachO
+ section
->offset
1452 + sym
->n_value
- section
->addr
);
1454 supersym
= findSymbolRefAtLocation(file
, sectionRec
, location
, &superfile
);
1456 result
= true; // No superclass symbol then it isn't an OSObject.
1460 // Find string in file and skip leading '_' and then find the suffix
1461 superstr
= symbolname(superfile
, supersym
) + 1;
1462 suffix
= superstr
+ strlen(superstr
) - sizeof(kGMetaSuffix
) + 1;
1463 if (suffix
<= superstr
|| strcmp(suffix
, kGMetaSuffix
)) {
1464 result
= true; // Not an OSObject superclass so ignore it..
1468 // Got a candidate so hand it over for class processing.
1469 snamelen
= suffix
- superstr
- sizeof(kOSObjPrefix
) + 2;
1470 supername
= (char *) malloc(snamelen
+ 1);
1471 bcopy(superstr
+ sizeof(kOSObjPrefix
) - 2, supername
, snamelen
);
1472 supername
[snamelen
] = '\0';
1476 break_if(getClass(file
->fClassList
, cname
),
1477 ("Duplicate class %s in %s\n", cname
, file
->fPath
));
1479 snprintf(strbuffer
, sizeof(strbuffer
), "%s%s", kVTablePrefix
, cname
);
1480 newClass
.fVTableSym
= findSymbolByName(file
, strbuffer
);
1481 break_if(!newClass
.fVTableSym
,
1482 ("Can't find vtable %s in %s\n", cname
, file
->fPath
));
1484 newClass
.fFile
= file
;
1485 newClass
.fSuperName
= supername
;
1486 newClass
.fPatchedVTable
= NULL
;
1488 // Can't use cname as it may be a stack variable
1489 // However the vtable's string has the class name as a suffix
1490 // so why don't we use that rather than mallocing a string.
1491 classname
= symbolname(file
, newClass
.fVTableSym
)
1492 + sizeof(kVTablePrefix
) - 1;
1493 break_if(!addClass(file
, &newClass
, classname
),
1494 ("recordClass - no memory?\n"));
1508 static Boolean
getMetaClassGraph(struct fileRecord
*file
)
1510 const struct nlist
*sym
;
1513 // Search the symbol table for the local symbols that are generated
1514 // by the metaclass system. There are three metaclass variables
1515 // that are relevant.
1517 // <ClassName>.metaClass A pointer to the meta class structure.
1518 // <ClassName>.superClass A pointer to the super class's meta class.
1519 // <ClassName>.gMetaClass The meta class structure itself.
1520 // ___vt<ClassName> The VTable for the class <ClassName>.
1522 // In this code I'm going to search for any symbols that
1523 // ends in k31SuperClassSuffix as this indicates this class is a conforming
1524 // OSObject subclass and will need to be patched, and it also
1525 // contains a pointer to the super class's meta class structure.
1526 sym
= file
->fLocalSyms
;
1527 for (i
= 0, nsyms
= file
->fNLocal
; i
< nsyms
; i
++, sym
++) {
1528 const char *symname
;
1530 char classname
[1024];
1531 unsigned char n_type
= sym
->n_type
& (N_TYPE
| N_EXT
);
1534 // Check that the symbols is a global and that it has a name.
1535 if (((N_SECT
| N_EXT
) != n_type
&& (N_ABS
| N_EXT
) != n_type
)
1536 || !sym
->n_un
.n_strx
)
1539 // Only search from the last *sep* in the symbol.
1540 // but skip the leading '_' in all symbols first.
1541 symname
= symbolname(file
, sym
) + 1;
1542 if (symname
[0] != kCPPSymbolPrefix
[0]
1543 || symname
[1] != kCPPSymbolPrefix
[1])
1546 suffix
= symname
+ strlen(symname
) - sizeof(k31SuperClassSuffix
) + 1;
1547 if (suffix
<= symname
|| strcmp(suffix
, k31SuperClassSuffix
))
1550 // Got a candidate so hand it over for class processing.
1551 cnamelen
= suffix
- symname
- sizeof(kOSObjPrefix
) + 2;
1552 return_if(cnamelen
+ 1 >= (int) sizeof(classname
),
1553 false, ("Symbol %s is too long", symname
));
1555 bcopy(symname
+ sizeof(kOSObjPrefix
) - 2, classname
, cnamelen
);
1556 classname
[cnamelen
] = '\0';
1557 if (!recordClass(file
, classname
, sym
))
1561 return_if(!file
->fClassList
, false, ("Internal error, "
1562 "getMetaClassGraph(%s) found no classes", file
->fPath
));
1564 DEBUG_LOG(("Found %ld classes in %p for %s\n",
1565 DataGetLength(file
->fClassList
)/sizeof(void*),
1566 file
->fClassList
, file
->fPath
));
1571 static Boolean
mergeOSObjectsForFile(const struct fileRecord
*file
)
1574 Boolean foundDuplicates
= false;
1576 DEBUG_LOG(("Merging file %s\n", file
->fPath
)); // @@@ gvdl:
1578 if (!file
->fClassList
)
1581 if (!sMergedFiles
) {
1582 sMergedFiles
= DataCreate(0);
1583 return_if(!sMergedFiles
, false,
1584 ("Unable to allocate memory metaclass list\n", file
->fPath
));
1587 // Check to see if we have already merged this file
1588 nmerged
= DataGetLength(sMergedFiles
) / sizeof(struct fileRecord
*);
1589 for (i
= 0; i
< nmerged
; i
++) {
1590 if (file
== ((void **) DataGetPtr(sMergedFiles
))[i
])
1594 if (!sMergeMetaClasses
) {
1595 sMergeMetaClasses
= DataCreate(0);
1596 return_if(!sMergeMetaClasses
, false,
1597 ("Unable to allocate memory metaclass list\n", file
->fPath
));
1599 else { /* perform a duplicate check */
1600 int k
, j
, cnt1
, cnt2
;
1601 struct metaClassRecord
**list1
, **list2
;
1603 list1
= (struct metaClassRecord
**) DataGetPtr(file
->fClassList
);
1604 cnt1
= DataGetLength(file
->fClassList
) / sizeof(*list1
);
1605 list2
= (struct metaClassRecord
**) DataGetPtr(sMergeMetaClasses
);
1606 cnt2
= DataGetLength(sMergeMetaClasses
) / sizeof(*list2
);
1608 for (k
= 0; k
< cnt1
; k
++) {
1609 for (j
= 0; j
< cnt2
; j
++) {
1610 if (!strcmp(list1
[k
]->fClassName
, list2
[j
]->fClassName
)) {
1611 errprintf("duplicate class %s in %s & %s\n",
1612 list1
[k
]->fClassName
,
1613 file
->fPath
, list2
[j
]->fFile
->fPath
);
1618 if (foundDuplicates
)
1621 return_if(!DataAppendBytes(sMergedFiles
, &file
, sizeof(file
)), false,
1622 ("Unable to allocate memory to merge %s\n", file
->fPath
));
1624 return_if(!DataAppendData(sMergeMetaClasses
, file
->fClassList
), false,
1625 ("Unable to allocate memory to merge %s\n", file
->fPath
));
1627 if (file
== sKernelFile
)
1628 sMergedKernel
= true;
1633 // Returns a pointer to the base of the section offset by the sections
1634 // base address. The offset is so that we can add nlist::n_values directly
1635 // to this address and get a valid pointer in our memory.
1636 static unsigned char *
1637 getSectionForSymbol(const struct fileRecord
*file
, const struct nlist
*symb
,
1640 const struct section
*section
;
1641 unsigned char sectind
;
1642 unsigned char *base
;
1644 sectind
= symb
->n_sect
; // Default to symbols section
1645 if ((symb
->n_type
& N_TYPE
) == N_ABS
&& !file
->fIsReloc
) {
1646 // Absolute symbol so we have to iterate over our sections
1647 for (sectind
= 1; sectind
<= file
->fNSects
; sectind
++) {
1648 unsigned long start
, end
;
1650 section
= file
->fSections
[sectind
- 1].fSection
;
1651 start
= section
->addr
;
1652 end
= start
+ section
->size
;
1653 if (start
<= symb
->n_value
&& symb
->n_value
< end
) {
1654 // Found the relevant section
1660 // Is the vtable in a valid section?
1661 return_if(sectind
== NO_SECT
|| sectind
> file
->fNSects
,
1662 (unsigned char *) -1,
1663 ("%s isn't a valid kext, bad section reference\n", file
->fPath
));
1665 section
= file
->fSections
[sectind
- 1].fSection
;
1667 // for when we start walking the vtable so compute offset's now.
1668 base
= file
->fMachO
+ section
->offset
;
1669 *endP
= (void **) (base
+ section
->size
);
1671 return base
- section
->addr
; // return with addr offset
1674 static Boolean
resolveKernelVTable(struct metaClassRecord
*metaClass
)
1676 const struct fileRecord
*file
;
1677 struct patchRecord
*patchedVTable
;
1678 void **curEntry
, **vtableEntries
, **endSection
;
1679 unsigned char *sectionBase
;
1680 struct patchRecord
*curPatch
;
1683 // Should never occur but it doesn't cost us anything to check.
1684 if (metaClass
->fPatchedVTable
)
1687 DEBUG_LOG(("Kernel vtable %s\n", metaClass
->fClassName
)); // @@@ gvdl:
1689 // Do we have a valid vtable to patch?
1690 return_if(!metaClass
->fVTableSym
,
1691 false, ("Internal error - no class vtable symbol?\n"));
1693 file
= metaClass
->fFile
;
1695 // If the metaClass we are being to ask is in the kernel then we
1696 // need to do a quick scan to grab the fPatchList in a reliable format
1697 // however we don't need to check the superclass in the kernel
1698 // as the kernel vtables are always correct wrt themselves.
1699 // Note this ends the superclass chain recursion.
1700 return_if(file
->fIsReloc
,
1701 false, ("Internal error - resolveKernelVTable is relocateable\n"));
1703 if (file
->fNoKernelExecutable
) {
1704 // Oh dear attempt to map the kernel's VM into my memory space
1705 return_if(file
->fNoKernelExecutable
, false,
1706 ("Internal error - fNoKernelExecutable not implemented yet\n"));
1709 // We are going to need the base and the end
1710 sectionBase
= getSectionForSymbol(file
, metaClass
->fVTableSym
, &endSection
);
1711 if (-1 == (long) sectionBase
)
1714 vtableEntries
= (void **) (sectionBase
+ metaClass
->fVTableSym
->n_value
);
1715 curEntry
= vtableEntries
+ kVTablePreambleLen
;
1716 for (classSize
= 0; curEntry
< endSection
&& *curEntry
; classSize
++)
1719 return_if(*curEntry
, false, ("Bad kernel image, short section\n"));
1721 patchedVTable
= (struct patchRecord
*)
1722 malloc((classSize
+ 1) * sizeof(struct patchRecord
));
1723 return_if(!patchedVTable
, false, ("resolveKernelVTable - no memory\n"));
1725 // Copy the vtable of this class into the patch table
1726 curPatch
= patchedVTable
;
1727 curEntry
= vtableEntries
+ kVTablePreambleLen
;
1728 for (; *curEntry
; curEntry
++, curPatch
++) {
1729 void * addr
= *curEntry
;
1732 addr
= (void *) OSSwapInt32((uint32_t) addr
);
1734 curPatch
->fSymbol
= (struct nlist
*)
1735 findSymbolByAddress(file
, addr
);
1736 if (curPatch
->fSymbol
)
1738 curPatch
->fType
= kSymbolLocal
;
1739 curPatch
->fFile
= file
;
1743 curPatch
->fSymbol
= (struct nlist
*)
1744 findSymbolByAddressInAllFiles(file
, addr
, &curPatch
->fFile
);
1745 if (!curPatch
->fSymbol
) {
1746 errprintf("%s: !findSymbolByAddressInAllFiles(%p)\n",
1750 curPatch
->fType
= kSymbolLocal
;
1754 // Tag the end of the patch vtable
1755 curPatch
->fSymbol
= NULL
;
1756 metaClass
->fPatchedVTable
= patchedVTable
;
1761 static const char *addNewString(struct fileRecord
*file
,
1762 const char *strname
, int namelen
)
1764 DataRef strings
= 0;
1767 namelen
++; // Include terminating '\0';
1769 // Make sure we have a string table as well for this symbol
1770 if (file
->fNewStringBlocks
) {
1771 DataRef
*blockTable
= (DataRef
*) DataGetPtr(file
->fNewStringBlocks
);
1772 int index
= DataGetLength(file
->fNewStringBlocks
) / sizeof(DataRef
*);
1773 strings
= blockTable
[index
- 1];
1774 if (DataRemaining(strings
) < namelen
)
1779 file
->fNewStringBlocks
= DataCreate(0);
1780 return_if(!file
->fNewStringBlocks
, NULL
,
1781 ("Unable to allocate new string table %s\n", file
->fPath
));
1785 int size
= (namelen
+ 1023) & ~1023;
1786 if (size
< 16 * 1024)
1788 strings
= DataCreate(size
);
1789 return_if(!strings
, NULL
,
1790 ("Unable to allocate new string block %s\n", file
->fPath
));
1792 !DataAppendBytes(file
->fNewStringBlocks
, &strings
, sizeof(strings
)),
1793 false, ("Unable to allocate string table for %s\n", file
->fPath
));
1796 newStr
= DataGetEndPtr(strings
);
1797 DataAppendBytes(strings
, strname
, namelen
);
1801 // reloc->fPatch must contain a valid pointer
1802 static struct nlist
*
1803 getNewSymbol(struct fileRecord
*file
,
1804 const struct relocRecord
*reloc
, const char *supername
)
1806 unsigned int size
, i
;
1809 struct relocation_info
*rinfo
;
1812 if (!file
->fNewSymbols
) {
1813 file
->fNewSymbols
= DataCreate(0);
1814 return_if(!file
->fNewSymbols
, NULL
,
1815 ("Unable to allocate new symbol table for %s\n", file
->fPath
));
1818 rinfo
= (struct relocation_info
*) reloc
->fRInfo
;
1819 size
= DataGetLength(file
->fNewSymbols
) / sizeof(struct nlist
*);
1820 sym
= (struct nlist
**) DataGetPtr(file
->fNewSymbols
);
1821 for (i
= 0; i
< size
; i
++, sym
++) {
1822 int symnum
= i
+ file
->fSymtab
->nsyms
;
1823 newStr
= symNameByIndex(file
, symnum
);
1824 if (!strcmp(newStr
, supername
)) {
1825 rinfo
->r_symbolnum
= symnum
;
1826 file
->fSymbolsDirty
= true;
1831 if (reloc
->fSymbol
->n_un
.n_strx
>= 0) {
1832 // This symbol has not been previously processed, so assert that it
1833 // is a valid non-local symbol. I need this condition to be true for
1834 // the later code to set to -1. Now, being the first time through,
1835 // I'd better make sure that n_sect is NO_SECT.
1837 return_if(reloc
->fSymbol
->n_sect
!= NO_SECT
, NULL
,
1838 ("Undefined symbol entry with non-zero section %s:%s\n",
1839 file
->fPath
, symbolname(file
, reloc
->fSymbol
)));
1841 // Mark the original symbol entry as having been processed.
1842 // This means that we wont attempt to create the symbol again
1843 // in the future if we come through a different path.
1844 ((struct nlist
*) reloc
->fSymbol
)->n_un
.n_strx
=
1845 -reloc
->fSymbol
->n_un
.n_strx
;
1847 // Mark the old symbol as being potentially deletable I can use the
1848 // n_sect field as the input symbol must be of type N_UNDF which means
1849 // that the n_sect field must be set to NO_SECT otherwise it is an
1850 // invalid input file.
1851 ((struct nlist
*) reloc
->fSymbol
)->n_sect
= (unsigned char) -1;
1854 // If we are here we didn't find the symbol so create a new one now
1855 msym
= (struct nlist
*) malloc(sizeof(struct nlist
));
1857 NULL
, ("Unable to create symbol table entry for %s", file
->fPath
));
1858 return_if(!DataAppendBytes(file
->fNewSymbols
, &msym
, sizeof(msym
)),
1859 NULL
, ("Unable to grow symbol table for %s\n", file
->fPath
));
1861 newStr
= addNewString(file
, supername
, strlen(supername
));
1865 // If we are here we didn't find the symbol so create a new one now
1866 return_if(!DataAppendBytes(file
->fSym2Strings
, &newStr
, sizeof(newStr
)),
1867 NULL
, ("Unable to grow symbol table for %s\n", file
->fPath
));
1868 file
->fSymbToStringTable
= (const char **) DataGetPtr(file
->fSym2Strings
);
1870 // Offset the string index by the original string table size
1871 // and negate the address to indicate that this is a 'new' symbol
1872 msym
->n_un
.n_strx
= -1;
1873 msym
->n_type
= (N_EXT
| N_UNDF
);
1874 msym
->n_sect
= NO_SECT
;
1876 msym
->n_value
= (unsigned long) newStr
;
1878 rinfo
->r_symbolnum
= i
+ file
->fSymtab
->nsyms
;
1879 file
->fSymbolsDirty
= true;
1883 static struct nlist
*
1884 fixOldSymbol(struct fileRecord
*file
,
1885 const struct relocRecord
*reloc
, const char *supername
)
1887 unsigned int namelen
;
1888 struct nlist
*sym
= (struct nlist
*) reloc
->fSymbol
;
1889 const char *oldname
= symbolname(file
, sym
);
1891 // assert(sym->n_un.n_strx >= 0);
1893 namelen
= strlen(supername
);
1895 sym
->n_un
.n_strx
= -sym
->n_un
.n_strx
;
1896 if (oldname
&& namelen
< strlen(oldname
))
1898 // Overwrite old string in string table
1899 strcpy((char *) oldname
, supername
);
1900 file
->fSymbolsDirty
= true;
1904 oldname
= addNewString(file
, supername
, namelen
);
1908 file
->fSymbToStringTable
[sym
- file
->fSymbolBase
] = oldname
;
1909 file
->fSymbolsDirty
= true;
1913 static enum patchState
1914 symbolCompare(const struct fileRecord
*file
,
1915 const struct nlist
*classsym
,
1916 const char *supername
)
1918 const char *classname
;
1921 // Check to see if the target function is locally defined
1922 // if it is then we can assume this is a local vtable override
1923 if ((classsym
->n_type
& N_TYPE
) != N_UNDF
)
1924 return kSymbolLocal
;
1926 // Check to see if both symbols point to the same symbol name
1927 // if so then we are still identical.
1928 classname
= symbolname(file
, classsym
);
1929 if (!strcmp(classname
, supername
))
1930 return kSymbolIdentical
;
1932 // We know that the target's vtable entry is different from the
1933 // superclass' vtable entry. This means that we will have to apply a
1934 // patch to the current entry, however before returning lets check to
1935 // see if we have a _RESERVEDnnn field 'cause we can use this as a
1936 // registration point that must align between vtables.
1937 if (strstr(supername
, kReservedNamePrefix
))
1938 return kSymbolMismatch
;
1940 // OK, we have a superclass difference where the superclass doesn't
1941 // reference a pad function so assume that the superclass is correct.
1942 if (strstr(classname
, kReservedNamePrefix
))
1943 return kSymbolPadUpdate
;
1945 return kSymbolSuperUpdate
;
1948 static Boolean
patchVTable(struct metaClassRecord
*metaClass
)
1950 struct metaClassRecord
*super
= NULL
;
1951 struct fileRecord
*file
;
1952 struct patchRecord
*patchedVTable
;
1953 struct relocRecord
**curReloc
, **vtableRelocs
, **endSection
;
1954 unsigned char *sectionBase
;
1957 // Should never occur but it doesn't cost us anything to check.
1958 if (metaClass
->fPatchedVTable
)
1961 // Do we have a valid vtable to patch?
1962 return_if(!metaClass
->fVTableSym
,
1963 false, ("Internal error - no class vtable symbol?\n"));
1965 file
= metaClass
->fFile
;
1967 if (!file
->fIsReloc
)
1969 // If the metaClass we are being to ask is already relocated then we
1970 // need to do a quick scan to grab the fPatchList in a reliable format
1971 // however we don't need to check the superclass in the already linked
1972 // modules as the vtables are always correct wrt themselves.
1973 // Note this ends the superclass chain recursion.
1975 res
= resolveKernelVTable(metaClass
);
1979 if (!metaClass
->fSuperName
)
1982 // The class isn't in the kernel so make sure that the super class
1983 // is patched before patching ouselves.
1984 super
= getClass(sMergeMetaClasses
, metaClass
->fSuperName
);
1985 return_if(!super
, false, ("Can't find superclass for %s : %s\n",
1986 metaClass
->fClassName
, metaClass
->fSuperName
));
1988 // Superclass recursion if necessary
1989 if (!super
->fPatchedVTable
) {
1991 res
= patchVTable(super
);
1996 DEBUG_LOG(("Patching %s\n", metaClass
->fClassName
)); // @@@ gvdl:
1998 // We are going to need the base and the end
2000 sectionBase
= getSectionForSymbol(file
,
2001 metaClass
->fVTableSym
, (void ***) &endSection
);
2002 if (-1 == (long) sectionBase
)
2005 vtableRelocs
= (struct relocRecord
**)
2006 (sectionBase
+ metaClass
->fVTableSym
->n_value
);
2007 curReloc
= vtableRelocs
+ kVTablePreambleLen
;
2008 for (classSize
= 0; curReloc
< endSection
&& *curReloc
; classSize
++)
2011 return_if(*curReloc
, false,
2012 ("%s isn't a valid kext, short section\n", file
->fPath
));
2014 patchedVTable
= (struct patchRecord
*)
2015 malloc((classSize
+ 1) * sizeof(struct patchRecord
));
2016 return_if(!patchedVTable
, false, ("patchedVTable - no memory\n"));
2019 struct patchRecord
*curPatch
;
2020 struct nlist
*symbol
;
2022 curPatch
= patchedVTable
;
2023 curReloc
= vtableRelocs
+ kVTablePreambleLen
;
2025 // Grab the super table patches if necessary
2026 // Can't be patching a kernel table as we don't walk super
2027 // class chains in the kernel symbol space.
2028 if (super
&& super
->fPatchedVTable
) {
2029 const struct patchRecord
*spp
;
2031 spp
= super
->fPatchedVTable
;
2033 for ( ; spp
->fSymbol
; curReloc
++, spp
++, curPatch
++) {
2034 const char *supername
=
2035 symbolname(spp
->fFile
, spp
->fSymbol
);
2037 symbol
= (struct nlist
*) (*curReloc
)->fSymbol
;
2039 curPatch
->fType
= symbolCompare(file
, symbol
, supername
);
2040 switch (curPatch
->fType
) {
2041 case kSymbolIdentical
:
2045 case kSymbolSuperUpdate
:
2046 symbol
= getNewSymbol(file
, (*curReloc
), supername
);
2049 case kSymbolPadUpdate
:
2050 symbol
= fixOldSymbol(file
, (*curReloc
), supername
);
2053 case kSymbolMismatch
:
2054 errprintf("%s is not compatible with its superclass, "
2055 "%s superclass changed?\n",
2056 metaClass
->fClassName
, super
->fClassName
);
2060 errprintf("Internal error - unknown patch type\n");
2064 curPatch
->fSymbol
= symbol
;
2065 (*curReloc
)->fSymbol
= symbol
;
2066 curPatch
->fFile
= file
;
2073 // Copy the remainder of this class' vtable into the patch table
2074 for (; *curReloc
; curReloc
++, curPatch
++) {
2075 // Local reloc symbols
2076 curPatch
->fType
= kSymbolLocal
;
2077 curPatch
->fSymbol
= (struct nlist
*) (*curReloc
)->fSymbol
;
2078 curPatch
->fFile
= file
;
2081 // Tag the end of the patch vtable
2082 curPatch
->fSymbol
= NULL
;
2084 metaClass
->fPatchedVTable
= patchedVTable
;
2090 free(patchedVTable
);
2095 static Boolean
growImage(struct fileRecord
*file
, vm_size_t delta
)
2098 file
->fMachOSize
+= delta
;
2099 return (file
->fMachO
+ file
->fMachOSize
<= file
->fPadEnd
);
2101 vm_address_t startMachO
, endMachO
, endMap
;
2102 vm_offset_t newMachO
;
2104 unsigned long i
, last
= 0;
2105 struct metaClassRecord
**classes
= NULL
;
2106 struct sectionRecord
*section
;
2109 startMachO
= (vm_address_t
) file
->fMachO
;
2110 endMachO
= startMachO
+ file
->fMachOSize
+ delta
;
2111 endMap
= (vm_address_t
) file
->fMap
+ file
->fMapSize
;
2113 // Do we have room in the current mapped image
2114 if (endMachO
< round_page_32(endMap
)) {
2115 file
->fMachOSize
+= delta
;
2119 newsize
= endMachO
- startMachO
;
2120 if (newsize
< round_page_32(file
->fMapSize
)) {
2121 DEBUG_LOG(("Growing image %s by moving\n", file
->fPath
));
2123 // We have room in the map if we shift the macho image within the
2124 // current map. We will have to patch up pointers into the object.
2125 newMachO
= (vm_offset_t
) file
->fMap
;
2126 bcopy((char *) startMachO
, (char *) newMachO
, file
->fMachOSize
);
2128 else if (file
->fIsKmem
) {
2129 // kmem_alloced mapping so we can try a kmem_realloc
2130 ret
= kmem_realloc(kernel_map
,
2131 (vm_address_t
) file
->fMap
,
2132 (vm_size_t
) file
->fMapSize
,
2135 if (KERN_SUCCESS
!= ret
)
2138 // If the mapping didn't move then just return
2139 if ((vm_address_t
) file
->fMap
== newMachO
) {
2140 file
->fMachOSize
= file
->fMapSize
= newsize
;
2144 DEBUG_LOG(("Growing image %s by reallocing\n", file
->fPath
));
2145 // We have relocated the kmem image so we are going to have to
2146 // move all of the pointers into the image around.
2149 DEBUG_LOG(("Growing image %s by allocating\n", file
->fPath
));
2150 // The image doesn't have room for us and I can't kmem_realloc
2151 // then I just have to bite the bullet and copy the object code
2152 // into a bigger memory segment
2153 ret
= kmem_alloc(kernel_map
, &newMachO
, newsize
);
2155 if (KERN_SUCCESS
!= ret
)
2157 bcopy((char *) startMachO
, (void *) newMachO
, file
->fMachOSize
);
2158 file
->fIsKmem
= true;
2162 file
->fMap
= file
->fMachO
= (unsigned char *) newMachO
;
2163 file
->fMapSize
= newsize
;
2164 file
->fMachOSize
+= delta
; // Increment the image size
2166 // If we are here then we have shifted the object image in memory
2167 // I really should change all of my pointers into the image to machO offsets
2168 // but I have run out of time. So I'm going to very quickly go over the
2169 // cached data structures and add adjustments to the addresses that are
2170 // affected. I wonder how long it will take me to get them all.
2172 // For every pointer into the MachO I need to add an adjustment satisfying
2173 // the following simultanous equations
2174 // addr_old = macho_old + fixed_offset
2175 // addr_new = macho_new + fixed_offset therefore:
2176 // addr_new = addr_old + (macho_new - macho_old)
2177 #define REBASE(addr, delta) ( ((vm_address_t) (addr)) += (delta) )
2178 delta
= newMachO
- startMachO
;
2180 // Rebase the cached-in object 'struct symtab_command' pointer
2181 REBASE(file
->fSymtab
, delta
);
2183 // Rebase the cached-in object 'struct nlist' pointer for all symbols
2184 REBASE(file
->fSymbolBase
, delta
);
2186 // Rebase the cached-in object 'struct nlist' pointer for local symbols
2187 REBASE(file
->fLocalSyms
, delta
);
2189 // Rebase the cached-in object 'char' pointer for the string table
2190 REBASE(file
->fStringBase
, delta
);
2192 // Ok now we have to go over all of the relocs one last time
2193 // to clean up the pad updates which had their string index negated
2194 // to indicate that we have finished with them.
2195 section
= file
->fSections
;
2196 for (i
= 0, last
= file
->fNSects
; i
< last
; i
++, section
++)
2197 REBASE(section
->fSection
, delta
);
2199 // We only ever grow images that contain class lists so dont bother
2200 // the check if file->fClassList is non-zero 'cause it can't be
2201 // assert(file->fClassList);
2202 last
= DataGetLength(file
->fClassList
)
2203 / sizeof(struct metaClassRecord
*);
2204 classes
= (struct metaClassRecord
**) DataGetPtr(file
->fClassList
);
2205 for (i
= 0; i
< last
; i
++) {
2206 struct patchRecord
*patch
;
2208 for (patch
= classes
[i
]->fPatchedVTable
; patch
->fSymbol
; patch
++) {
2209 vm_address_t symAddr
= (vm_address_t
) patch
->fSymbol
;
2211 // Only need to rebase if the symbol is part of the image
2212 // If this is a new symbol then it was independantly allocated
2213 if (symAddr
>= startMachO
&& symAddr
< endMachO
)
2214 REBASE(patch
->fSymbol
, delta
);
2218 // Finally rebase all of the string table pointers
2219 last
= file
->fSymtab
->nsyms
;
2220 for (i
= 0; i
< last
; i
++)
2221 REBASE(file
->fSymbToStringTable
[i
], delta
);
2230 // Note: This function is only called from kld_file_prepare_for_link()
2231 // This function can only operate on 32 bit mach-o files
2233 prepareFileForLink(struct fileRecord
*file
)
2235 unsigned long i
, last
, numnewsyms
, newsymsize
, newstrsize
;
2236 struct sectionRecord
*section
;
2237 struct nlist
**symp
, *sym
;
2238 DataRef newStrings
, *stringBlocks
;
2240 // If we didn't even do a pseudo 'relocate' and dirty the image
2241 // then we can just return now.
2242 if (!file
->fImageDirty
) {
2244 if (file
->fSwapped
) {
2245 kld_macho_unswap((struct mach_header
*) file
->fMachO
, file
->fSwapped
, false);
2246 file
->fSwapped
= false;
2252 DEBUG_LOG(("Linking 2 %s\n", file
->fPath
)); // @@@ gvdl:
2254 // We have to go over all of the relocs to repair the damage
2255 // that we have done to the image when we did our 'relocation'
2256 section
= file
->fSections
;
2257 for (i
= 0, last
= file
->fNSects
; i
< last
; i
++, section
++) {
2258 unsigned char *sectionBase
;
2259 struct relocRecord
*rec
;
2260 unsigned long j
, nreloc
;
2262 if (section
->fRelocCache
) {
2263 sectionBase
= file
->fMachO
+ section
->fSection
->offset
;
2264 nreloc
= section
->fSection
->nreloc
;
2265 rec
= (struct relocRecord
*) DataGetPtr(section
->fRelocCache
);
2267 // We will need to repair the reloc list
2268 for (j
= 0; j
< nreloc
; j
++, rec
++) {
2270 struct nlist
*repairSym
;
2272 // Repair Damage to object image
2273 entry
= (void **) (sectionBase
+ rec
->fRInfo
->r_address
);
2274 *entry
= rec
->fValue
;
2276 // Check if the symbol that this relocation entry points
2277 // to is marked as erasable
2278 repairSym
= (struct nlist
*) rec
->fSymbol
;
2279 if (repairSym
&& repairSym
->n_type
== (N_EXT
| N_UNDF
)
2280 && repairSym
->n_sect
== (unsigned char) -1) {
2281 // It is in use so we better clear the mark
2282 repairSym
->n_un
.n_strx
= -repairSym
->n_un
.n_strx
;
2283 repairSym
->n_sect
= NO_SECT
;
2287 // Clean up the fRelocCache we don't need it any more.
2288 DataRelease(section
->fRelocCache
);
2289 section
->fRelocCache
= 0;
2292 file
->fImageDirty
= false; // Image is clean
2294 // If we didn't dirty the symbol table then just return
2295 if (!file
->fSymbolsDirty
) {
2297 if (file
->fSwapped
) {
2298 kld_macho_unswap((struct mach_header
*) file
->fMachO
, file
->fSwapped
, false);
2299 file
->fSwapped
= false;
2305 // calculate total file size increase and check against padding
2306 if (file
->fNewSymbols
) {
2307 numnewsyms
= DataGetLength(file
->fNewSymbols
);
2308 symp
= (struct nlist
**) DataGetPtr(file
->fNewSymbols
);
2314 numnewsyms
/= sizeof(struct nlist
*);
2315 file
->fSymtab
->nsyms
+= numnewsyms
;
2317 // old sting size + 30% rounded up to nearest page
2318 newstrsize
= file
->fSymtab
->strsize
* 21 / 16;
2319 newstrsize
= (newstrsize
+ PAGE_MASK
) & ~PAGE_MASK
;
2320 newStrings
= DataCreate(newstrsize
);
2321 return_if(!newStrings
, false,
2322 ("Unable to allocate a copy aside buffer, no memory\n"));
2324 newsymsize
= numnewsyms
* sizeof(struct nlist
);
2325 file
->fStringBase
+= newsymsize
;
2326 file
->fSymtab
->stroff
+= newsymsize
;
2328 last
= file
->fSymtab
->nsyms
- numnewsyms
;
2330 DataAppendBytes(newStrings
, &newstrsize
, 4); // Leading nuls
2331 sym
= file
->fSymbolBase
;
2333 // Pre-compute an already offset new symbol pointer. The offset is the
2334 // orignal symbol table.
2336 for (i
= 0; i
< file
->fSymtab
->nsyms
; i
++, sym
++) {
2337 const char *str
= symNameByIndex(file
, i
);
2338 int len
= strlen(str
) + 1;
2341 // Rebase sym in the new symbol region
2345 if (sym
->n_un
.n_strx
< 0 && sym
->n_type
== (N_EXT
| N_UNDF
)
2346 && (unsigned char) -1 == sym
->n_sect
) {
2347 // after patching we find that this symbol is no longer in
2348 // use. So invalidate it by converting it into an N_ABS
2349 // symbol, remove the external bit and null out the name.
2350 bzero(sym
, sizeof(*sym
));
2351 sym
->n_type
= N_ABS
;
2354 // Repair the symbol for the getNewSymbol case.
2355 if (-1 == sym
->n_un
.n_strx
)
2358 // Record the offset of the string in the new table
2359 strx
= DataGetLength(newStrings
);
2360 return_if(!DataAppendBytes(newStrings
, str
, len
), false,
2361 ("Unable to append string, no memory\n"));
2363 sym
->n_un
.n_strx
= strx
;
2364 file
->fSymbToStringTable
[i
] = file
->fStringBase
+ strx
;
2368 // Don't need the new strings any more
2370 if (file
->fNewStringBlocks
){
2371 last
= DataGetLength(file
->fNewStringBlocks
) / sizeof(DataRef
);
2372 stringBlocks
= (DataRef
*) DataGetPtr(file
->fNewStringBlocks
);
2379 for (i
= 0; i
< last
; i
++)
2380 DataRelease(stringBlocks
[i
]);
2382 DataRelease(file
->fNewStringBlocks
);
2383 file
->fNewStringBlocks
= 0;
2385 newstrsize
= DataGetLength(newStrings
);
2386 newstrsize
= (newstrsize
+ 3) & ~3; // Round to nearest word
2388 !growImage(file
, newsymsize
+ newstrsize
- file
->fSymtab
->strsize
),
2389 false, ("Unable to patch the extension, no memory\n", file
->fPath
));
2391 // Push out the new symbol table if necessary
2395 // Append the new symbols to the original symbol table.
2396 base
= (caddr_t
) file
->fSymbolBase
2397 + (file
->fSymtab
->nsyms
- numnewsyms
) * sizeof(struct nlist
);
2398 symp
= (struct nlist
**) DataGetPtr(file
->fNewSymbols
);
2399 for (i
= 0; i
< numnewsyms
; i
++, base
+= sizeof(struct nlist
), symp
++)
2400 bcopy(*symp
, base
, sizeof(struct nlist
));
2402 DataRelease(file
->fNewSymbols
);
2403 file
->fNewSymbols
= 0;
2406 // Push out the new string table if necessary
2408 unsigned long *base
= (unsigned long *) file
->fStringBase
;
2409 unsigned long actuallen
= DataGetLength(newStrings
);
2411 // Set the last word in string table to zero before copying data
2412 base
[(newstrsize
/ sizeof(unsigned long)) - 1] = 0;
2414 // Now copy the new strings back to the end of the file
2415 bcopy((caddr_t
) DataGetPtr(newStrings
), file
->fStringBase
, actuallen
);
2417 file
->fSymtab
->strsize
= newstrsize
;
2419 DataRelease(newStrings
);
2422 file
->fSymbolsDirty
= false;
2424 if (file
->fSwapped
) {
2425 kld_macho_unswap((struct mach_header
*) file
->fMachO
, file
->fSwapped
, false);
2426 file
->fSwapped
= false;
2432 // This function can only operate on 32 bit mach-o files
2435 kld_file_map(const char *pathName
,
2440 kld_file_map(const char *pathName
)
2443 struct fileRecord file
, *fp
= 0;
2445 // Already done no need to repeat
2446 fp
= getFile(pathName
);
2450 bzero(&file
, sizeof(file
));
2454 file
.fMapSize
= mapSize
;
2455 file
.fIsKmem
= isKmem
;
2457 if (!mapObjectFile(&file
, pathName
))
2462 const struct machOMapping
{
2463 struct mach_header h
;
2464 struct load_command c
[1];
2466 const struct load_command
*cmd
;
2467 boolean_t lookVMRange
;
2470 if (!findBestArch(&file
, pathName
))
2473 machO
= (const struct machOMapping
*) file
.fMachO
;
2474 if (file
.fMachOSize
< machO
->h
.sizeofcmds
)
2477 // If the file type is MH_EXECUTE then this must be a kernel
2478 // as all Kernel extensions must be of type MH_OBJECT
2479 file
.fIsKernel
= (MH_EXECUTE
== machO
->h
.filetype
);
2481 for (i
= 0, cmd
= &machO
->c
[0], lookVMRange
= true; i
< machO
->h
.ncmds
; i
++) {
2482 if (cmd
->cmd
== LC_SYMTAB
)
2483 file
.fSymtab
= (struct symtab_command
*) cmd
;
2484 else if (cmd
->cmd
== LC_SEGMENT
) {
2485 struct segment_command
*seg
= (struct segment_command
*) cmd
;
2486 int nsects
= seg
->nsects
;
2489 if (!strcmp("__PRELINK", seg
->segname
))
2490 // segments following __PRELINK are going to move, so ignore them
2491 lookVMRange
= false;
2492 else if (!file
.fVMAddr
&& !file
.fVMEnd
) {
2493 file
.fVMAddr
= seg
->vmaddr
;
2494 file
.fVMEnd
= seg
->vmaddr
+ seg
->vmsize
;
2496 if (seg
->vmaddr
< file
.fVMAddr
)
2497 file
.fVMAddr
= seg
->vmaddr
;
2498 if ((seg
->vmaddr
+ seg
->vmsize
) > file
.fVMEnd
)
2499 file
.fVMEnd
= seg
->vmaddr
+ seg
->vmsize
;
2504 return_if(!parseSegments(&file
, seg
),
2505 false, ("%s isn't a valid mach-o, bad segment",
2508 if (file
.fIsKernel
) {
2510 // We don't need to look for the LinkEdit segment unless
2511 // we are running in the kernel environment.
2512 if (!strcmp(kLinkEditSegName
, seg
->segname
))
2513 file
.fLinkEditSeg
= seg
;
2517 cmd
= (struct load_command
*) ((UInt8
*) cmd
+ cmd
->cmdsize
);
2519 break_if(!file
.fSymtab
,
2520 ("%s isn't a valid mach-o, no symbols\n", pathName
));
2522 if (machO
->h
.flags
& MH_INCRLINK
) {
2524 file
.fIsIncrLink
= true;
2525 ((struct machOMapping
*) machO
)->h
.flags
&= ~MH_INCRLINK
;
2528 // the symtab fileoffset is the end of seg0's vmsize,
2529 // which can be (rarely) unaligned.
2531 align
= file
.fSymtab
->symoff
% sizeof(long);
2533 align
= sizeof(long) - align
;
2534 growImage(&file
, align
);
2535 bcopy(file
.fMachO
+ file
.fSymtab
->symoff
,
2536 file
.fMachO
+ file
.fSymtab
->symoff
+ align
,
2537 file
.fSymtab
->stroff
+ file
.fSymtab
->strsize
- file
.fSymtab
->symoff
);
2538 file
.fSymtab
->symoff
+= align
;
2539 file
.fSymtab
->stroff
+= align
;
2544 if (!parseSymtab(&file
, pathName
))
2547 fp
= addFile(&file
, pathName
);
2551 if (file
.fFoundOSObject
&& !getMetaClassGraph(fp
))
2558 // Automatically load the kernel's link edit segment if we are
2559 // attempting to load a driver.
2561 struct segment_command
*sg
;
2565 sg
= (struct segment_command
*) getsegbyname(kLinkEditSegName
);
2566 break_if(!sg
, ("Can't find kernel link edit segment\n"));
2568 kernelSize
= sg
->vmaddr
+ sg
->vmsize
- (size_t) &_mh_execute_header
;
2569 ret
= kld_file_map(kld_basefile_name
,
2570 (unsigned char *) &_mh_execute_header
, kernelSize
,
2571 /* isKmem */ false);
2572 break_if(!ret
, ("kld can't map kernel file"));
2579 // Failure path, then clean up
2581 // @@@ gvdl: for the time being leak the file ref in the file table
2589 void *kld_file_getaddr(const char *pathName
, long *size
)
2591 struct fileRecord
*file
= getFile(pathName
);
2597 *size
= file
->fMachOSize
;
2599 return file
->fMachO
;
2602 void *kld_file_lookupsymbol(const char *pathName
, const char *symname
)
2604 struct fileRecord
*file
= getFile(pathName
);
2605 const struct nlist
*sym
;
2606 const struct section
*section
;
2607 unsigned char *sectionBase
;
2608 unsigned char sectind
;
2611 NULL
, ("Unknown file %s\n", pathName
));
2613 sym
= findSymbolByName(file
, symname
);
2615 // May be a non-extern symbol so look for it there
2617 unsigned int i
, nsyms
;
2619 sym
= file
->fSymbolBase
;
2620 for (i
= 0, nsyms
= file
->fSymtab
->nsyms
; i
< nsyms
; i
++, sym
++) {
2621 if ( (sym
->n_type
& N_EXT
) ) {
2623 break; // Terminate search when we hit an extern
2625 if ( (sym
->n_type
& N_STAB
) )
2627 if ( !strcmp(symname
, symNameByIndex(file
, i
)) )
2633 NULL
, ("Unknown symbol %s in %s\n", symname
, pathName
));
2635 // Is the vtable in a valid section?
2636 sectind
= sym
->n_sect
;
2637 return_if(sectind
== NO_SECT
|| sectind
> file
->fNSects
, NULL
,
2638 ("Malformed object file, invalid section reference for %s in %s\n",
2639 symname
, pathName
));
2641 section
= file
->fSections
[sectind
- 1].fSection
;
2642 sectionBase
= file
->fMachO
+ section
->offset
- section
->addr
;
2644 return (void *) (sectionBase
+ sym
->n_value
);
2647 Boolean
kld_file_merge_OSObjects(const char *pathName
)
2649 struct fileRecord
*file
= getFile(pathName
);
2652 false, ("Internal error - unable to find file %s\n", pathName
));
2654 return mergeOSObjectsForFile(file
);
2657 Boolean
kld_file_patch_OSObjects(const char *pathName
)
2659 struct fileRecord
*file
= getFile(pathName
);
2660 struct metaClassRecord
**classes
;
2661 unsigned long i
, last
;
2664 false, ("Internal error - unable to find file %s\n", pathName
));
2666 DEBUG_LOG(("Patch file %s\n", pathName
)); // @@@ gvdl:
2668 // If we don't have any classes we can return now.
2669 if (!file
->fClassList
)
2672 // If we haven't alread merged the kernel then do it now
2673 if (!sMergedKernel
&& sKernelFile
)
2674 mergeOSObjectsForFile(sKernelFile
);
2675 return_if(!sMergedKernel
, false, ("Internal error no kernel?\n"));
2677 if (!mergeOSObjectsForFile(file
))
2680 // Patch all of the classes in this executable
2681 last
= DataGetLength(file
->fClassList
) / sizeof(void *);
2682 classes
= (struct metaClassRecord
**) DataGetPtr(file
->fClassList
);
2683 for (i
= 0; i
< last
; i
++) {
2684 if (!patchVTable(classes
[i
])) {
2685 // RY: Set a flag in the file list to invalidate this data.
2686 // I would remove the file from the list, but that seems to be
2687 // not worth the effort.
2688 file
->fIgnoreFile
= TRUE
;
2697 Boolean
kld_file_prepare_for_link(void)
2700 unsigned long i
, nmerged
= 0;
2701 struct fileRecord
**files
;
2703 // Check to see if we have already merged this file
2704 nmerged
= DataGetLength(sMergedFiles
) / sizeof(struct fileRecord
*);
2705 files
= (struct fileRecord
**) DataGetPtr(sMergedFiles
);
2706 for (i
= 0; i
< nmerged
; i
++) {
2707 if (!files
[i
]->fIgnoreFile
&& !prepareFileForLink(files
[i
]))
2712 // Clear down the meta class table and merged file lists
2713 DataRelease(sMergeMetaClasses
);
2714 DataRelease(sMergedFiles
);
2715 sMergedFiles
= sMergeMetaClasses
= NULL
;
2716 sMergedKernel
= false;
2721 void kld_file_cleanup_all_resources(void)
2723 unsigned long i
, nfiles
;
2725 #if KERNEL // @@@ gvdl:
2726 // Debugger("kld_file_cleanup_all_resources");
2729 if (!sFilesTable
|| !(nfiles
= DataGetLength(sFilesTable
)))
2730 return; // Nothing to do just return now
2732 nfiles
/= sizeof(struct fileRecord
*);
2733 for (i
= 0; i
< nfiles
; i
++)
2734 removeFile(((void **) DataGetPtr(sFilesTable
))[i
]);
2736 DataRelease(sFilesTable
);
2739 // Don't really have to clean up anything more as the whole
2740 // malloc engine is going to be released and I couldn't be bothered.
2746 static const struct fileRecord
*sortFile
;
2747 static int symCompare(const void *vSym1
, const void *vSym2
)
2749 const struct nlist
*sym1
= vSym1
;
2750 const struct nlist
*sym2
= vSym2
;
2753 unsigned int ind1
, ind2
;
2755 ind1
= sym1
->n_type
& N_TYPE
;
2756 ind2
= sym2
->n_type
& N_TYPE
;
2758 // if sym1 is undefined then sym1 must come later than sym2
2761 // if sym2 is undefined then sym1 must come earlier than sym2
2764 /* drop out if neither are undefined */
2769 const struct fileRecord
*file
= sortFile
;
2770 const char *name1
, *name2
;
2772 name1
= file
->fStringBase
+ sym1
->n_un
.n_strx
;
2773 name2
= file
->fStringBase
+ sym2
->n_un
.n_strx
;
2774 return strcmp(name1
, name2
);
2779 Boolean
kld_file_debug_dump(const char *pathName
, const char *outName
)
2781 const struct fileRecord
*file
= getFile(pathName
);
2783 Boolean ret
= false;
2785 return_if(!file
, false, ("Unknown file %s for dumping\n", pathName
));
2787 fd
= open(outName
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0666);
2788 return_if(-1 == fd
, false, ("Can't create output file %s - %s(%d)\n",
2789 outName
, strerror(errno
), errno
));
2793 // Sorting doesn't work until I fix the relocs too?
2795 // sort the symbol table appropriately
2796 unsigned int nsyms
= file
->fSymtab
->nsyms
2797 - (file
->fLocalSyms
- file
->fSymbolBase
);
2799 heapsort((void *) file
->fLocalSyms
, nsyms
, sizeof(struct nlist
),
2803 break_if(-1 == write(fd
, file
->fMachO
, file
->fMachOSize
),
2804 ("Can't dump output file %s - %s(%d)\n",
2805 outName
, strerror(errno
), errno
));
2814 #endif /* !KERNEL */